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
);
42 if ((ExceptionDisposition
== EXCEPTION_CONTINUE_SEARCH
|| ExceptionDisposition
== EXCEPTION_EXECUTE_HANDLER
) &&
43 GlobalTopLevelExceptionFilter
!= UnhandledExceptionFilter
)
45 ExceptionDisposition
= UnhandledExceptionFilter(ExceptionInfo
);
48 return ExceptionDisposition
;
53 BaseProcessStartup(PPROCESS_START_ROUTINE lpStartAddress
)
57 DPRINT("BaseProcessStartup(..) - setting up exception frame.\n");
61 /* Set our Start Address */
62 NtSetInformationThread(NtCurrentThread(),
63 ThreadQuerySetWin32StartAddress
,
65 sizeof(PPROCESS_START_ROUTINE
));
67 /* Call the Start Routine */
68 uExitCode
= (lpStartAddress
)();
70 _SEH_EXCEPT(BaseExceptionFilter
)
72 /* Get the SEH Error */
73 uExitCode
= _SEH_GetExceptionCode();
77 /* Exit the Process with our error */
78 ExitProcess(uExitCode
);
82 * Tells CSR that a new process was created
86 BasepNotifyCsrOfCreation(ULONG dwCreationFlags
,
88 IN BOOL InheritHandles
)
90 ULONG Request
= CREATE_PROCESS
;
91 CSR_API_MESSAGE CsrRequest
;
94 DPRINT("BasepNotifyCsrOfCreation: Process: %lx, Flags %lx\n",
95 ProcessId
, dwCreationFlags
);
97 /* Fill out the request */
98 CsrRequest
.Data
.CreateProcessRequest
.NewProcessId
= ProcessId
;
99 CsrRequest
.Data
.CreateProcessRequest
.Flags
= dwCreationFlags
;
100 CsrRequest
.Data
.CreateProcessRequest
.bInheritHandles
= InheritHandles
;
103 Status
= CsrClientCallServer(&CsrRequest
,
105 MAKE_CSR_API(Request
, CSR_NATIVE
),
106 sizeof(CSR_API_MESSAGE
));
107 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
109 DPRINT1("Failed to tell csrss about new process\n");
110 return CsrRequest
.Status
;
114 return STATUS_SUCCESS
;
118 * Creates the first Thread in a Proces
122 BasepCreateFirstThread(HANDLE ProcessHandle
,
123 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
124 PSECTION_IMAGE_INFORMATION SectionImageInfo
,
127 OBJECT_ATTRIBUTES LocalObjectAttributes
;
128 POBJECT_ATTRIBUTES ObjectAttributes
;
130 INITIAL_TEB InitialTeb
;
134 DPRINT("BasepCreateFirstThread. hProcess: %lx\n", ProcessHandle
);
136 /* Create the Thread's Stack */
137 BasepCreateStack(ProcessHandle
,
138 SectionImageInfo
->MaximumStackSize
,
139 SectionImageInfo
->CommittedStackSize
,
142 /* Create the Thread's Context */
143 BasepInitializeContext(&Context
,
145 SectionImageInfo
->TransferAddress
,
146 InitialTeb
.StackBase
,
149 /* Convert the thread attributes */
150 ObjectAttributes
= BasepConvertObjectAttributes(&LocalObjectAttributes
,
154 /* Create the Kernel Thread Object */
155 Status
= NtCreateThread(&hThread
,
169 * Converts ANSI to Unicode Environment
173 BasepConvertUnicodeEnvironment(OUT SIZE_T
* EnvSize
,
174 IN PVOID lpEnvironment
)
178 UNICODE_STRING UnicodeEnv
;
181 DPRINT("BasepConvertUnicodeEnvironment\n");
183 /* Scan the environment to calculate its Unicode size */
184 AnsiEnv
.Buffer
= pcScan
= (PCHAR
)lpEnvironment
;
187 pcScan
+= strlen(pcScan
) + 1;
190 /* Create our ANSI String */
191 if (pcScan
== (PCHAR
)lpEnvironment
)
193 AnsiEnv
.Length
= 2 * sizeof(CHAR
);
198 AnsiEnv
.Length
= (ULONG_PTR
)pcScan
- (ULONG_PTR
)lpEnvironment
+ sizeof(CHAR
);
200 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ 1;
202 /* Allocate memory for the Unicode Environment */
203 UnicodeEnv
.Buffer
= NULL
;
204 *EnvSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
205 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
206 (PVOID
)&UnicodeEnv
.Buffer
,
212 if (!NT_SUCCESS(Status
))
214 SetLastError(Status
);
219 /* Use the allocated size */
220 UnicodeEnv
.MaximumLength
= *EnvSize
;
223 RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
224 return UnicodeEnv
.Buffer
;
228 * Converts a Win32 Priority Class to NT
232 BasepConvertPriorityClass(IN ULONG dwCreationFlags
)
236 if(dwCreationFlags
& IDLE_PRIORITY_CLASS
)
238 ReturnClass
= PROCESS_PRIORITY_CLASS_IDLE
;
240 else if(dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
242 ReturnClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
244 else if(dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
246 ReturnClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
248 else if(dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
250 ReturnClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
252 else if(dwCreationFlags
& HIGH_PRIORITY_CLASS
)
254 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
256 else if(dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
258 /* Check for Privilege First */
259 if (BasepCheckRealTimePrivilege())
261 ReturnClass
= PROCESS_PRIORITY_CLASS_REALTIME
;
265 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
270 ReturnClass
= PROCESS_PRIORITY_CLASS_INVALID
;
277 * Duplicates a standard handle and writes it where requested.
281 BasepDuplicateAndWriteHandle(IN HANDLE ProcessHandle
,
282 IN HANDLE StandardHandle
,
286 HANDLE DuplicatedHandle
;
289 DPRINT("BasepDuplicateAndWriteHandle. hProcess: %lx, Handle: %lx,"
290 "Address: %p\n", ProcessHandle
, StandardHandle
, Address
);
292 /* Don't touch Console Handles */
293 if (IsConsoleHandle(StandardHandle
)) return;
295 /* Duplicate the handle */
296 Status
= NtDuplicateObject(NtCurrentProcess(),
300 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
,
303 if (NT_SUCCESS(Status
))
306 NtWriteVirtualMemory(ProcessHandle
,
316 BasepGetDllPath(LPWSTR FullPath
,
319 /* FIXME: Not yet implemented */
325 BasepCopyHandles(IN PRTL_USER_PROCESS_PARAMETERS Params
,
326 IN PRTL_USER_PROCESS_PARAMETERS PebParams
,
327 IN BOOL InheritHandles
)
329 DPRINT("BasepCopyHandles %p %p, %d\n", Params
, PebParams
, InheritHandles
);
331 /* Copy the handle if we are inheriting or if it's a console handle */
332 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardInput
))
334 Params
->StandardInput
= PebParams
->StandardInput
;
336 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardOutput
))
338 Params
->StandardOutput
= PebParams
->StandardOutput
;
340 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardError
))
342 Params
->StandardError
= PebParams
->StandardError
;
348 BasepInitializeEnvironment(HANDLE ProcessHandle
,
350 LPWSTR ApplicationPathName
,
351 LPWSTR lpCurrentDirectory
,
352 LPWSTR lpCommandLine
,
353 LPVOID lpEnvironment
,
355 LPSTARTUPINFOW StartupInfo
,
359 WCHAR FullPath
[MAX_PATH
];
361 LPWSTR DllPathString
;
362 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
;
363 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
= NULL
;
364 UNICODE_STRING DllPath
, ImageName
, CommandLine
, CurrentDirectory
;
370 UNICODE_STRING Desktop
, Shell
, Runtime
, Title
;
371 PPEB OurPeb
= NtCurrentPeb();
372 LPVOID Environment
= lpEnvironment
;
374 DPRINT("BasepInitializeEnvironment\n");
376 /* Get the full path name */
377 RetVal
= GetFullPathNameW(ApplicationPathName
,
381 DPRINT("ApplicationPathName: %S, FullPath: %S\n", ApplicationPathName
,
384 /* Get the DLL Path */
385 DllPathString
= BasepGetDllPath(FullPath
, Environment
);
387 /* Initialize Strings */
388 RtlInitUnicodeString(&DllPath
, DllPathString
);
389 RtlInitUnicodeString(&ImageName
, FullPath
);
390 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
391 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
393 /* Initialize more Strings from the Startup Info */
394 if (StartupInfo
->lpDesktop
)
396 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
400 RtlInitUnicodeString(&Desktop
, L
"");
402 if (StartupInfo
->lpReserved
)
404 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
408 RtlInitUnicodeString(&Shell
, L
"");
410 if (StartupInfo
->lpTitle
)
412 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
416 RtlInitUnicodeString(&Title
, L
"");
419 /* This one is special because the length can differ */
420 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
421 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
423 /* Create the Parameter Block */
424 DPRINT("Creating Process Parameters: %wZ %wZ %wZ %wZ %wZ %wZ %wZ\n",
425 &ImageName
, &DllPath
, &CommandLine
, &Desktop
, &Title
, &Shell
,
427 Status
= RtlCreateProcessParameters(&ProcessParameters
,
431 &CurrentDirectory
: NULL
,
439 if (!NT_SUCCESS(Status
))
441 DPRINT1("Failed to create process parameters!\n");
445 /* Check if we got an environment. If not, use ours */
448 /* Save pointer and start lookup */
449 Environment
= ScanChar
= ProcessParameters
->Environment
;
453 /* Save pointer and start lookup */
454 Environment
= ScanChar
= OurPeb
->ProcessParameters
->Environment
;
457 /* Find the environment size */
460 if (EnvSize
&& Environment
== lpEnvironment
)
462 /* its a converted ansi environment, bypass the length calculation */
463 EnviroSize
= EnvSize
;
469 ScanChar
+= wcslen(ScanChar
) + 1;
472 /* Calculate the size of the block */
473 if (ScanChar
== Environment
)
475 EnviroSize
= 2 * sizeof(WCHAR
);
479 EnviroSize
= (ULONG
)((ULONG_PTR
)ScanChar
- (ULONG_PTR
)Environment
+ sizeof(WCHAR
));
482 DPRINT("EnvironmentSize %ld\n", EnviroSize
);
484 /* Allocate and Initialize new Environment Block */
486 ProcessParameters
->Environment
= NULL
;
487 Status
= ZwAllocateVirtualMemory(ProcessHandle
,
488 (PVOID
*)&ProcessParameters
->Environment
,
493 if (!NT_SUCCESS(Status
))
495 DPRINT1("Failed to allocate Environment Block\n");
499 /* Write the Environment Block */
500 ZwWriteVirtualMemory(ProcessHandle
,
501 ProcessParameters
->Environment
,
507 /* Write new parameters */
508 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
509 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
510 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
511 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
512 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
513 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
514 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
515 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
516 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
518 /* Write the handles only if we have to */
519 if (StartupInfo
->dwFlags
& STARTF_USESTDHANDLES
)
521 DPRINT("Using Standard Handles\n");
522 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
523 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
524 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
527 /* Use Special Flags for ConDllInitialize in Kernel32 */
528 if (CreationFlags
& DETACHED_PROCESS
)
530 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
532 else if (CreationFlags
& CREATE_NO_WINDOW
)
534 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
536 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
538 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
542 /* Inherit our Console Handle */
543 ProcessParameters
->ConsoleHandle
= OurPeb
->ProcessParameters
->ConsoleHandle
;
545 /* Is the shell trampling on our Handles? */
546 if (!(StartupInfo
->dwFlags
&
547 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
549 /* Use handles from PEB, if inheriting or they are console */
550 DPRINT("Copying handles from parent\n");
551 BasepCopyHandles(ProcessParameters
,
552 OurPeb
->ProcessParameters
,
557 /* Also set the Console Flag */
558 if (CreationFlags
& CREATE_NEW_PROCESS_GROUP
)
560 ProcessParameters
->ConsoleFlags
= 1;
563 /* Allocate memory for the parameter block */
564 Size
= ProcessParameters
->Length
;
565 Status
= NtAllocateVirtualMemory(ProcessHandle
,
566 (PVOID
*)&RemoteParameters
,
571 if (!NT_SUCCESS(Status
))
573 DPRINT1("Failed to allocate Parameters Block\n");
577 /* Set the allocated size */
578 ProcessParameters
->MaximumLength
= Size
;
580 /* Handle some Parameter Flags */
581 ProcessParameters
->ConsoleFlags
= (CreationFlags
& CREATE_NEW_PROCESS_GROUP
);
582 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
583 PPF_PROFILE_USER
: 0;
584 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
585 PPF_PROFILE_KERNEL
: 0;
586 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
587 PPF_PROFILE_SERVER
: 0;
588 ProcessParameters
->Flags
|= (NtCurrentPeb()->ProcessParameters
->Flags
&
589 PPF_DISABLE_HEAP_CHECKS
);
591 /* Write the Parameter Block */
592 Status
= NtWriteVirtualMemory(ProcessHandle
,
595 ProcessParameters
->Length
,
598 /* Write the PEB Pointer */
599 Status
= NtWriteVirtualMemory(ProcessHandle
,
600 &Peb
->ProcessParameters
,
606 RtlFreeHeap(GetProcessHeap(), 0, DllPath
.Buffer
);
607 RtlDestroyProcessParameters(ProcessParameters
);
609 DPRINT("Completed\n");
610 return STATUS_SUCCESS
;
613 /* FUNCTIONS ****************************************************************/
616 * FUNCTION: The CreateProcess function creates a new process and its
617 * primary thread. The new process executes the specified executable file
620 * lpApplicationName = Pointer to name of executable module
621 * lpCommandLine = Pointer to command line string
622 * lpProcessAttributes = Process security attributes
623 * lpThreadAttributes = Thread security attributes
624 * bInheritHandles = Handle inheritance flag
625 * dwCreationFlags = Creation flags
626 * lpEnvironment = Pointer to new environment block
627 * lpCurrentDirectory = Pointer to current directory name
628 * lpStartupInfo = Pointer to startup info
629 * lpProcessInformation = Pointer to process information
635 CreateProcessA(LPCSTR lpApplicationName
,
637 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
638 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
639 BOOL bInheritHandles
,
640 DWORD dwCreationFlags
,
641 LPVOID lpEnvironment
,
642 LPCSTR lpCurrentDirectory
,
643 LPSTARTUPINFOA lpStartupInfo
,
644 LPPROCESS_INFORMATION lpProcessInformation
)
646 PUNICODE_STRING CommandLine
= NULL
;
647 UNICODE_STRING DummyString
;
648 UNICODE_STRING LiveCommandLine
;
649 UNICODE_STRING ApplicationName
;
650 UNICODE_STRING CurrentDirectory
;
652 STARTUPINFOW StartupInfo
;
654 DPRINT("dwCreationFlags %x, lpEnvironment %x, lpCurrentDirectory %x, "
655 "lpStartupInfo %x, lpProcessInformation %x\n",
656 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
657 lpStartupInfo
, lpProcessInformation
);
659 /* Copy Startup Info */
660 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
662 /* Initialize all strings to nothing */
663 LiveCommandLine
.Buffer
= NULL
;
664 DummyString
.Buffer
= NULL
;
665 ApplicationName
.Buffer
= NULL
;
666 CurrentDirectory
.Buffer
= NULL
;
667 StartupInfo
.lpDesktop
= NULL
;
668 StartupInfo
.lpReserved
= NULL
;
669 StartupInfo
.lpTitle
= NULL
;
671 /* Convert the Command line */
674 /* If it's too long, then we'll have a problem */
675 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
676 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
678 /* Cache it in the TEB */
679 CommandLine
= Basep8BitStringToCachedUnicodeString(lpCommandLine
);
683 /* Use a dynamic version */
684 Basep8BitStringToHeapUnicodeString(&LiveCommandLine
,
690 /* The logic below will use CommandLine, so we must make it valid */
691 CommandLine
= &DummyString
;
694 /* Convert the Name and Directory */
695 if (lpApplicationName
)
697 Basep8BitStringToHeapUnicodeString(&ApplicationName
,
700 if (lpCurrentDirectory
)
702 Basep8BitStringToHeapUnicodeString(&CurrentDirectory
,
706 /* Now convert Startup Strings */
707 if (lpStartupInfo
->lpReserved
)
709 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
710 &StartupInfo
.lpReserved
);
712 if (lpStartupInfo
->lpDesktop
)
714 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
715 &StartupInfo
.lpDesktop
);
717 if (lpStartupInfo
->lpTitle
)
719 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
720 &StartupInfo
.lpTitle
);
723 /* Call the Unicode function */
724 bRetVal
= CreateProcessW(ApplicationName
.Buffer
,
725 LiveCommandLine
.Buffer
?
726 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
732 CurrentDirectory
.Buffer
,
734 lpProcessInformation
);
737 RtlFreeUnicodeString(&ApplicationName
);
738 RtlFreeUnicodeString(&LiveCommandLine
);
739 RtlFreeUnicodeString(&CurrentDirectory
);
740 RtlFreeHeap(GetProcessHeap(), 0, StartupInfo
.lpDesktop
);
741 RtlFreeHeap(GetProcessHeap(), 0, StartupInfo
.lpReserved
);
742 RtlFreeHeap(GetProcessHeap(), 0, StartupInfo
.lpTitle
);
744 /* Return what Unicode did */
753 CreateProcessW(LPCWSTR lpApplicationName
,
754 LPWSTR lpCommandLine
,
755 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
756 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
757 BOOL bInheritHandles
,
758 DWORD dwCreationFlags
,
759 LPVOID lpEnvironment
,
760 LPCWSTR lpCurrentDirectory
,
761 LPSTARTUPINFOW lpStartupInfo
,
762 LPPROCESS_INFORMATION lpProcessInformation
)
765 PROCESS_PRIORITY_CLASS PriorityClass
;
766 BOOLEAN FoundQuotes
= FALSE
;
767 BOOLEAN QuotesNeeded
= FALSE
;
768 BOOLEAN CmdLineIsAppName
= FALSE
;
769 UNICODE_STRING ApplicationName
;
770 OBJECT_ATTRIBUTES LocalObjectAttributes
;
771 POBJECT_ATTRIBUTES ObjectAttributes
;
772 HANDLE hSection
, hProcess
, hThread
;
773 SECTION_IMAGE_INFORMATION SectionImageInfo
;
774 LPWSTR CurrentDirectory
= NULL
;
775 LPWSTR CurrentDirectoryPart
;
776 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
777 STARTUPINFOW StartupInfo
;
779 LPWSTR BatchCommandLine
;
781 UNICODE_STRING CommandLineString
;
783 LPWSTR QuotedCmdLine
= NULL
;
785 LPWSTR NullBuffer
= NULL
;
786 LPWSTR NameBuffer
= NULL
;
790 BOOLEAN SearchDone
= FALSE
;
792 PPEB OurPeb
= NtCurrentPeb();
796 DPRINT("CreateProcessW: lpApplicationName: %S lpCommandLine: %S"
797 " lpEnvironment: %p lpCurrentDirectory: %S dwCreationFlags: %lx\n",
798 lpApplicationName
, lpCommandLine
, lpEnvironment
, lpCurrentDirectory
,
801 /* Flags we don't handle yet */
802 if (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
)
804 DPRINT1("CREATE_SEPARATE_WOW_VDM not handled\n");
806 if (dwCreationFlags
& CREATE_SHARED_WOW_VDM
)
808 DPRINT1("CREATE_SHARED_WOW_VDM not handled\n");
810 if (dwCreationFlags
& CREATE_FORCEDOS
)
812 DPRINT1("CREATE_FORCEDOS not handled\n");
815 /* Fail on this flag, it's only valid with the WithLogonW function */
816 if (dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
)
818 DPRINT1("Invalid flag used\n");
819 SetLastError(ERROR_INVALID_PARAMETER
);
823 /* This combination is illegal (see MSDN) */
824 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
825 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
827 DPRINT1("Invalid flag combo used\n");
828 SetLastError(ERROR_INVALID_PARAMETER
);
832 /* Another illegal combo */
833 if ((dwCreationFlags
& (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
)) ==
834 (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
))
836 DPRINT1("Invalid flag combo used\n");
837 SetLastError(ERROR_INVALID_PARAMETER
);
842 * We're going to modify and mask out flags and stuff in lpStartupInfo,
843 * so we'll use our own local copy for that.
845 StartupInfo
= *lpStartupInfo
;
847 /* FIXME: Use default Separate/Shared VDM Flag */
849 /* If we are inside a Job, use Separate VDM so it won't escape the Job */
850 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
852 if (NtIsProcessInJob(NtCurrentProcess(), NULL
))
854 /* Remove the shared flag and add the separate flag. */
855 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
856 CREATE_SEPARATE_WOW_VDM
;
861 * According to some sites, ShellExecuteEx uses an undocumented flag to
862 * send private handle data (such as HMONITOR or HICON). See:
863 * www.catch22.net/tuts/undoc01.asp. This implies that we can't use the
864 * standard handles anymore since we'd be overwriting this private data
866 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
867 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
869 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
872 /* Start by zeroing out the fields */
873 RtlZeroMemory(lpProcessInformation
, sizeof(PROCESS_INFORMATION
));
875 /* Easy stuff first, convert the process priority class */
876 PriorityClass
.Foreground
= FALSE
;
877 PriorityClass
.PriorityClass
= BasepConvertPriorityClass(dwCreationFlags
);
879 /* Get the application name and do all the proper formating necessary */
881 /* See if we have an application name (oh please let us have one!) */
882 if (!lpApplicationName
)
885 NameBuffer
= RtlAllocateHeap(GetProcessHeap(),
887 MAX_PATH
* sizeof(WCHAR
));
889 /* This is all we have to work with :( */
890 lpApplicationName
= lpCommandLine
;
892 /* Initialize our friends at the beginning */
893 NullBuffer
= (LPWSTR
)lpApplicationName
;
894 ScanString
= (LPWSTR
)lpApplicationName
;
896 /* We will start by looking for a quote */
897 if (*ScanString
== L
'\"')
902 /* Advance past quote */
904 lpApplicationName
= ScanString
;
906 /* Find the closing quote */
909 if (*ScanString
== L
'\"')
912 NullBuffer
= ScanString
;
919 NullBuffer
= ScanString
;
924 /* No quotes, so we'll be looking for white space */
926 /* Reset the pointer */
927 lpApplicationName
= lpCommandLine
;
929 /* Find whitespace of Tab */
932 if (*ScanString
== ' ' || *ScanString
== '\t')
935 NullBuffer
= ScanString
;
941 NullBuffer
= ScanString
;
945 /* Set the Null Buffer */
946 SaveChar
= *NullBuffer
;
947 *NullBuffer
= UNICODE_NULL
;
949 /* Do a search for the file */
950 DPRINT("Ready for SearchPathW: %S\n", lpApplicationName
);
951 RetVal
= SearchPathW(NULL
,
956 NULL
) * sizeof(WCHAR
);
958 /* Did it find something? */
961 /* Get file attributes */
962 ULONG Attributes
= GetFileAttributesW(NameBuffer
);
963 if (Attributes
& FILE_ATTRIBUTE_DIRECTORY
)
965 /* Give it a length of 0 to fail, this was a directory. */
971 RetVal
+= sizeof(WCHAR
);
975 /* Now check if we have a file, and if the path size is OK */
976 if (!RetVal
|| RetVal
>= (MAX_PATH
* sizeof(WCHAR
)))
981 /* We failed, try to get the Path Type */
982 DPRINT("SearchPathW failed. Retval: %ld\n", RetVal
);
983 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
985 /* If it's not relative, try to get the error */
986 if (PathType
!= RELATIVE_PATH
)
988 /* This should fail, and give us a detailed LastError */
989 hFile
= CreateFileW(lpApplicationName
,
991 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
994 FILE_ATTRIBUTE_NORMAL
,
997 /* Did it actually NOT fail? */
998 if (hFile
!= INVALID_HANDLE_VALUE
)
1000 /* Fake the error */
1002 SetLastErrorByStatus(STATUS_OBJECT_NAME_NOT_FOUND
);
1007 /* Immediately set the error */
1008 SetLastErrorByStatus(STATUS_OBJECT_NAME_NOT_FOUND
);
1011 /* Did we already fail once? */
1014 SetLastError(Error
);
1018 /* Not yet, cache it */
1019 Error
= GetLastError();
1022 /* Put back the command line */
1023 *NullBuffer
= SaveChar
;
1024 lpApplicationName
= NameBuffer
;
1027 * If the search isn't done and we still have cmdline
1028 * then start over. Ex: c:\ha ha ha\haha.exe
1030 if (*ScanString
&& !SearchDone
)
1032 /* Move in the buffer */
1034 NullBuffer
= ScanString
;
1036 /* We will have to add a quote, since there is a space*/
1037 QuotesNeeded
= TRUE
;
1039 /* And we will also fake the fact we found one */
1046 /* We totally failed */
1050 /* Put back the command line */
1051 *NullBuffer
= SaveChar
;
1052 lpApplicationName
= NameBuffer
;
1053 DPRINT("SearchPathW suceeded (%ld): %S\n", RetVal
, NameBuffer
);
1055 else if (!lpCommandLine
|| *lpCommandLine
== UNICODE_NULL
)
1057 /* We have an app name (good!) but no command line */
1058 CmdLineIsAppName
= TRUE
;
1059 lpCommandLine
= (LPWSTR
)lpApplicationName
;
1062 /* At this point the name has been toyed with enough to be openable */
1063 Status
= BasepMapFile(lpApplicationName
, &hSection
, &ApplicationName
);
1065 /* Check for failure */
1066 if (!NT_SUCCESS(Status
))
1068 /* Could be a non-PE File */
1071 /* Check if the Kernel tells us it's not even valid MZ */
1072 case STATUS_INVALID_IMAGE_NE_FORMAT
:
1073 case STATUS_INVALID_IMAGE_PROTECT
:
1074 case STATUS_INVALID_IMAGE_NOT_MZ
:
1077 /* If it's a DOS app, use VDM */
1078 if ((BasepCheckDosApp(&ApplicationName
)))
1080 DPRINT1("Launching VDM...\n");
1081 RtlFreeHeap(GetProcessHeap(), 0, NameBuffer
);
1082 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1083 return CreateProcessW(L
"ntvdm.exe",
1084 (LPWSTR
)lpApplicationName
,
1085 lpProcessAttributes
,
1092 lpProcessInformation
);
1095 /* It's a batch file */
1096 Extension
= &ApplicationName
.Buffer
[ApplicationName
.Length
/
1099 /* Make sure the extensions are correct */
1100 if (_wcsnicmp(Extension
, L
".bat", 4) && _wcsnicmp(Extension
, L
".cmd", 4))
1102 SetLastError(ERROR_BAD_EXE_FORMAT
);
1106 /* Calculate the length of the command line */
1107 CmdLineLength
= wcslen(CMD_STRING
) + wcslen(lpCommandLine
) + 1;
1109 /* If we found quotes, then add them into the length size */
1110 if (CmdLineIsAppName
|| FoundQuotes
) CmdLineLength
+= 2;
1111 CmdLineLength
*= sizeof(WCHAR
);
1113 /* Allocate space for the new command line */
1114 BatchCommandLine
= RtlAllocateHeap(GetProcessHeap(),
1119 wcscpy(BatchCommandLine
, CMD_STRING
);
1120 if (CmdLineIsAppName
|| FoundQuotes
)
1122 wcscat(BatchCommandLine
, L
"\"");
1124 wcscat(BatchCommandLine
, lpCommandLine
);
1125 if (CmdLineIsAppName
|| FoundQuotes
)
1127 wcscat(BatchCommandLine
, L
"\"");
1130 /* Create it as a Unicode String */
1131 RtlInitUnicodeString(&CommandLineString
, BatchCommandLine
);
1133 /* Set the command line to this */
1134 lpCommandLine
= CommandLineString
.Buffer
;
1135 lpApplicationName
= NULL
;
1138 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1139 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
),
1320 /* Convert the environment */
1321 if(lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
1323 lpEnvironment
= BasepConvertUnicodeEnvironment(&EnvSize
, lpEnvironment
);
1324 if (!lpEnvironment
) return FALSE
;
1327 /* Create Process Environment */
1328 RemotePeb
= ProcessBasicInfo
.PebBaseAddress
;
1329 Status
= BasepInitializeEnvironment(hProcess
,
1331 (LPWSTR
)lpApplicationName
,
1333 (QuotesNeeded
|| CmdLineIsAppName
) ?
1334 QuotedCmdLine
: lpCommandLine
,
1341 /* Cleanup Environment */
1342 if (lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
1344 RtlDestroyEnvironment(lpEnvironment
);
1347 if (!NT_SUCCESS(Status
))
1349 DPRINT1("Could not initialize Process Environment\n");
1350 SetLastErrorByStatus(Status
);
1354 /* Close the section */
1358 /* Duplicate the handles if needed */
1359 if (!bInheritHandles
&& !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
1360 SectionImageInfo
.SubsystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
1362 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
;
1364 /* Get the remote parameters */
1365 Status
= NtReadVirtualMemory(hProcess
,
1366 &RemotePeb
->ProcessParameters
,
1370 if (!NT_SUCCESS(Status
))
1372 DPRINT1("Failed to read memory\n");
1376 /* Duplicate and write the handles */
1377 BasepDuplicateAndWriteHandle(hProcess
,
1378 OurPeb
->ProcessParameters
->StandardInput
,
1379 &RemoteParameters
->StandardInput
);
1380 BasepDuplicateAndWriteHandle(hProcess
,
1381 OurPeb
->ProcessParameters
->StandardOutput
,
1382 &RemoteParameters
->StandardOutput
);
1383 BasepDuplicateAndWriteHandle(hProcess
,
1384 OurPeb
->ProcessParameters
->StandardError
,
1385 &RemoteParameters
->StandardError
);
1388 /* Create the first thread */
1389 DPRINT("Creating thread for process (EntryPoint = 0x%.08x)\n",
1390 SectionImageInfo
.TransferAddress
);
1391 hThread
= BasepCreateFirstThread(hProcess
,
1396 if (hThread
== NULL
)
1398 DPRINT1("Could not create Initial Thread\n");
1404 Status
= BasepNotifyCsrOfCreation(dwCreationFlags
,
1405 (HANDLE
)ProcessBasicInfo
.UniqueProcessId
,
1408 if (!NT_SUCCESS(Status
))
1410 DPRINT1("CSR Notification Failed");
1411 SetLastErrorByStatus(Status
);
1415 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
1417 NtResumeThread(hThread
, &Dummy
);
1421 lpProcessInformation
->dwProcessId
= (DWORD
)ClientId
.UniqueProcess
;
1422 lpProcessInformation
->dwThreadId
= (DWORD
)ClientId
.UniqueThread
;
1423 lpProcessInformation
->hProcess
= hProcess
;
1424 lpProcessInformation
->hThread
= hThread
;
1425 DPRINT("hThread[%lx]: %lx inside hProcess[%lx]: %lx\n", hThread
,
1426 ClientId
.UniqueThread
, ClientId
.UniqueProcess
, hProcess
);
1427 hProcess
= hThread
= NULL
;
1429 /* De-allocate heap strings */
1430 if (NameBuffer
) RtlFreeHeap(GetProcessHeap(), 0, NameBuffer
);
1431 if (ApplicationName
.Buffer
)
1432 RtlFreeHeap(GetProcessHeap(), 0, ApplicationName
.Buffer
);
1433 if (CurrentDirectory
) RtlFreeHeap(GetProcessHeap(), 0, CurrentDirectory
);
1434 if (QuotedCmdLine
) RtlFreeHeap(GetProcessHeap(), 0, QuotedCmdLine
);
1436 /* Kill any handles still alive */
1437 if (hSection
) NtClose(hSection
);
1440 /* We don't know any more details then this */
1441 NtTerminateProcess(hProcess
, STATUS_UNSUCCESSFUL
);
1444 if (hProcess
) NtClose(hProcess
);
1446 /* Return Success */