2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * FILE: lib/kernel32/process/create.c
5 * PURPOSE: Process functions
6 * PROGRAMMER: Alex Ionescu (alex@relsoft.net)
7 * Ariadne ( ariadne@xs4all.nl)
10 /* INCLUDES ****************************************************************/
15 #include "../include/debug.h"
17 #define CMD_STRING L"cmd /c "
19 extern __declspec(noreturn
)
22 ConsoleControlDispatcher(DWORD CodeAndFlag
);
24 /* INTERNAL FUNCTIONS *******************************************************/
26 _SEH_FILTER(BaseExceptionFilter
)
28 EXCEPTION_POINTERS
*ExceptionInfo
= _SEH_GetExceptionPointers();
29 LONG ExceptionDisposition
= EXCEPTION_EXECUTE_HANDLER
;
31 if (GlobalTopLevelExceptionFilter
!= NULL
)
35 ExceptionDisposition
= GlobalTopLevelExceptionFilter(ExceptionInfo
);
39 ExceptionDisposition
= UnhandledExceptionFilter(ExceptionInfo
);
44 return ExceptionDisposition
;
49 BaseProcessStartup(PPROCESS_START_ROUTINE lpStartAddress
)
53 DPRINT("BaseProcessStartup(..) - setting up exception frame.\n");
57 /* Set our Start Address */
58 NtSetInformationThread(NtCurrentThread(),
59 ThreadQuerySetWin32StartAddress
,
61 sizeof(PPROCESS_START_ROUTINE
));
63 /* Call the Start Routine */
64 uExitCode
= (lpStartAddress
)();
66 _SEH_EXCEPT(BaseExceptionFilter
)
68 /* Get the SEH Error */
69 uExitCode
= _SEH_GetExceptionCode();
73 /* Exit the Process with our error */
74 ExitProcess(uExitCode
);
78 * Tells CSR that a new process was created
82 BasepNotifyCsrOfCreation(ULONG dwCreationFlags
,
84 IN ULONG SubsystemType
,
85 OUT PHANDLE ConsoleHandle
,
86 OUT PHANDLE InputHandle
,
87 OUT PHANDLE OutputHandle
)
89 ULONG Request
= CREATE_PROCESS
;
90 CSR_API_MESSAGE CsrRequest
;
93 DPRINT("BasepNotifyCsrOfCreation\n");
95 /* Some hacks (heck, this whole API is a hack) */
96 if (SubsystemType
== IMAGE_SUBSYSTEM_WINDOWS_GUI
)
98 dwCreationFlags
= (dwCreationFlags
&~ CREATE_NEW_CONSOLE
) |
101 else if (SubsystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
103 dwCreationFlags
|= CREATE_NEW_CONSOLE
;
106 /* Fill out the request */
107 CsrRequest
.Data
.CreateProcessRequest
.NewProcessId
= ProcessId
;
108 CsrRequest
.Data
.CreateProcessRequest
.Flags
= dwCreationFlags
;
109 CsrRequest
.Data
.CreateProcessRequest
.CtrlDispatcher
= ConsoleControlDispatcher
;
110 CsrRequest
.Data
.CreateProcessRequest
.InputHandle
= 0;
111 CsrRequest
.Data
.CreateProcessRequest
.OutputHandle
= 0;
112 CsrRequest
.Data
.CreateProcessRequest
.Console
= 0;
115 Status
= CsrClientCallServer(&CsrRequest
,
117 MAKE_CSR_API(Request
, CSR_NATIVE
),
118 sizeof(CSR_API_MESSAGE
));
119 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
121 DPRINT1("Failed to tell csrss about new process\n");
122 return CsrRequest
.Status
;
125 *ConsoleHandle
= CsrRequest
.Data
.CreateProcessRequest
.Console
;
126 *InputHandle
= CsrRequest
.Data
.CreateProcessRequest
.InputHandle
;
127 *OutputHandle
= CsrRequest
.Data
.CreateProcessRequest
.OutputHandle
;
128 DPRINT("CSR Created: %lx %lx\n", *InputHandle
, *OutputHandle
);
131 return STATUS_SUCCESS
;
135 * Creates the first Thread in a Proces
139 BasepCreateFirstThread(HANDLE ProcessHandle
,
140 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
141 PSECTION_IMAGE_INFORMATION SectionImageInfo
,
144 OBJECT_ATTRIBUTES LocalObjectAttributes
;
145 POBJECT_ATTRIBUTES ObjectAttributes
;
147 INITIAL_TEB InitialTeb
;
151 DPRINT("BasepCreateFirstThread. hProcess: %lx\n", ProcessHandle
);
153 /* Create the Thread's Stack */
154 BasepCreateStack(ProcessHandle
,
155 SectionImageInfo
->MaximumStackSize
,
156 SectionImageInfo
->CommittedStackSize
,
159 /* Create the Thread's Context */
160 BasepInitializeContext(&Context
,
162 SectionImageInfo
->TransferAddress
,
163 InitialTeb
.StackBase
,
166 /* Convert the thread attributes */
167 ObjectAttributes
= BasepConvertObjectAttributes(&LocalObjectAttributes
,
171 /* Create the Kernel Thread Object */
172 Status
= NtCreateThread(&hThread
,
186 * Converts ANSI to Unicode Environment
190 BasepConvertUnicodeEnvironment(IN PVOID lpEnvironment
)
195 UNICODE_STRING UnicodeEnv
;
198 DPRINT("BasepConvertUnicodeEnvironment\n");
200 /* Scan the environment to calculate its Unicode size */
201 AnsiEnv
.Buffer
= pcScan
= lpEnvironment
;
202 while (*pcScan
) while (*pcScan
++);
204 /* Create our ANSI String */
205 AnsiEnv
.Length
= (ULONG_PTR
)pcScan
- (ULONG_PTR
)lpEnvironment
+ 1;
206 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ 1;
208 /* Allocate memory for the Unicode Environment */
209 UnicodeEnv
.Buffer
= NULL
;
210 EnvSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
211 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
212 (PVOID
)&UnicodeEnv
.Buffer
,
218 if (!NT_SUCCESS(Status
))
220 SetLastError(Status
);
224 /* Use the allocated size */
225 UnicodeEnv
.MaximumLength
= EnvSize
;
228 RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
229 return UnicodeEnv
.Buffer
;
233 * Converts a Win32 Priority Class to NT
237 BasepConvertPriorityClass(IN ULONG dwCreationFlags
)
241 if(dwCreationFlags
& IDLE_PRIORITY_CLASS
)
243 ReturnClass
= PROCESS_PRIORITY_CLASS_IDLE
;
245 else if(dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
247 ReturnClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
249 else if(dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
251 ReturnClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
253 else if(dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
255 ReturnClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
257 else if(dwCreationFlags
& HIGH_PRIORITY_CLASS
)
259 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
261 else if(dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
263 /* Check for Privilege First */
264 if (BasepCheckRealTimePrivilege())
266 ReturnClass
= PROCESS_PRIORITY_CLASS_REALTIME
;
270 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
275 ReturnClass
= 0 /* FIXME */;
282 * Duplicates a standard handle and writes it where requested.
286 BasepDuplicateAndWriteHandle(IN HANDLE ProcessHandle
,
287 IN HANDLE StandardHandle
,
291 HANDLE DuplicatedHandle
;
294 DPRINT("BasepDuplicateAndWriteHandle. hProcess: %lx, Handle: %lx,"
295 "Address: %p\n", ProcessHandle
, StandardHandle
, Address
);
297 /* Don't touch Console Handles */
298 if (IsConsoleHandle(StandardHandle
)) return;
300 /* Duplicate the handle */
301 Status
= NtDuplicateObject(NtCurrentProcess(),
305 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
,
308 if (NT_SUCCESS(Status
))
311 NtWriteVirtualMemory(ProcessHandle
,
321 BasepGetDllPath(LPWSTR FullPath
,
324 /* FIXME: Not yet implemented */
330 BasepCopyHandles(IN PRTL_USER_PROCESS_PARAMETERS Params
,
331 IN PRTL_USER_PROCESS_PARAMETERS PebParams
,
332 IN BOOL InheritHandles
)
334 /* Copy the handle if we are inheriting or if it's a console handle */
335 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardInput
))
337 Params
->StandardInput
= PebParams
->StandardInput
;
339 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardOutput
))
341 Params
->StandardOutput
= PebParams
->StandardOutput
;
343 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardError
))
345 Params
->StandardError
= PebParams
->StandardError
;
351 BasepInitializeEnvironment(HANDLE ProcessHandle
,
353 LPWSTR ApplicationPathName
,
354 LPWSTR lpCurrentDirectory
,
355 LPWSTR lpCommandLine
,
357 LPSTARTUPINFOW StartupInfo
,
363 WCHAR FullPath
[MAX_PATH
];
365 LPWSTR DllPathString
;
366 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
;
367 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
= NULL
;
368 UNICODE_STRING DllPath
, ImageName
, CommandLine
, CurrentDirectory
;
374 UNICODE_STRING Desktop
, Shell
, Runtime
, Title
;
375 PPEB OurPeb
= NtCurrentPeb();
377 DPRINT("BasepInitializeEnvironment\n");
379 /* Get the full path name */
380 RetVal
= GetFullPathNameW(ApplicationPathName
,
384 DPRINT("ApplicationPathName: %S, FullPath: %S\n", ApplicationPathName
,
387 /* Get the DLL Path */
388 DllPathString
= BasepGetDllPath(FullPath
, Environment
);
390 /* Initialize Strings */
391 RtlInitUnicodeString(&DllPath
, DllPathString
);
392 RtlInitUnicodeString(&ImageName
, FullPath
);
393 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
394 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
396 /* Initialize more Strings from the Startup Info */
397 if (StartupInfo
->lpDesktop
)
399 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
403 RtlInitUnicodeString(&Desktop
, L
"");
405 if (StartupInfo
->lpReserved
)
407 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
411 RtlInitUnicodeString(&Shell
, L
"");
413 if (StartupInfo
->lpTitle
)
415 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
419 RtlInitUnicodeString(&Title
, L
"");
422 /* This one is special because the length can differ */
423 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
424 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
426 /* Create the Parameter Block */
427 DPRINT("Creating Process Parameters: %wZ %wZ %wZ %wZ %wZ %wZ %wZ\n",
428 &ImageName
, &DllPath
, &CommandLine
, &Desktop
, &Title
, &Shell
,
430 Status
= RtlCreateProcessParameters(&ProcessParameters
,
434 &CurrentDirectory
: NULL
,
442 if (!NT_SUCCESS(Status
))
444 DPRINT1("Failed to create process parameters!\n");
448 /* Check if we got an environment. If not, use ours */
451 /* Save pointer and start lookup */
452 Environment
= ScanChar
= ProcessParameters
->Environment
;
456 /* Save pointer and start lookup */
457 Environment
= ScanChar
= OurPeb
->ProcessParameters
->Environment
;
460 /* Find the environment size */
463 while (*ScanChar
) while (*ScanChar
++);
465 /* Calculate the size of the block */
466 EnviroSize
= (ULONG
)((ULONG_PTR
)ScanChar
- (ULONG_PTR
)Environment
);
467 DPRINT("EnvironmentSize %ld\n", EnviroSize
);
469 /* Allocate and Initialize new Environment Block */
471 ProcessParameters
->Environment
= NULL
;
472 Status
= ZwAllocateVirtualMemory(ProcessHandle
,
473 (PVOID
*)&ProcessParameters
->Environment
,
478 if (!NT_SUCCESS(Status
))
480 DPRINT1("Failed to allocate Environment Block\n");
484 /* Write the Environment Block */
485 ZwWriteVirtualMemory(ProcessHandle
,
486 ProcessParameters
->Environment
,
492 /* Write new parameters */
493 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
494 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
495 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
496 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
497 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
498 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
499 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
500 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
501 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
503 /* Write the handles only if we have to */
504 if (StartupInfo
->dwFlags
& STARTF_USESTDHANDLES
)
506 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
507 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
508 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
511 /* Use Special Flags for ConDllInitialize in Kernel32 */
512 if (CreationFlags
& DETACHED_PROCESS
)
514 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
516 else if (CreationFlags
& CREATE_NO_WINDOW
)
518 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
520 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
522 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
526 /* Inherit our Console Handle */
527 ProcessParameters
->ConsoleHandle
= OurPeb
->ProcessParameters
->ConsoleHandle
;
529 /* Is the shell trampling on our Handles? */
530 if (!(StartupInfo
->dwFlags
&
531 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
533 /* Use handles from PEB, if inheriting or they are console */
534 BasepCopyHandles(ProcessParameters
,
535 OurPeb
->ProcessParameters
,
540 /* Also set the Console Flag */
541 if (CreationFlags
& CREATE_NEW_PROCESS_GROUP
)
543 ProcessParameters
->ConsoleFlags
= 1;
546 /* Allocate memory for the parameter block */
547 Size
= ProcessParameters
->Length
;
548 Status
= NtAllocateVirtualMemory(ProcessHandle
,
549 (PVOID
*)&RemoteParameters
,
554 if (!NT_SUCCESS(Status
))
556 DPRINT1("Failed to allocate Parameters Block\n");
560 /* Set the allocated size */
561 ProcessParameters
->MaximumLength
= Size
;
563 /* Handle some Parameter Flags */
564 ProcessParameters
->ConsoleFlags
= (CreationFlags
& CREATE_NEW_PROCESS_GROUP
);
565 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
566 PPF_PROFILE_USER
: 0;
567 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
568 PPF_PROFILE_KERNEL
: 0;
569 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
570 PPF_PROFILE_SERVER
: 0;
571 ProcessParameters
->Flags
|= (NtCurrentPeb()->ProcessParameters
->Flags
&
572 PPF_DISABLE_HEAP_CHECKS
);
575 * FIXME: Our console init stuff is messy. See my comment in kernel32's
578 if (!ProcessParameters
->StandardInput
) ProcessParameters
->StandardInput
= hInput
;
579 if (!ProcessParameters
->StandardOutput
) ProcessParameters
->StandardOutput
= hOutput
;
580 if (!ProcessParameters
->StandardError
) ProcessParameters
->StandardError
= hOutput
;
582 /* Write the Parameter Block */
583 Status
= NtWriteVirtualMemory(ProcessHandle
,
586 ProcessParameters
->Length
,
589 /* Write the PEB Pointer */
590 Status
= NtWriteVirtualMemory(ProcessHandle
,
591 &Peb
->ProcessParameters
,
597 RtlFreeHeap(GetProcessHeap(), 0, DllPath
.Buffer
);
598 RtlDestroyProcessParameters(ProcessParameters
);
600 DPRINT("Completed\n");
601 return STATUS_SUCCESS
;
604 /* FUNCTIONS ****************************************************************/
607 * FUNCTION: The CreateProcess function creates a new process and its
608 * primary thread. The new process executes the specified executable file
611 * lpApplicationName = Pointer to name of executable module
612 * lpCommandLine = Pointer to command line string
613 * lpProcessAttributes = Process security attributes
614 * lpThreadAttributes = Thread security attributes
615 * bInheritHandles = Handle inheritance flag
616 * dwCreationFlags = Creation flags
617 * lpEnvironment = Pointer to new environment block
618 * lpCurrentDirectory = Pointer to current directory name
619 * lpStartupInfo = Pointer to startup info
620 * lpProcessInformation = Pointer to process information
626 CreateProcessA(LPCSTR lpApplicationName
,
628 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
629 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
630 BOOL bInheritHandles
,
631 DWORD dwCreationFlags
,
632 LPVOID lpEnvironment
,
633 LPCSTR lpCurrentDirectory
,
634 LPSTARTUPINFOA lpStartupInfo
,
635 LPPROCESS_INFORMATION lpProcessInformation
)
637 PUNICODE_STRING CommandLine
= NULL
;
638 UNICODE_STRING DummyString
;
639 UNICODE_STRING LiveCommandLine
;
640 UNICODE_STRING ApplicationName
;
641 UNICODE_STRING CurrentDirectory
;
643 STARTUPINFOW StartupInfo
;
645 DPRINT("dwCreationFlags %x, lpEnvironment %x, lpCurrentDirectory %x, "
646 "lpStartupInfo %x, lpProcessInformation %x\n",
647 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
648 lpStartupInfo
, lpProcessInformation
);
650 /* Copy Startup Info */
651 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
653 /* Initialize all strings to nothing */
654 LiveCommandLine
.Buffer
= NULL
;
655 DummyString
.Buffer
= NULL
;
656 ApplicationName
.Buffer
= NULL
;
657 CurrentDirectory
.Buffer
= NULL
;
658 StartupInfo
.lpDesktop
= NULL
;
659 StartupInfo
.lpReserved
= NULL
;
660 StartupInfo
.lpTitle
= NULL
;
662 /* Convert the Command line */
665 /* If it's too long, then we'll have a problem */
666 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
667 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
669 /* Cache it in the TEB */
670 CommandLine
= Basep8BitStringToCachedUnicodeString(lpCommandLine
);
674 /* Use a dynamic version */
675 Basep8BitStringToLiveUnicodeString(&LiveCommandLine
,
681 /* The logic below will use CommandLine, so we must make it valid */
682 CommandLine
= &DummyString
;
685 /* Convert the Name and Directory */
686 if (lpApplicationName
)
688 Basep8BitStringToLiveUnicodeString(&ApplicationName
,
691 if (lpCurrentDirectory
)
693 Basep8BitStringToLiveUnicodeString(&CurrentDirectory
,
697 /* Now convert Startup Strings */
698 if (lpStartupInfo
->lpReserved
)
700 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
701 &StartupInfo
.lpReserved
);
703 if (lpStartupInfo
->lpDesktop
)
705 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
706 &StartupInfo
.lpDesktop
);
708 if (lpStartupInfo
->lpTitle
)
710 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
711 &StartupInfo
.lpTitle
);
714 /* Call the Unicode function */
715 bRetVal
= CreateProcessW(ApplicationName
.Buffer
,
716 LiveCommandLine
.Buffer
?
717 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
723 CurrentDirectory
.Buffer
,
725 lpProcessInformation
);
728 RtlFreeUnicodeString(&ApplicationName
);
729 RtlFreeUnicodeString(&LiveCommandLine
);
730 RtlFreeUnicodeString(&CurrentDirectory
);
731 RtlFreeHeap(GetProcessHeap(), 0, StartupInfo
.lpDesktop
);
732 RtlFreeHeap(GetProcessHeap(), 0, StartupInfo
.lpReserved
);
733 RtlFreeHeap(GetProcessHeap(), 0, StartupInfo
.lpTitle
);
735 /* Return what Unicode did */
744 CreateProcessW(LPCWSTR lpApplicationName
,
745 LPWSTR lpCommandLine
,
746 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
747 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
748 BOOL bInheritHandles
,
749 DWORD dwCreationFlags
,
750 LPVOID lpEnvironment
,
751 LPCWSTR lpCurrentDirectory
,
752 LPSTARTUPINFOW lpStartupInfo
,
753 LPPROCESS_INFORMATION lpProcessInformation
)
756 PROCESS_PRIORITY_CLASS PriorityClass
;
757 BOOLEAN FoundQuotes
= FALSE
;
758 BOOLEAN QuotesNeeded
= FALSE
;
759 BOOLEAN CmdLineIsAppName
= FALSE
;
760 UNICODE_STRING ApplicationName
;
761 OBJECT_ATTRIBUTES LocalObjectAttributes
;
762 POBJECT_ATTRIBUTES ObjectAttributes
;
763 HANDLE hSection
, hProcess
, hThread
;
764 SECTION_IMAGE_INFORMATION SectionImageInfo
;
765 LPWSTR CurrentDirectory
= NULL
;
766 LPWSTR CurrentDirectoryPart
;
767 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
768 STARTUPINFOW StartupInfo
;
770 LPWSTR BatchCommandLine
;
772 UNICODE_STRING CommandLineString
;
775 LPWSTR QuotedCmdLine
= NULL
;
778 LPWSTR NameBuffer
= NULL
;
782 BOOLEAN SearchDone
= FALSE
;
783 HANDLE hConsole
, hInput
, hOutput
;
785 PPEB OurPeb
= NtCurrentPeb();
788 DPRINT("CreateProcessW: lpApplicationName: %S lpCommandLine: %S"
789 " lpEnvironment: %p lpCurrentDirectory: %S dwCreationFlags: %lx\n",
790 lpApplicationName
, lpCommandLine
, lpEnvironment
, lpCurrentDirectory
,
793 /* Flags we don't handle yet */
794 if (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
)
796 DPRINT1("CREATE_SEPARATE_WOW_VDM not handled\n");
798 if (dwCreationFlags
& CREATE_SHARED_WOW_VDM
)
800 DPRINT1("CREATE_SHARED_WOW_VDM not handled\n");
802 if (dwCreationFlags
& CREATE_FORCEDOS
)
804 DPRINT1("CREATE_FORCEDOS not handled\n");
807 /* Fail on this flag, it's only valid with the WithLogonW function */
808 if (dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
)
810 DPRINT1("Invalid flag used\n");
811 SetLastError(ERROR_INVALID_PARAMETER
);
815 /* This combination is illegal (see MSDN) */
816 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
817 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
819 DPRINT1("Invalid flag combo used\n");
820 SetLastError(ERROR_INVALID_PARAMETER
);
824 /* Another illegal combo */
825 if ((dwCreationFlags
& (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
)) ==
826 (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
))
828 DPRINT1("Invalid flag combo used\n");
829 SetLastError(ERROR_INVALID_PARAMETER
);
834 * We're going to modify and mask out flags and stuff in lpStartupInfo,
835 * so we'll use our own local copy for that.
837 StartupInfo
= *lpStartupInfo
;
839 /* FIXME: Use default Separate/Shared VDM Flag */
841 /* If we are inside a Job, use Separate VDM so it won't escape the Job */
842 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
844 if (NtIsProcessInJob(NtCurrentProcess(), NULL
))
846 /* Remove the shared flag and add the separate flag. */
847 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
848 CREATE_SEPARATE_WOW_VDM
;
853 * According to some sites, ShellExecuteEx uses an undocumented flag to
854 * send private handle data (such as HMONITOR or HICON). See:
855 * www.catch22.net/tuts/undoc01.asp. This implies that we can't use the
856 * standard handles anymore since we'd be overwriting this private data
858 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
859 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
861 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
864 /* Start by zeroing out the fields */
865 RtlZeroMemory(lpProcessInformation
, sizeof(PROCESS_INFORMATION
));
867 /* Easy stuff first, convert the process priority class */
868 PriorityClass
.Foreground
= FALSE
;
869 PriorityClass
.PriorityClass
= BasepConvertPriorityClass(dwCreationFlags
);
871 /* Convert the environment */
872 if(lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
874 lpEnvironment
= BasepConvertUnicodeEnvironment(lpEnvironment
);
875 if (!lpEnvironment
) return FALSE
;
878 /* Get the application name and do all the proper formating necessary */
880 /* See if we have an application name (oh please let us have one!) */
881 if (!lpApplicationName
)
884 NameBuffer
= RtlAllocateHeap(GetProcessHeap(),
886 MAX_PATH
* sizeof(WCHAR
));
888 /* This is all we have to work with :( */
889 lpApplicationName
= lpCommandLine
;
891 /* Initialize our friends at the beginning */
892 NullBuffer
= (LPWSTR
)lpApplicationName
;
893 ScanString
= (LPWSTR
)lpApplicationName
;
895 /* We will start by looking for a quote */
896 if (*ScanString
== L
'\"')
901 /* Advance past quote */
903 lpApplicationName
= ScanString
;
905 /* Find the closing quote */
908 if (*ScanString
== L
'\"')
911 NullBuffer
= ScanString
;
918 NullBuffer
= ScanString
;
923 /* No quotes, so we'll be looking for white space */
925 /* Reset the pointer */
926 lpApplicationName
= lpCommandLine
;
928 /* Find whitespace of Tab */
931 if (*ScanString
== ' ' || *ScanString
== '\t')
934 NullBuffer
= ScanString
;
940 NullBuffer
= ScanString
;
944 /* Set the Null Buffer */
945 SaveChar
= *NullBuffer
;
946 *NullBuffer
= UNICODE_NULL
;
948 /* Do a search for the file */
949 DPRINT("Ready for SearchPathW: %S\n", lpApplicationName
);
950 RetVal
= SearchPathW(NULL
,
955 NULL
) * sizeof(WCHAR
);
957 /* Did it find something? */
960 /* Get file attributes */
961 ULONG Attributes
= GetFileAttributesW(NameBuffer
);
962 if (Attributes
& FILE_ATTRIBUTE_DIRECTORY
)
964 /* Give it a length of 0 to fail, this was a directory. */
970 RetVal
+= sizeof(WCHAR
);
974 /* Now check if we have a file, and if the path size is OK */
975 if (!RetVal
|| RetVal
>= (MAX_PATH
/ sizeof(WCHAR
)))
980 /* We failed, try to get the Path Type */
981 DPRINT("SearchPathW failed. Retval: %ld\n", RetVal
);
982 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
984 /* If it's not relative, try to get the error */
985 if (PathType
!= RELATIVE_PATH
)
987 /* This should fail, and give us a detailed LastError */
988 hFile
= CreateFileW(lpApplicationName
,
990 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
993 FILE_ATTRIBUTE_NORMAL
,
996 /* Did it actually NOT fail? */
997 if (hFile
!= INVALID_HANDLE_VALUE
)
1001 SetLastErrorByStatus(STATUS_OBJECT_NAME_NOT_FOUND
);
1006 /* Immediately set the error */
1007 SetLastErrorByStatus(STATUS_OBJECT_NAME_NOT_FOUND
);
1010 /* Did we already fail once? */
1013 SetLastError(Error
);
1017 /* Not yet, cache it */
1018 Error
= GetLastError();
1021 /* Put back the command line */
1022 *NullBuffer
= SaveChar
;
1023 lpApplicationName
= NameBuffer
;
1026 * If the search isn't done and we still have cmdline
1027 * then start over. Ex: c:\ha ha ha\haha.exe
1029 if (*ScanString
&& !SearchDone
)
1031 /* Move in the buffer */
1033 NullBuffer
= ScanString
;
1035 /* We will have to add a quote, since there is a space*/
1036 QuotesNeeded
= TRUE
;
1038 /* And we will also fake the fact we found one */
1045 /* We totally failed */
1049 /* Put back the command line */
1050 *NullBuffer
= SaveChar
;
1051 lpApplicationName
= NameBuffer
;
1052 DPRINT("SearchPathW suceeded (%ld): %S\n", RetVal
, NameBuffer
);
1054 else if (!lpCommandLine
|| *lpCommandLine
== UNICODE_NULL
)
1056 /* We have an app name (good!) but no command line */
1057 CmdLineIsAppName
= TRUE
;
1058 lpCommandLine
= (LPWSTR
)lpApplicationName
;
1061 /* At this point the name has been toyed with enough to be openable */
1062 Status
= BasepMapFile(lpApplicationName
, &hSection
, &ApplicationName
);
1064 /* Check for failure */
1065 if (!NT_SUCCESS(Status
))
1067 /* Could be a non-PE File */
1070 /* Check if the Kernel tells us it's not even valid MZ */
1071 case STATUS_INVALID_IMAGE_NE_FORMAT
:
1072 case STATUS_INVALID_IMAGE_PROTECT
:
1073 case STATUS_INVALID_IMAGE_NOT_MZ
:
1075 /* If it's a DOS app, use VDM
1076 if ((BasepCheckDosApp(&ApplicationName))) */
1078 DPRINT1("Launching VDM...\n");
1079 RtlFreeHeap(GetProcessHeap(), 0, NameBuffer
);
1080 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1081 return CreateProcessW(L
"ntvdm.exe",
1082 (LPWSTR
)lpApplicationName
,
1083 lpProcessAttributes
,
1090 lpProcessInformation
);
1093 /* It's a batch file */
1094 Extension
= &ApplicationName
.Buffer
[ApplicationName
.Length
/
1097 /* Make sure the extensions are correct */
1098 if (_wcsnicmp(Extension
, L
".bat", 4) && _wcsnicmp(Extension
, L
".cmd", 4))
1100 SetLastError(ERROR_BAD_EXE_FORMAT
);
1104 /* Calculate the length of the command line */
1105 CmdLineLength
= wcslen(CMD_STRING
) + wcslen(lpCommandLine
) + 1;
1107 /* If we found quotes, then add them into the length size */
1108 if (CmdLineIsAppName
|| FoundQuotes
) CmdLineLength
+= 2;
1109 CmdLineLength
*= sizeof(WCHAR
);
1111 /* Allocate space for the new command line */
1112 BatchCommandLine
= RtlAllocateHeap(GetProcessHeap(),
1117 wcscpy(BatchCommandLine
, CMD_STRING
);
1118 if (CmdLineIsAppName
|| FoundQuotes
)
1120 wcscat(BatchCommandLine
, L
"\"");
1122 wcscat(BatchCommandLine
, lpCommandLine
);
1123 if (CmdLineIsAppName
|| FoundQuotes
)
1125 wcscat(BatchCommandLine
, L
"\"");
1128 /* Create it as a Unicode String */
1129 RtlInitUnicodeString(&CommandLineString
, BatchCommandLine
);
1131 /* Set the command line to this */
1132 lpCommandLine
= CommandLineString
.Buffer
;
1133 lpApplicationName
= NULL
;
1136 RtlFreeHeap(GetProcessHeap(), 0, TempBuffer
);
1137 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1138 ApplicationName
.Buffer
= NULL
;
1143 case STATUS_INVALID_IMAGE_WIN_16
:
1145 /* It's a Win16 Image, use VDM */
1146 DPRINT1("Launching VDM...\n");
1147 RtlFreeHeap(GetProcessHeap(), 0, NameBuffer
);
1148 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1149 return CreateProcessW(L
"ntvdm.exe",
1150 (LPWSTR
)lpApplicationName
,
1151 lpProcessAttributes
,
1158 lpProcessInformation
);
1161 /* Invalid Image Type */
1162 SetLastError(ERROR_BAD_EXE_FORMAT
);
1167 /* Use our desktop if we didn't get any */
1168 if (!StartupInfo
.lpDesktop
)
1170 StartupInfo
.lpDesktop
= OurPeb
->ProcessParameters
->DesktopInfo
.Buffer
;
1173 /* FIXME: Check if Application is allowed to run */
1175 /* FIXME: Allow CREATE_SEPARATE only for WOW Apps, once we have that. */
1177 /* Get some information about the executable */
1178 Status
= ZwQuerySection(hSection
,
1179 SectionImageInformation
,
1181 sizeof(SectionImageInfo
),
1183 if(!NT_SUCCESS(Status
))
1186 DPRINT1("Unable to get SectionImageInformation, status 0x%x\n", Status
);
1187 SetLastErrorByStatus(Status
);
1191 /* Don't execute DLLs */
1192 if (SectionImageInfo
.ImageCharacteristics
& IMAGE_FILE_DLL
)
1195 DPRINT1("Can't execute a DLL\n");
1196 SetLastError(ERROR_BAD_EXE_FORMAT
);
1200 /* FIXME: Check for Debugger */
1202 /* FIXME: Check if Machine Type and SubSys Version Match */
1204 /* We don't support POSIX or anything else for now */
1205 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
!= SectionImageInfo
.SubsystemType
&&
1206 IMAGE_SUBSYSTEM_WINDOWS_CUI
!= SectionImageInfo
.SubsystemType
)
1209 DPRINT1("Invalid subsystem %d\n", SectionImageInfo
.SubsystemType
);
1210 SetLastError(ERROR_BAD_EXE_FORMAT
);
1214 /* Initialize the process object attributes */
1215 ObjectAttributes
= BasepConvertObjectAttributes(&LocalObjectAttributes
,
1216 lpProcessAttributes
,
1219 /* Create the Process */
1220 Status
= NtCreateProcess(&hProcess
,
1228 if(!NT_SUCCESS(Status
))
1231 DPRINT1("Unable to create process, status 0x%x\n", Status
);
1232 SetLastErrorByStatus(Status
);
1237 Status
= NtSetInformationProcess(hProcess
,
1238 ProcessPriorityClass
,
1240 sizeof(PROCESS_PRIORITY_CLASS
));
1241 if(!NT_SUCCESS(Status
))
1245 DPRINT1("Unable to set new process priority, status 0x%x\n", Status
);
1246 SetLastErrorByStatus(Status
);
1250 /* Set Error Mode */
1251 if (dwCreationFlags
& CREATE_DEFAULT_ERROR_MODE
)
1253 ULONG ErrorMode
= SEM_FAILCRITICALERRORS
;
1254 NtSetInformationProcess(hProcess
,
1255 ProcessDefaultHardErrorMode
,
1260 /* Convert the directory to a full path */
1261 if (lpCurrentDirectory
)
1263 /* Allocate a buffer */
1264 CurrentDirectory
= RtlAllocateHeap(GetProcessHeap(),
1266 MAX_PATH
* sizeof(WCHAR
) + 2);
1268 /* Get the length */
1269 if (GetFullPathNameW(lpCurrentDirectory
,
1272 &CurrentDirectoryPart
) > MAX_PATH
)
1274 DPRINT1("Directory name too long\n");
1275 SetLastError(ERROR_DIRECTORY
);
1280 /* Insert quotes if needed */
1281 if (QuotesNeeded
|| CmdLineIsAppName
)
1283 /* Allocate a buffer */
1284 QuotedCmdLine
= RtlAllocateHeap(GetProcessHeap(),
1286 (wcslen(lpCommandLine
) + 2 + 1) *
1289 /* Copy the first quote */
1290 wcscpy(QuotedCmdLine
, L
"\"");
1292 /* Save a null char */
1295 SaveChar
= *NullBuffer
;
1296 *NullBuffer
= UNICODE_NULL
;
1299 /* Add the command line and the finishing quote */
1300 wcscat(QuotedCmdLine
, lpCommandLine
);
1301 wcscat(QuotedCmdLine
, L
"\"");
1303 /* Add the null char */
1306 *NullBuffer
= SaveChar
;
1307 wcscat(QuotedCmdLine
, NullBuffer
);
1310 DPRINT("Quoted CmdLine: %S\n", QuotedCmdLine
);
1313 /* Get the Process Information */
1314 Status
= NtQueryInformationProcess(hProcess
,
1315 ProcessBasicInformation
,
1317 sizeof(ProcessBasicInfo
),
1321 Status
= BasepNotifyCsrOfCreation(dwCreationFlags
,
1322 (HANDLE
)ProcessBasicInfo
.UniqueProcessId
,
1323 SectionImageInfo
.SubsystemType
,
1328 if (!NT_SUCCESS(Status
))
1330 DPRINT1("CSR Notification Failed");
1331 SetLastErrorByStatus(Status
);
1335 /* Create Process Environment */
1336 RemotePeb
= ProcessBasicInfo
.PebBaseAddress
;
1337 Status
= BasepInitializeEnvironment(hProcess
,
1339 (LPWSTR
)lpApplicationName
,
1341 (QuotesNeeded
|| CmdLineIsAppName
) ?
1342 QuotedCmdLine
: lpCommandLine
,
1349 if (!NT_SUCCESS(Status
))
1351 DPRINT1("Could not initialize Process Environment\n");
1352 SetLastErrorByStatus(Status
);
1356 /* Close the section */
1360 /* Duplicate the handles if needed */
1361 if (!bInheritHandles
&& !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
1362 SectionImageInfo
.SubsystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
1364 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
;
1366 /* Get the remote parameters */
1367 Status
= NtReadVirtualMemory(hProcess
,
1368 &RemotePeb
->ProcessParameters
,
1372 if (!NT_SUCCESS(Status
))
1374 DPRINT1("Failed to read memory\n");
1378 /* Duplicate and write the handles */
1379 BasepDuplicateAndWriteHandle(hProcess
,
1380 OurPeb
->ProcessParameters
->StandardInput
,
1381 &RemoteParameters
->StandardInput
);
1382 BasepDuplicateAndWriteHandle(hProcess
,
1383 OurPeb
->ProcessParameters
->StandardOutput
,
1384 &RemoteParameters
->StandardOutput
);
1385 BasepDuplicateAndWriteHandle(hProcess
,
1386 OurPeb
->ProcessParameters
->StandardError
,
1387 &RemoteParameters
->StandardError
);
1390 /* Create the first thread */
1391 DPRINT("Creating thread for process (EntryPoint = 0x%.08x)\n",
1392 SectionImageInfo
.TransferAddress
);
1393 hThread
= BasepCreateFirstThread(hProcess
,
1398 if (hThread
== NULL
)
1400 DPRINT1("Could not create Initial Thread\n");
1404 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
1406 NtResumeThread(hThread
, &Dummy
);
1409 /* Cleanup Environment */
1410 if (lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
1412 RtlDestroyEnvironment(lpEnvironment
);
1416 lpProcessInformation
->dwProcessId
= (DWORD
)ClientId
.UniqueProcess
;
1417 lpProcessInformation
->dwThreadId
= (DWORD
)ClientId
.UniqueThread
;
1418 lpProcessInformation
->hProcess
= hProcess
;
1419 lpProcessInformation
->hThread
= hThread
;
1420 DPRINT("hThread[%lx]: %lx inside hProcess[%lx]: %lx\n", hThread
,
1421 ClientId
.UniqueThread
, ClientId
.UniqueProcess
, hProcess
);
1422 hProcess
= hThread
= NULL
;
1424 /* De-allocate heap strings */
1425 if (NameBuffer
) RtlFreeHeap(GetProcessHeap(), 0, NameBuffer
);
1426 if (ApplicationName
.Buffer
)
1427 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1428 if (CurrentDirectory
) RtlFreeHeap(GetProcessHeap(), 0, CurrentDirectory
);
1429 if (QuotedCmdLine
) RtlFreeHeap(GetProcessHeap(), 0, QuotedCmdLine
);
1431 /* Kill any handles still alive */
1432 if (hSection
) NtClose(hSection
);
1435 /* We don't know any more details then this */
1436 NtTerminateProcess(hProcess
, STATUS_UNSUCCESSFUL
);
1439 if (hProcess
) NtClose(hProcess
);
1441 /* Return Success */