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
,
163 if (!NT_SUCCESS(Status
))
173 * Converts ANSI to Unicode Environment
177 BasepConvertUnicodeEnvironment(OUT SIZE_T
* EnvSize
,
178 IN PVOID lpEnvironment
)
182 UNICODE_STRING UnicodeEnv
;
185 DPRINT("BasepConvertUnicodeEnvironment\n");
187 /* Scan the environment to calculate its Unicode size */
188 AnsiEnv
.Buffer
= pcScan
= (PCHAR
)lpEnvironment
;
191 pcScan
+= strlen(pcScan
) + 1;
194 /* Create our ANSI String */
195 if (pcScan
== (PCHAR
)lpEnvironment
)
197 AnsiEnv
.Length
= 2 * sizeof(CHAR
);
202 AnsiEnv
.Length
= (ULONG_PTR
)pcScan
- (ULONG_PTR
)lpEnvironment
+ sizeof(CHAR
);
204 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ 1;
206 /* Allocate memory for the Unicode Environment */
207 UnicodeEnv
.Buffer
= NULL
;
208 *EnvSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
209 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
210 (PVOID
)&UnicodeEnv
.Buffer
,
216 if (!NT_SUCCESS(Status
))
218 SetLastError(Status
);
223 /* Use the allocated size */
224 UnicodeEnv
.MaximumLength
= *EnvSize
;
227 RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
228 return UnicodeEnv
.Buffer
;
232 * Converts a Win32 Priority Class to NT
236 BasepConvertPriorityClass(IN ULONG dwCreationFlags
)
240 if(dwCreationFlags
& IDLE_PRIORITY_CLASS
)
242 ReturnClass
= PROCESS_PRIORITY_CLASS_IDLE
;
244 else if(dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
246 ReturnClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
248 else if(dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
250 ReturnClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
252 else if(dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
254 ReturnClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
256 else if(dwCreationFlags
& HIGH_PRIORITY_CLASS
)
258 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
260 else if(dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
262 /* Check for Privilege First */
263 if (BasepCheckRealTimePrivilege())
265 ReturnClass
= PROCESS_PRIORITY_CLASS_REALTIME
;
269 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
274 ReturnClass
= PROCESS_PRIORITY_CLASS_INVALID
;
281 * Duplicates a standard handle and writes it where requested.
285 BasepDuplicateAndWriteHandle(IN HANDLE ProcessHandle
,
286 IN HANDLE StandardHandle
,
290 HANDLE DuplicatedHandle
;
293 DPRINT("BasepDuplicateAndWriteHandle. hProcess: %lx, Handle: %lx,"
294 "Address: %p\n", ProcessHandle
, StandardHandle
, Address
);
296 /* Don't touch Console Handles */
297 if (IsConsoleHandle(StandardHandle
)) return;
299 /* Duplicate the handle */
300 Status
= NtDuplicateObject(NtCurrentProcess(),
304 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
,
307 if (NT_SUCCESS(Status
))
310 NtWriteVirtualMemory(ProcessHandle
,
320 BasepGetDllPath(LPWSTR FullPath
,
323 /* FIXME: Not yet implemented */
329 BasepCopyHandles(IN PRTL_USER_PROCESS_PARAMETERS Params
,
330 IN PRTL_USER_PROCESS_PARAMETERS PebParams
,
331 IN BOOL InheritHandles
)
333 DPRINT("BasepCopyHandles %p %p, %d\n", Params
, PebParams
, InheritHandles
);
335 /* Copy the handle if we are inheriting or if it's a console handle */
336 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardInput
))
338 Params
->StandardInput
= PebParams
->StandardInput
;
340 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardOutput
))
342 Params
->StandardOutput
= PebParams
->StandardOutput
;
344 if (InheritHandles
|| IsConsoleHandle(PebParams
->StandardError
))
346 Params
->StandardError
= PebParams
->StandardError
;
352 BasepInitializeEnvironment(HANDLE ProcessHandle
,
354 LPWSTR ApplicationPathName
,
355 LPWSTR lpCurrentDirectory
,
356 LPWSTR lpCommandLine
,
357 LPVOID lpEnvironment
,
359 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();
376 LPVOID Environment
= lpEnvironment
;
378 DPRINT("BasepInitializeEnvironment\n");
380 /* Get the full path name */
381 RetVal
= GetFullPathNameW(ApplicationPathName
,
385 DPRINT("ApplicationPathName: %S, FullPath: %S\n", ApplicationPathName
,
388 /* Get the DLL Path */
389 DllPathString
= BasepGetDllPath(FullPath
, Environment
);
391 /* Initialize Strings */
392 RtlInitUnicodeString(&DllPath
, DllPathString
);
393 RtlInitUnicodeString(&ImageName
, FullPath
);
394 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
395 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
397 /* Initialize more Strings from the Startup Info */
398 if (StartupInfo
->lpDesktop
)
400 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
404 RtlInitUnicodeString(&Desktop
, L
"");
406 if (StartupInfo
->lpReserved
)
408 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
412 RtlInitUnicodeString(&Shell
, L
"");
414 if (StartupInfo
->lpTitle
)
416 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
420 RtlInitUnicodeString(&Title
, L
"");
423 /* This one is special because the length can differ */
424 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
425 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
427 /* Create the Parameter Block */
428 DPRINT("Creating Process Parameters: %wZ %wZ %wZ %wZ %wZ %wZ %wZ\n",
429 &ImageName
, &DllPath
, &CommandLine
, &Desktop
, &Title
, &Shell
,
431 Status
= RtlCreateProcessParameters(&ProcessParameters
,
435 &CurrentDirectory
: NULL
,
443 if (!NT_SUCCESS(Status
))
445 DPRINT1("Failed to create process parameters!\n");
449 /* Check if we got an environment. If not, use ours */
452 /* Save pointer and start lookup */
453 Environment
= ScanChar
= ProcessParameters
->Environment
;
457 /* Save pointer and start lookup */
458 Environment
= ScanChar
= OurPeb
->ProcessParameters
->Environment
;
461 /* Find the environment size */
464 if (EnvSize
&& Environment
== lpEnvironment
)
466 /* its a converted ansi environment, bypass the length calculation */
467 EnviroSize
= EnvSize
;
473 ScanChar
+= wcslen(ScanChar
) + 1;
476 /* Calculate the size of the block */
477 if (ScanChar
== Environment
)
479 EnviroSize
= 2 * sizeof(WCHAR
);
483 EnviroSize
= (ULONG
)((ULONG_PTR
)ScanChar
- (ULONG_PTR
)Environment
+ sizeof(WCHAR
));
486 DPRINT("EnvironmentSize %ld\n", EnviroSize
);
488 /* Allocate and Initialize new Environment Block */
490 ProcessParameters
->Environment
= NULL
;
491 Status
= ZwAllocateVirtualMemory(ProcessHandle
,
492 (PVOID
*)&ProcessParameters
->Environment
,
497 if (!NT_SUCCESS(Status
))
499 DPRINT1("Failed to allocate Environment Block\n");
503 /* Write the Environment Block */
504 ZwWriteVirtualMemory(ProcessHandle
,
505 ProcessParameters
->Environment
,
511 /* Write new parameters */
512 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
513 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
514 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
515 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
516 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
517 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
518 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
519 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
520 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
522 /* Write the handles only if we have to */
523 if (StartupInfo
->dwFlags
& STARTF_USESTDHANDLES
)
525 DPRINT("Using Standard Handles\n");
526 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
527 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
528 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
531 /* Use Special Flags for ConDllInitialize in Kernel32 */
532 if (CreationFlags
& DETACHED_PROCESS
)
534 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
536 else if (CreationFlags
& CREATE_NO_WINDOW
)
538 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
540 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
542 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
546 /* Inherit our Console Handle */
547 ProcessParameters
->ConsoleHandle
= OurPeb
->ProcessParameters
->ConsoleHandle
;
549 /* Is the shell trampling on our Handles? */
550 if (!(StartupInfo
->dwFlags
&
551 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
553 /* Use handles from PEB, if inheriting or they are console */
554 DPRINT("Copying handles from parent\n");
555 BasepCopyHandles(ProcessParameters
,
556 OurPeb
->ProcessParameters
,
561 /* Also set the Console Flag */
562 if (CreationFlags
& CREATE_NEW_PROCESS_GROUP
)
564 ProcessParameters
->ConsoleFlags
= 1;
567 /* Allocate memory for the parameter block */
568 Size
= ProcessParameters
->Length
;
569 Status
= NtAllocateVirtualMemory(ProcessHandle
,
570 (PVOID
*)&RemoteParameters
,
575 if (!NT_SUCCESS(Status
))
577 DPRINT1("Failed to allocate Parameters Block\n");
581 /* Set the allocated size */
582 ProcessParameters
->MaximumLength
= Size
;
584 /* Handle some Parameter Flags */
585 ProcessParameters
->ConsoleFlags
= (CreationFlags
& CREATE_NEW_PROCESS_GROUP
);
586 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
587 RTL_USER_PROCESS_PARAMETERS_PROFILE_USER
: 0;
588 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
589 RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL
: 0;
590 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
591 RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER
: 0;
592 ProcessParameters
->Flags
|= (NtCurrentPeb()->ProcessParameters
->Flags
&
593 RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_CHECKS
);
595 /* Write the Parameter Block */
596 Status
= NtWriteVirtualMemory(ProcessHandle
,
599 ProcessParameters
->Length
,
602 /* Write the PEB Pointer */
603 Status
= NtWriteVirtualMemory(ProcessHandle
,
604 &Peb
->ProcessParameters
,
610 RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath
.Buffer
);
611 RtlDestroyProcessParameters(ProcessParameters
);
613 DPRINT("Completed\n");
614 return STATUS_SUCCESS
;
617 /* FUNCTIONS ****************************************************************/
624 CreateProcessInternalW(HANDLE hToken
,
625 LPCWSTR lpApplicationName
,
626 LPWSTR lpCommandLine
,
627 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
628 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
629 BOOL bInheritHandles
,
630 DWORD dwCreationFlags
,
631 LPVOID lpEnvironment
,
632 LPCWSTR lpCurrentDirectory
,
633 LPSTARTUPINFOW lpStartupInfo
,
634 LPPROCESS_INFORMATION lpProcessInformation
,
638 PROCESS_PRIORITY_CLASS PriorityClass
;
639 BOOLEAN FoundQuotes
= FALSE
;
640 BOOLEAN QuotesNeeded
= FALSE
;
641 BOOLEAN CmdLineIsAppName
= FALSE
;
642 UNICODE_STRING ApplicationName
= {0};
643 OBJECT_ATTRIBUTES LocalObjectAttributes
;
644 POBJECT_ATTRIBUTES ObjectAttributes
;
645 HANDLE hSection
= NULL
, hProcess
= NULL
, hThread
= NULL
;
646 SECTION_IMAGE_INFORMATION SectionImageInfo
;
647 LPWSTR CurrentDirectory
= NULL
;
648 LPWSTR CurrentDirectoryPart
;
649 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
650 STARTUPINFOW StartupInfo
;
652 LPWSTR BatchCommandLine
;
654 UNICODE_STRING CommandLineString
;
656 LPWSTR QuotedCmdLine
= NULL
;
658 LPWSTR NullBuffer
= NULL
;
659 LPWSTR NameBuffer
= NULL
;
663 BOOLEAN SearchDone
= FALSE
;
664 BOOLEAN Escape
= FALSE
;
666 PPEB OurPeb
= NtCurrentPeb();
671 DPRINT("CreateProcessW: lpApplicationName: %S lpCommandLine: %S"
672 " lpEnvironment: %p lpCurrentDirectory: %S dwCreationFlags: %lx\n",
673 lpApplicationName
, lpCommandLine
, lpEnvironment
, lpCurrentDirectory
,
676 /* Flags we don't handle yet */
677 if (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
)
679 DPRINT1("CREATE_SEPARATE_WOW_VDM not handled\n");
681 if (dwCreationFlags
& CREATE_SHARED_WOW_VDM
)
683 DPRINT1("CREATE_SHARED_WOW_VDM not handled\n");
685 if (dwCreationFlags
& CREATE_FORCEDOS
)
687 DPRINT1("CREATE_FORCEDOS not handled\n");
690 /* Fail on this flag, it's only valid with the WithLogonW function */
691 if (dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
)
693 DPRINT1("Invalid flag used\n");
694 SetLastError(ERROR_INVALID_PARAMETER
);
698 /* This combination is illegal (see MSDN) */
699 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
700 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
702 DPRINT1("Invalid flag combo used\n");
703 SetLastError(ERROR_INVALID_PARAMETER
);
707 /* Another illegal combo */
708 if ((dwCreationFlags
& (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
)) ==
709 (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
))
711 DPRINT1("Invalid flag combo used\n");
712 SetLastError(ERROR_INVALID_PARAMETER
);
717 * We're going to modify and mask out flags and stuff in lpStartupInfo,
718 * so we'll use our own local copy for that.
720 StartupInfo
= *lpStartupInfo
;
722 /* FIXME: Use default Separate/Shared VDM Flag */
724 /* If we are inside a Job, use Separate VDM so it won't escape the Job */
725 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
727 if (NtIsProcessInJob(NtCurrentProcess(), NULL
))
729 /* Remove the shared flag and add the separate flag. */
730 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
731 CREATE_SEPARATE_WOW_VDM
;
736 * According to some sites, ShellExecuteEx uses an undocumented flag to
737 * send private handle data (such as HMONITOR or HICON). See:
738 * www.catch22.net/tuts/undoc01.asp. This implies that we can't use the
739 * standard handles anymore since we'd be overwriting this private data
741 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
742 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
744 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
747 /* Start by zeroing out the fields */
748 RtlZeroMemory(lpProcessInformation
, sizeof(PROCESS_INFORMATION
));
750 /* Easy stuff first, convert the process priority class */
751 PriorityClass
.Foreground
= FALSE
;
752 PriorityClass
.PriorityClass
= BasepConvertPriorityClass(dwCreationFlags
);
756 /* Serach for escape sequences */
757 ScanString
= lpCommandLine
;
758 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
761 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\"')
769 /* Get the application name and do all the proper formating necessary */
771 /* See if we have an application name (oh please let us have one!) */
772 if (!lpApplicationName
)
775 NameBuffer
= RtlAllocateHeap(RtlGetProcessHeap(),
777 MAX_PATH
* sizeof(WCHAR
));
778 if (NameBuffer
== NULL
)
780 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
784 /* This is all we have to work with :( */
785 lpApplicationName
= lpCommandLine
;
787 /* Initialize our friends at the beginning */
788 NullBuffer
= (LPWSTR
)lpApplicationName
;
789 ScanString
= (LPWSTR
)lpApplicationName
;
791 /* We will start by looking for a quote */
792 if (*ScanString
== L
'\"')
797 /* Advance past quote */
799 lpApplicationName
= ScanString
;
801 /* Find the closing quote */
804 if (*ScanString
== L
'\"' && *(ScanString
- 1) != L
'^')
807 NullBuffer
= ScanString
;
814 NullBuffer
= ScanString
;
819 /* No quotes, so we'll be looking for white space */
821 /* Reset the pointer */
822 lpApplicationName
= lpCommandLine
;
824 /* Find whitespace of Tab */
827 if (*ScanString
== ' ' || *ScanString
== '\t')
830 NullBuffer
= ScanString
;
836 NullBuffer
= ScanString
;
840 /* Set the Null Buffer */
841 SaveChar
= *NullBuffer
;
842 *NullBuffer
= UNICODE_NULL
;
844 /* Do a search for the file */
845 DPRINT("Ready for SearchPathW: %S\n", lpApplicationName
);
846 RetVal
= SearchPathW(NULL
,
851 NULL
) * sizeof(WCHAR
);
853 /* Did it find something? */
856 /* Get file attributes */
857 ULONG Attributes
= GetFileAttributesW(NameBuffer
);
858 if (Attributes
& FILE_ATTRIBUTE_DIRECTORY
)
860 /* Give it a length of 0 to fail, this was a directory. */
866 RetVal
+= sizeof(WCHAR
);
870 /* Now check if we have a file, and if the path size is OK */
871 if (!RetVal
|| RetVal
>= (MAX_PATH
* sizeof(WCHAR
)))
876 /* We failed, try to get the Path Type */
877 DPRINT("SearchPathW failed. Retval: %ld\n", RetVal
);
878 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
880 /* If it's not relative, try to get the error */
881 if (PathType
!= RELATIVE_PATH
)
883 /* This should fail, and give us a detailed LastError */
884 hFile
= CreateFileW(lpApplicationName
,
886 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
889 FILE_ATTRIBUTE_NORMAL
,
892 /* Did it actually NOT fail? */
893 if (hFile
!= INVALID_HANDLE_VALUE
)
897 SetLastErrorByStatus(STATUS_OBJECT_NAME_NOT_FOUND
);
902 /* Immediately set the error */
903 SetLastErrorByStatus(STATUS_OBJECT_NAME_NOT_FOUND
);
906 /* Did we already fail once? */
913 /* Not yet, cache it */
914 Error
= GetLastError();
917 /* Put back the command line */
918 *NullBuffer
= SaveChar
;
919 lpApplicationName
= NameBuffer
;
922 * If the search isn't done and we still have cmdline
923 * then start over. Ex: c:\ha ha ha\haha.exe
925 if (*ScanString
&& !SearchDone
)
927 /* Move in the buffer */
929 NullBuffer
= ScanString
;
931 /* We will have to add a quote, since there is a space*/
934 /* And we will also fake the fact we found one */
941 /* We totally failed */
945 /* Put back the command line */
946 *NullBuffer
= SaveChar
;
947 lpApplicationName
= NameBuffer
;
948 DPRINT("SearchPathW suceeded (%ld): %S\n", RetVal
, NameBuffer
);
950 else if (!lpCommandLine
|| *lpCommandLine
== UNICODE_NULL
)
952 /* We have an app name (good!) but no command line */
953 CmdLineIsAppName
= TRUE
;
954 lpCommandLine
= (LPWSTR
)lpApplicationName
;
957 /* At this point the name has been toyed with enough to be openable */
958 Status
= BasepMapFile(lpApplicationName
, &hSection
, &ApplicationName
);
960 /* Check for failure */
961 if (!NT_SUCCESS(Status
))
963 /* Could be a non-PE File */
966 /* Check if the Kernel tells us it's not even valid MZ */
967 case STATUS_INVALID_IMAGE_NE_FORMAT
:
968 case STATUS_INVALID_IMAGE_PROTECT
:
969 case STATUS_INVALID_IMAGE_NOT_MZ
:
972 /* If it's a DOS app, use VDM */
973 if ((BasepCheckDosApp(&ApplicationName
)))
975 DPRINT1("Launching VDM...\n");
976 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
977 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
978 return CreateProcessW(L
"ntvdm.exe",
979 (LPWSTR
)lpApplicationName
,
987 lpProcessInformation
);
990 /* It's a batch file */
991 Extension
= &ApplicationName
.Buffer
[ApplicationName
.Length
/
994 /* Make sure the extensions are correct */
995 if (_wcsnicmp(Extension
, L
".bat", 4) && _wcsnicmp(Extension
, L
".cmd", 4))
997 SetLastError(ERROR_BAD_EXE_FORMAT
);
1001 /* Calculate the length of the command line */
1002 CmdLineLength
= wcslen(CMD_STRING
) + wcslen(lpCommandLine
) + 1;
1004 /* If we found quotes, then add them into the length size */
1005 if (CmdLineIsAppName
|| FoundQuotes
) CmdLineLength
+= 2;
1006 CmdLineLength
*= sizeof(WCHAR
);
1008 /* Allocate space for the new command line */
1009 BatchCommandLine
= RtlAllocateHeap(RtlGetProcessHeap(),
1012 if (BatchCommandLine
== NULL
)
1014 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
1019 wcscpy(BatchCommandLine
, CMD_STRING
);
1020 if (CmdLineIsAppName
|| FoundQuotes
)
1022 wcscat(BatchCommandLine
, L
"\"");
1024 wcscat(BatchCommandLine
, lpCommandLine
);
1025 if (CmdLineIsAppName
|| FoundQuotes
)
1027 wcscat(BatchCommandLine
, L
"\"");
1030 /* Create it as a Unicode String */
1031 RtlInitUnicodeString(&CommandLineString
, BatchCommandLine
);
1033 /* Set the command line to this */
1034 lpCommandLine
= CommandLineString
.Buffer
;
1035 lpApplicationName
= NULL
;
1038 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
1039 ApplicationName
.Buffer
= NULL
;
1043 case STATUS_INVALID_IMAGE_WIN_16
:
1045 /* It's a Win16 Image, use VDM */
1046 DPRINT1("Launching VDM...\n");
1047 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
1048 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
1049 return CreateProcessW(L
"ntvdm.exe",
1050 (LPWSTR
)lpApplicationName
,
1051 lpProcessAttributes
,
1058 lpProcessInformation
);
1061 /* Invalid Image Type */
1062 SetLastError(ERROR_BAD_EXE_FORMAT
);
1067 /* Use our desktop if we didn't get any */
1068 if (!StartupInfo
.lpDesktop
)
1070 StartupInfo
.lpDesktop
= OurPeb
->ProcessParameters
->DesktopInfo
.Buffer
;
1073 /* FIXME: Check if Application is allowed to run */
1075 /* FIXME: Allow CREATE_SEPARATE only for WOW Apps, once we have that. */
1077 /* Get some information about the executable */
1078 Status
= ZwQuerySection(hSection
,
1079 SectionImageInformation
,
1081 sizeof(SectionImageInfo
),
1083 if(!NT_SUCCESS(Status
))
1085 DPRINT1("Unable to get SectionImageInformation, status 0x%x\n", Status
);
1086 SetLastErrorByStatus(Status
);
1090 /* Don't execute DLLs */
1091 if (SectionImageInfo
.ImageCharacteristics
& IMAGE_FILE_DLL
)
1093 DPRINT1("Can't execute a DLL\n");
1094 SetLastError(ERROR_BAD_EXE_FORMAT
);
1098 /* FIXME: Check for Debugger */
1100 /* FIXME: Check if Machine Type and SubSys Version Match */
1102 /* We don't support POSIX or anything else for now */
1103 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
!= SectionImageInfo
.SubsystemType
&&
1104 IMAGE_SUBSYSTEM_WINDOWS_CUI
!= SectionImageInfo
.SubsystemType
)
1106 DPRINT1("Invalid subsystem %d\n", SectionImageInfo
.SubsystemType
);
1107 SetLastError(ERROR_BAD_EXE_FORMAT
);
1111 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
== SectionImageInfo
.SubsystemType
)
1113 /* Do not create a console for GUI applications */
1114 dwCreationFlags
&= ~CREATE_NEW_CONSOLE
;
1115 dwCreationFlags
|= DETACHED_PROCESS
;
1118 /* Initialize the process object attributes */
1119 ObjectAttributes
= BasepConvertObjectAttributes(&LocalObjectAttributes
,
1120 lpProcessAttributes
,
1123 /* Create the Process */
1124 Status
= NtCreateProcess(&hProcess
,
1132 if(!NT_SUCCESS(Status
))
1134 DPRINT1("Unable to create process, status 0x%x\n", Status
);
1135 SetLastErrorByStatus(Status
);
1140 Status
= NtSetInformationProcess(hProcess
,
1141 ProcessPriorityClass
,
1143 sizeof(PROCESS_PRIORITY_CLASS
));
1144 if(!NT_SUCCESS(Status
))
1146 DPRINT1("Unable to set new process priority, status 0x%x\n", Status
);
1147 SetLastErrorByStatus(Status
);
1151 /* Set Error Mode */
1152 if (dwCreationFlags
& CREATE_DEFAULT_ERROR_MODE
)
1154 ULONG ErrorMode
= SEM_FAILCRITICALERRORS
;
1155 NtSetInformationProcess(hProcess
,
1156 ProcessDefaultHardErrorMode
,
1161 /* Convert the directory to a full path */
1162 if (lpCurrentDirectory
)
1164 /* Allocate a buffer */
1165 CurrentDirectory
= RtlAllocateHeap(RtlGetProcessHeap(),
1167 (MAX_PATH
+ 1) * sizeof(WCHAR
));
1168 if (CurrentDirectory
== NULL
)
1170 DPRINT1("Cannot allocate memory for directory name\n");
1171 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
1175 /* Get the length */
1176 if (GetFullPathNameW(lpCurrentDirectory
,
1179 &CurrentDirectoryPart
) > MAX_PATH
)
1181 DPRINT1("Directory name too long\n");
1182 SetLastError(ERROR_DIRECTORY
);
1187 /* Insert quotes if needed */
1188 if (QuotesNeeded
|| CmdLineIsAppName
)
1190 /* Allocate a buffer */
1191 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
1193 (wcslen(lpCommandLine
) + 2 + 1) *
1195 if (QuotedCmdLine
== NULL
)
1197 DPRINT1("Cannot allocate memory for quoted command line\n");
1198 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
1202 /* Copy the first quote */
1203 wcscpy(QuotedCmdLine
, L
"\"");
1205 /* Save a null char */
1208 SaveChar
= *NullBuffer
;
1209 *NullBuffer
= UNICODE_NULL
;
1212 /* Add the command line and the finishing quote */
1213 wcscat(QuotedCmdLine
, lpCommandLine
);
1214 wcscat(QuotedCmdLine
, L
"\"");
1216 /* Add the null char */
1219 *NullBuffer
= SaveChar
;
1220 wcscat(QuotedCmdLine
, NullBuffer
);
1223 DPRINT("Quoted CmdLine: %S\n", QuotedCmdLine
);
1228 if (QuotedCmdLine
== NULL
)
1230 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
1232 (wcslen(lpCommandLine
) + 1) * sizeof(WCHAR
));
1233 if (QuotedCmdLine
== NULL
)
1235 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
1238 wcscpy(QuotedCmdLine
, lpCommandLine
);
1241 ScanString
= QuotedCmdLine
;
1242 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
1245 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\\')
1247 memmove(ScanString
-1, ScanString
, wcslen(ScanString
) * sizeof(WCHAR
) + sizeof(WCHAR
));
1252 /* Get the Process Information */
1253 Status
= NtQueryInformationProcess(hProcess
,
1254 ProcessBasicInformation
,
1256 sizeof(ProcessBasicInfo
),
1259 /* Convert the environment */
1260 if(lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
1262 lpEnvironment
= BasepConvertUnicodeEnvironment(&EnvSize
, lpEnvironment
);
1263 if (!lpEnvironment
) goto Cleanup
;
1266 /* Create Process Environment */
1267 RemotePeb
= ProcessBasicInfo
.PebBaseAddress
;
1268 Status
= BasepInitializeEnvironment(hProcess
,
1270 (LPWSTR
)lpApplicationName
,
1272 (QuotesNeeded
|| CmdLineIsAppName
|| Escape
) ?
1273 QuotedCmdLine
: lpCommandLine
,
1280 /* Cleanup Environment */
1281 if (lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
1283 RtlDestroyEnvironment(lpEnvironment
);
1286 if (!NT_SUCCESS(Status
))
1288 DPRINT1("Could not initialize Process Environment\n");
1289 SetLastErrorByStatus(Status
);
1293 /* Close the section */
1297 /* Duplicate the handles if needed */
1298 if (!bInheritHandles
&& !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
1299 SectionImageInfo
.SubsystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
1301 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
;
1303 /* Get the remote parameters */
1304 Status
= NtReadVirtualMemory(hProcess
,
1305 &RemotePeb
->ProcessParameters
,
1309 if (!NT_SUCCESS(Status
))
1311 DPRINT1("Failed to read memory\n");
1315 /* Duplicate and write the handles */
1316 BasepDuplicateAndWriteHandle(hProcess
,
1317 OurPeb
->ProcessParameters
->StandardInput
,
1318 &RemoteParameters
->StandardInput
);
1319 BasepDuplicateAndWriteHandle(hProcess
,
1320 OurPeb
->ProcessParameters
->StandardOutput
,
1321 &RemoteParameters
->StandardOutput
);
1322 BasepDuplicateAndWriteHandle(hProcess
,
1323 OurPeb
->ProcessParameters
->StandardError
,
1324 &RemoteParameters
->StandardError
);
1327 /* Create the first thread */
1328 DPRINT("Creating thread for process (EntryPoint = 0x%p)\n",
1329 SectionImageInfo
.TransferAddress
);
1330 hThread
= BasepCreateFirstThread(hProcess
,
1335 if (hThread
== NULL
)
1337 DPRINT1("Could not create Initial Thread\n");
1338 /* FIXME - set last error code */
1343 Status
= BasepNotifyCsrOfCreation(dwCreationFlags
,
1344 (HANDLE
)ProcessBasicInfo
.UniqueProcessId
,
1347 if (!NT_SUCCESS(Status
))
1349 DPRINT1("CSR Notification Failed");
1350 SetLastErrorByStatus(Status
);
1354 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
1356 NtResumeThread(hThread
, &Dummy
);
1360 lpProcessInformation
->dwProcessId
= (DWORD
)ClientId
.UniqueProcess
;
1361 lpProcessInformation
->dwThreadId
= (DWORD
)ClientId
.UniqueThread
;
1362 lpProcessInformation
->hProcess
= hProcess
;
1363 lpProcessInformation
->hThread
= hThread
;
1364 DPRINT("hThread[%p]: %p inside hProcess[%p]: %p\n", hThread
,
1365 ClientId
.UniqueThread
, ClientId
.UniqueProcess
, hProcess
);
1366 hProcess
= hThread
= NULL
;
1370 /* De-allocate heap strings */
1371 if (NameBuffer
) RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
1372 if (ApplicationName
.Buffer
)
1373 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
1374 if (CurrentDirectory
) RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentDirectory
);
1375 if (QuotedCmdLine
) RtlFreeHeap(RtlGetProcessHeap(), 0, QuotedCmdLine
);
1377 /* Kill any handles still alive */
1378 if (hSection
) NtClose(hSection
);
1381 /* We don't know any more details then this */
1382 NtTerminateProcess(hProcess
, STATUS_UNSUCCESSFUL
);
1385 if (hProcess
) NtClose(hProcess
);
1387 /* Return Success */
1396 CreateProcessW(LPCWSTR lpApplicationName
,
1397 LPWSTR lpCommandLine
,
1398 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
1399 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
1400 BOOL bInheritHandles
,
1401 DWORD dwCreationFlags
,
1402 LPVOID lpEnvironment
,
1403 LPCWSTR lpCurrentDirectory
,
1404 LPSTARTUPINFOW lpStartupInfo
,
1405 LPPROCESS_INFORMATION lpProcessInformation
)
1407 /* Call the internal (but exported) version */
1408 return CreateProcessInternalW(0,
1411 lpProcessAttributes
,
1418 lpProcessInformation
,
1427 CreateProcessInternalA(HANDLE hToken
,
1428 LPCSTR lpApplicationName
,
1429 LPSTR lpCommandLine
,
1430 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
1431 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
1432 BOOL bInheritHandles
,
1433 DWORD dwCreationFlags
,
1434 LPVOID lpEnvironment
,
1435 LPCSTR lpCurrentDirectory
,
1436 LPSTARTUPINFOA lpStartupInfo
,
1437 LPPROCESS_INFORMATION lpProcessInformation
,
1440 PUNICODE_STRING CommandLine
= NULL
;
1441 UNICODE_STRING DummyString
;
1442 UNICODE_STRING LiveCommandLine
;
1443 UNICODE_STRING ApplicationName
;
1444 UNICODE_STRING CurrentDirectory
;
1446 STARTUPINFOW StartupInfo
;
1448 DPRINT("dwCreationFlags %x, lpEnvironment %x, lpCurrentDirectory %x, "
1449 "lpStartupInfo %x, lpProcessInformation %x\n",
1450 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
1451 lpStartupInfo
, lpProcessInformation
);
1453 /* Copy Startup Info */
1454 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
1456 /* Initialize all strings to nothing */
1457 LiveCommandLine
.Buffer
= NULL
;
1458 DummyString
.Buffer
= NULL
;
1459 ApplicationName
.Buffer
= NULL
;
1460 CurrentDirectory
.Buffer
= NULL
;
1461 StartupInfo
.lpDesktop
= NULL
;
1462 StartupInfo
.lpReserved
= NULL
;
1463 StartupInfo
.lpTitle
= NULL
;
1465 /* Convert the Command line */
1468 /* If it's too long, then we'll have a problem */
1469 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
1470 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
1472 /* Cache it in the TEB */
1473 CommandLine
= Basep8BitStringToCachedUnicodeString(lpCommandLine
);
1477 /* Use a dynamic version */
1478 Basep8BitStringToHeapUnicodeString(&LiveCommandLine
,
1484 /* The logic below will use CommandLine, so we must make it valid */
1485 CommandLine
= &DummyString
;
1488 /* Convert the Name and Directory */
1489 if (lpApplicationName
)
1491 Basep8BitStringToHeapUnicodeString(&ApplicationName
,
1494 if (lpCurrentDirectory
)
1496 Basep8BitStringToHeapUnicodeString(&CurrentDirectory
,
1497 lpCurrentDirectory
);
1500 /* Now convert Startup Strings */
1501 if (lpStartupInfo
->lpReserved
)
1503 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
1504 &StartupInfo
.lpReserved
);
1506 if (lpStartupInfo
->lpDesktop
)
1508 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
1509 &StartupInfo
.lpDesktop
);
1511 if (lpStartupInfo
->lpTitle
)
1513 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
1514 &StartupInfo
.lpTitle
);
1517 /* Call the Unicode function */
1518 bRetVal
= CreateProcessInternalW(hToken
,
1519 ApplicationName
.Buffer
,
1520 LiveCommandLine
.Buffer
?
1521 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
1522 lpProcessAttributes
,
1527 CurrentDirectory
.Buffer
,
1529 lpProcessInformation
,
1533 RtlFreeUnicodeString(&ApplicationName
);
1534 RtlFreeUnicodeString(&LiveCommandLine
);
1535 RtlFreeUnicodeString(&CurrentDirectory
);
1536 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpDesktop
);
1537 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpReserved
);
1538 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpTitle
);
1540 /* Return what Unicode did */
1545 * FUNCTION: The CreateProcess function creates a new process and its
1546 * primary thread. The new process executes the specified executable file
1549 * lpApplicationName = Pointer to name of executable module
1550 * lpCommandLine = Pointer to command line string
1551 * lpProcessAttributes = Process security attributes
1552 * lpThreadAttributes = Thread security attributes
1553 * bInheritHandles = Handle inheritance flag
1554 * dwCreationFlags = Creation flags
1555 * lpEnvironment = Pointer to new environment block
1556 * lpCurrentDirectory = Pointer to current directory name
1557 * lpStartupInfo = Pointer to startup info
1558 * lpProcessInformation = Pointer to process information
1564 CreateProcessA(LPCSTR lpApplicationName
,
1565 LPSTR lpCommandLine
,
1566 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
1567 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
1568 BOOL bInheritHandles
,
1569 DWORD dwCreationFlags
,
1570 LPVOID lpEnvironment
,
1571 LPCSTR lpCurrentDirectory
,
1572 LPSTARTUPINFOA lpStartupInfo
,
1573 LPPROCESS_INFORMATION lpProcessInformation
)
1575 /* Call the internal (but exported) version */
1576 return CreateProcessInternalA(0,
1579 lpProcessAttributes
,
1586 lpProcessInformation
,