2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * FILE: lib/kernel32/proc/proc.c
5 * PURPOSE: Process functions
6 * PROGRAMMERS: Ariadne (ariadne@xs4all.nl)
11 /* INCLUDES ****************************************************************/
18 /* GLOBALS *******************************************************************/
20 WaitForInputIdleType UserWaitForInputIdleRoutine
;
21 UNICODE_STRING BaseUnicodeCommandLine
;
22 ANSI_STRING BaseAnsiCommandLine
;
23 UNICODE_STRING BasePathVariableName
= RTL_CONSTANT_STRING(L
"PATH");
24 LPSTARTUPINFOA BaseAnsiStartupInfo
= NULL
;
25 PLDR_DATA_TABLE_ENTRY BasepExeLdrEntry
;
26 BOOLEAN g_AppCertInitialized
;
27 BOOLEAN g_HaveAppCerts
;
28 LIST_ENTRY BasepAppCertDllsList
;
29 RTL_CRITICAL_SECTION gcsAppCert
;
30 PBASEP_APPCERT_EMBEDDED_FUNC fEmbeddedCertFunc
;
31 NTSTATUS g_AppCertStatus
;
32 RTL_QUERY_REGISTRY_TABLE BasepAppCertTable
[2] =
35 BasepConfigureAppCertDlls
,
38 &BasepAppCertDllsList
,
45 PSAFER_REPLACE_PROCESS_THREAD_TOKENS g_SaferReplaceProcessThreadTokens
;
46 HMODULE gSaferHandle
= (HMODULE
)-1;
49 RegisterWaitForInputIdle(WaitForInputIdleType lpfnRegisterWaitForInputIdle
);
51 #define CMD_STRING L"cmd /c "
53 /* FUNCTIONS ****************************************************************/
57 StuffStdHandle(IN HANDLE ProcessHandle
,
58 IN HANDLE StandardHandle
,
62 HANDLE DuplicatedHandle
;
63 SIZE_T NumberOfBytesWritten
;
65 /* If there is no handle to duplicate, return immediately */
66 if (!StandardHandle
) return;
68 /* Duplicate the handle */
69 Status
= NtDuplicateObject(NtCurrentProcess(),
75 DUPLICATE_SAME_ACCESS
|
76 DUPLICATE_SAME_ATTRIBUTES
);
77 if (!NT_SUCCESS(Status
)) return;
80 NtWriteVirtualMemory(ProcessHandle
,
84 &NumberOfBytesWritten
);
89 BuildSubSysCommandLine(IN LPCWSTR SubsystemName
,
90 IN LPCWSTR ApplicationName
,
91 IN LPCWSTR CommandLine
,
92 OUT PUNICODE_STRING SubsysCommandLine
)
94 UNICODE_STRING CommandLineString
, ApplicationNameString
;
98 /* Convert to unicode strings */
99 RtlInitUnicodeString(&CommandLineString
, ApplicationName
);
100 RtlInitUnicodeString(&ApplicationNameString
, CommandLine
);
102 /* Allocate buffer for the output string */
103 Length
= CommandLineString
.MaximumLength
+ ApplicationNameString
.MaximumLength
+ 32;
104 Buffer
= RtlAllocateHeap(RtlGetProcessHeap(), 0, Length
);
105 RtlInitEmptyUnicodeString(SubsysCommandLine
, Buffer
, (USHORT
)Length
);
108 /* Fail, no memory */
109 BaseSetLastNTError(STATUS_NO_MEMORY
);
113 /* Build the final subsystem command line */
114 RtlAppendUnicodeToString(SubsysCommandLine
, SubsystemName
);
115 RtlAppendUnicodeStringToString(SubsysCommandLine
, &CommandLineString
);
116 RtlAppendUnicodeToString(SubsysCommandLine
, L
" /C ");
117 RtlAppendUnicodeStringToString(SubsysCommandLine
, &ApplicationNameString
);
123 BasepIsImageVersionOk(IN ULONG ImageMajorVersion
,
124 IN ULONG ImageMinorVersion
)
126 /* Accept images for NT 3.1 or higher, as long as they're not newer than us */
127 return ((ImageMajorVersion
>= 3) &&
128 ((ImageMajorVersion
!= 3) ||
129 (ImageMinorVersion
>= 10)) &&
130 (ImageMajorVersion
<= SharedUserData
->NtMajorVersion
) &&
131 ((ImageMajorVersion
!= SharedUserData
->NtMajorVersion
) ||
132 (ImageMinorVersion
<= SharedUserData
->NtMinorVersion
)));
137 BasepCheckWebBladeHashes(IN HANDLE FileHandle
)
142 /* Get all the MD5 hashes */
143 Status
= RtlComputeImportTableHash(FileHandle
, Hash
, 1);
144 if (!NT_SUCCESS(Status
)) return Status
;
146 /* Depending on which suite this is, run a bsearch and block the appropriate ones */
147 if (SharedUserData
->SuiteMask
& VER_SUITE_COMPUTE_SERVER
)
149 DPRINT1("Egad! This is a ReactOS Compute Server and we should prevent you from using certain APIs...but we won't.");
151 else if (SharedUserData
->SuiteMask
& VER_SUITE_STORAGE_SERVER
)
153 DPRINT1("Gasp! This is a ReactOS Storage Server and we should prevent you from using certain APIs...but we won't.");
155 else if (SharedUserData
->SuiteMask
& VER_SUITE_BLADE
)
157 DPRINT1("Golly! This is a ReactOS Web Blade Server and we should prevent you from using certain APIs...but we won't.");
160 /* Actually, fuck it, don't block anything, we're open source */
161 return STATUS_SUCCESS
;
166 BasepSaveAppCertRegistryValue(IN PLIST_ENTRY List
,
167 IN PWCHAR ComponentName
,
170 /* Pretty much the only thing this key is used for, is malware */
172 return STATUS_NOT_IMPLEMENTED
;
177 BasepConfigureAppCertDlls(IN PWSTR ValueName
,
180 IN ULONG ValueLength
,
182 IN PVOID EntryContext
)
184 /* Add this to the certification list */
185 return BasepSaveAppCertRegistryValue(Context
, ValueName
, ValueData
);
190 BasepIsProcessAllowed(IN LPWSTR ApplicationName
)
192 NTSTATUS Status
, Status1
;
195 HMODULE TrustLibrary
;
196 PBASEP_APPCERT_ENTRY Entry
;
198 PLIST_ENTRY NextEntry
;
200 UNICODE_STRING CertKey
= RTL_CONSTANT_STRING(L
"\\Registry\\MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\AppCertDlls");
201 OBJECT_ATTRIBUTES KeyAttributes
= RTL_CONSTANT_OBJECT_ATTRIBUTES(&CertKey
, OBJ_CASE_INSENSITIVE
);
203 /* Try to initialize the certification subsystem */
204 while (!g_AppCertInitialized
)
207 Status
= STATUS_SUCCESS
;
210 /* Acquire the lock while initializing and see if we lost a race */
211 RtlEnterCriticalSection(&gcsAppCert
);
212 if (g_AppCertInitialized
) break;
214 /* On embedded, there is a special DLL */
215 if (SharedUserData
->SuiteMask
& VER_SUITE_EMBEDDEDNT
)
217 /* Allocate a buffer for the name */
218 Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
220 MAX_PATH
* sizeof(WCHAR
) +
221 sizeof(UNICODE_NULL
));
224 /* Fail if no memory */
225 Status
= STATUS_NO_MEMORY
;
229 /* Now get the system32 directory in our buffer, make sure it fits */
230 Length
= GetSystemDirectoryW(Buffer
, MAX_PATH
- sizeof("EmbdTrst.DLL"));
231 if ((Length
) && (Length
<= MAX_PATH
- sizeof("EmbdTrst.DLL")))
233 /* Add a slash if needed, and add the embedded cert DLL name */
234 if (Buffer
[Length
- 1] != '\\') Buffer
[Length
++] = '\\';
235 RtlCopyMemory(&Buffer
[Length
],
237 sizeof(L
"EmbdTrst.DLL"));
240 TrustLibrary
= LoadLibraryW(Buffer
);
243 /* And extract the special function out of it */
244 fEmbeddedCertFunc
= (PVOID
)GetProcAddress(TrustLibrary
,
245 "ImageOkToRunOnEmbeddedNT");
249 /* If we didn't get this far, set a failure code */
250 if (!fEmbeddedCertFunc
) Status
= STATUS_UNSUCCESSFUL
;
255 /* Other systems have a registry entry for this */
256 Status1
= NtOpenKey(&KeyHandle
, KEY_READ
, &KeyAttributes
);
257 if (NT_SUCCESS(Status1
))
259 /* Close it, we'll query it through Rtl */
262 /* Do the query, which will call a special callback */
263 Status
= RtlQueryRegistryValues(RTL_REGISTRY_CONTROL
,
268 if (Status
== STATUS_OBJECT_NAME_NOT_FOUND
)
270 Status
= STATUS_SUCCESS
;
275 /* Free any buffer if we had one */
276 if (Buffer
) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer
);
278 /* Check for errors, or a missing embedded/custom certification DLL */
279 if (!NT_SUCCESS(Status
) ||
280 (!(fEmbeddedCertFunc
) && (IsListEmpty(&BasepAppCertDllsList
))))
282 /* The subsystem is not active on this machine, so give up */
283 g_HaveAppCerts
= FALSE
;
284 g_AppCertStatus
= Status
;
288 /* We have certification DLLs active, remember this */
289 g_HaveAppCerts
= TRUE
;
292 /* We are done the initialization phase, release the lock */
293 g_AppCertInitialized
= TRUE
;
294 RtlLeaveCriticalSection(&gcsAppCert
);
297 /* If there's no certification DLLs present, return the failure code */
298 if (!g_HaveAppCerts
) return g_AppCertStatus
;
300 /* Otherwise, assume success and make sure we have *something* */
301 ASSERT(fEmbeddedCertFunc
|| !IsListEmpty(&BasepAppCertDllsList
));
302 Status
= STATUS_SUCCESS
;
304 /* If the something is an embedded certification DLL, call it and return */
305 if (fEmbeddedCertFunc
) return fEmbeddedCertFunc(ApplicationName
);
307 /* Otherwise we have custom certification DLLs, parse them */
308 NextEntry
= BasepAppCertDllsList
.Flink
;
310 while (NextEntry
!= &BasepAppCertDllsList
)
312 /* Make sure the entry has a callback */
313 Entry
= CONTAINING_RECORD(NextEntry
, BASEP_APPCERT_ENTRY
, Entry
);
314 ASSERT(Entry
->fPluginCertFunc
!= NULL
);
316 /* Call it and check if it failed */
317 Status
= Entry
->fPluginCertFunc(ApplicationName
, 1);
318 if (!NT_SUCCESS(Status
)) CertFlag
= 3;
321 NextEntry
= NextEntry
->Flink
;
324 /* Now loop them again */
325 NextEntry
= BasepAppCertDllsList
.Flink
;
326 while (NextEntry
!= &BasepAppCertDllsList
)
328 /* Make sure the entry has a callback */
329 Entry
= CONTAINING_RECORD(NextEntry
, BASEP_APPCERT_ENTRY
, Entry
);
330 ASSERT(Entry
->fPluginCertFunc
!= NULL
);
332 /* Call it, this time with the flag from the loop above */
333 Status
= Entry
->fPluginCertFunc(ApplicationName
, CertFlag
);
336 /* All done, return the status */
342 BasepReplaceProcessThreadTokens(IN HANDLE TokenHandle
,
343 IN HANDLE ProcessHandle
,
344 IN HANDLE ThreadHandle
)
347 ANSI_STRING SaferiReplaceProcessThreadTokens
= RTL_CONSTANT_STRING("SaferiReplaceProcessThreadTokens");
349 /* Enter the application certification lock */
350 RtlEnterCriticalSection(&gcsAppCert
);
352 /* Check if we already know the function */
353 if (g_SaferReplaceProcessThreadTokens
)
356 Status
= g_SaferReplaceProcessThreadTokens(TokenHandle
,
364 /* Check if the app certification DLL isn't loaded */
365 if (!(gSaferHandle
) ||
366 (gSaferHandle
== (HMODULE
)-1) ||
367 (gSaferHandle
== (HMODULE
)-2))
369 /* Then we can't call the function */
370 Status
= STATUS_ENTRYPOINT_NOT_FOUND
;
374 /* We have the DLL, find the address of the Safer function */
375 Status
= LdrGetProcedureAddress(gSaferHandle
,
376 &SaferiReplaceProcessThreadTokens
,
378 (PVOID
*)&g_SaferReplaceProcessThreadTokens
);
379 if (NT_SUCCESS(Status
))
381 /* Found it, now call it */
382 Status
= g_SaferReplaceProcessThreadTokens(TokenHandle
,
390 /* We couldn't find it, so this must be an unsupported DLL */
391 LdrUnloadDll(gSaferHandle
);
393 Status
= STATUS_ENTRYPOINT_NOT_FOUND
;
398 /* Release the lock and return the result */
399 RtlLeaveCriticalSection(&gcsAppCert
);
405 BasepSxsCloseHandles(IN PBASE_MSG_SXS_HANDLES Handles
)
410 ASSERT(Handles
!= NULL
);
411 ASSERT(Handles
->Process
== NULL
|| Handles
->Process
== NtCurrentProcess());
413 /* Close the file handle */
416 Status
= NtClose(Handles
->File
);
417 ASSERT(NT_SUCCESS(Status
));
420 /* Close the section handle */
421 if (Handles
->Section
)
423 Status
= NtClose(Handles
->Section
);
424 ASSERT(NT_SUCCESS(Status
));
427 /* Unmap the section view */
428 if (Handles
->ViewBase
.QuadPart
)
430 Status
= NtUnmapViewOfSection(NtCurrentProcess(),
431 (PVOID
)Handles
->ViewBase
.LowPart
);
432 ASSERT(NT_SUCCESS(Status
));
437 LONG
BaseExceptionFilter(EXCEPTION_POINTERS
*ExceptionInfo
)
439 LONG ExceptionDisposition
= EXCEPTION_EXECUTE_HANDLER
;
440 LPTOP_LEVEL_EXCEPTION_FILTER RealFilter
;
441 RealFilter
= RtlDecodePointer(GlobalTopLevelExceptionFilter
);
443 if (RealFilter
!= NULL
)
447 ExceptionDisposition
= RealFilter(ExceptionInfo
);
449 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
454 if ((ExceptionDisposition
== EXCEPTION_CONTINUE_SEARCH
|| ExceptionDisposition
== EXCEPTION_EXECUTE_HANDLER
) &&
455 RealFilter
!= UnhandledExceptionFilter
)
457 ExceptionDisposition
= UnhandledExceptionFilter(ExceptionInfo
);
460 return ExceptionDisposition
;
465 BaseProcessStartup(PPROCESS_START_ROUTINE lpStartAddress
)
467 DPRINT("BaseProcessStartup(..) - setting up exception frame.\n");
471 /* Set our Start Address */
472 NtSetInformationThread(NtCurrentThread(),
473 ThreadQuerySetWin32StartAddress
,
475 sizeof(PPROCESS_START_ROUTINE
));
477 /* Call the Start Routine */
478 ExitThread(lpStartAddress());
480 _SEH2_EXCEPT(BaseExceptionFilter(_SEH2_GetExceptionInformation()))
482 /* Get the Exit code from the SEH Handler */
483 if (!BaseRunningInServerProcess
)
485 /* Kill the whole process, usually */
486 ExitProcess(_SEH2_GetExceptionCode());
490 /* If running inside CSRSS, kill just this thread */
491 ExitThread(_SEH2_GetExceptionCode());
499 BasepNotifyCsrOfThread(IN HANDLE ThreadHandle
,
500 IN PCLIENT_ID ClientId
)
503 BASE_API_MESSAGE ApiMessage
;
504 PBASE_CREATE_THREAD CreateThreadRequest
= &ApiMessage
.Data
.CreateThreadRequest
;
506 DPRINT("BasepNotifyCsrOfThread: Thread: %p, Handle %p\n",
507 ClientId
->UniqueThread
, ThreadHandle
);
509 /* Fill out the request */
510 CreateThreadRequest
->ClientId
= *ClientId
;
511 CreateThreadRequest
->ThreadHandle
= ThreadHandle
;
514 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
516 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepCreateThread
),
517 sizeof(BASE_CREATE_THREAD
));
518 if (!NT_SUCCESS(Status
))
520 DPRINT1("Failed to tell CSRSS about new thread: %lx\n", Status
);
525 return STATUS_SUCCESS
;
530 BasePushProcessParameters(IN ULONG ParameterFlags
,
531 IN HANDLE ProcessHandle
,
533 IN LPCWSTR ApplicationPathName
,
534 IN LPWSTR lpCurrentDirectory
,
535 IN LPWSTR lpCommandLine
,
536 IN LPVOID lpEnvironment
,
537 IN LPSTARTUPINFOW StartupInfo
,
538 IN DWORD CreationFlags
,
539 IN BOOL InheritHandles
,
540 IN ULONG ImageSubsystem
,
541 IN PVOID AppCompatData
,
542 IN ULONG AppCompatDataSize
)
544 WCHAR FullPath
[MAX_PATH
+ 5];
545 PWCHAR Remaining
, DllPathString
, ScanChar
;
546 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
, RemoteParameters
;
547 PVOID RemoteAppCompatData
;
548 UNICODE_STRING DllPath
, ImageName
, CommandLine
, CurrentDirectory
;
549 UNICODE_STRING Desktop
, Shell
, Runtime
, Title
;
553 BOOLEAN HavePebLock
= FALSE
, Result
;
554 PPEB Peb
= NtCurrentPeb();
556 /* Get the full path name */
557 Size
= GetFullPathNameW(ApplicationPathName
,
561 if ((Size
) && (Size
<= (MAX_PATH
+ 4)))
563 /* Get the DLL Path */
564 DllPathString
= BaseComputeProcessDllPath(FullPath
, lpEnvironment
);
568 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
572 /* Initialize Strings */
573 RtlInitUnicodeString(&DllPath
, DllPathString
);
574 RtlInitUnicodeString(&ImageName
, FullPath
);
578 /* Couldn't get the path name. Just take the original path */
579 DllPathString
= BaseComputeProcessDllPath((LPWSTR
)ApplicationPathName
,
584 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
588 /* Initialize Strings */
589 RtlInitUnicodeString(&DllPath
, DllPathString
);
590 RtlInitUnicodeString(&ImageName
, ApplicationPathName
);
593 /* Initialize Strings */
594 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
595 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
597 /* Initialize more Strings from the Startup Info */
598 if (StartupInfo
->lpDesktop
)
600 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
604 RtlInitUnicodeString(&Desktop
, L
"");
606 if (StartupInfo
->lpReserved
)
608 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
612 RtlInitUnicodeString(&Shell
, L
"");
614 if (StartupInfo
->lpTitle
)
616 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
620 RtlInitUnicodeString(&Title
, ApplicationPathName
);
623 /* This one is special because the length can differ */
624 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
625 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
627 /* Enforce no app compat data if the pointer was NULL */
628 if (!AppCompatData
) AppCompatDataSize
= 0;
630 /* Create the Parameter Block */
631 ProcessParameters
= NULL
;
632 DPRINT("ImageName: '%wZ'\n", &ImageName
);
633 DPRINT("DllPath : '%wZ'\n", &DllPath
);
634 DPRINT("CurDir : '%wZ'\n", &CurrentDirectory
);
635 DPRINT("CmdLine : '%wZ'\n", &CommandLine
);
636 DPRINT("Title : '%wZ'\n", &Title
);
637 DPRINT("Desktop : '%wZ'\n", &Desktop
);
638 DPRINT("Shell : '%wZ'\n", &Shell
);
639 DPRINT("Runtime : '%wZ'\n", &Runtime
);
640 Status
= RtlCreateProcessParameters(&ProcessParameters
,
644 &CurrentDirectory
: NULL
,
651 if (!NT_SUCCESS(Status
)) goto FailPath
;
653 /* Clear the current directory handle if not inheriting */
654 if (!InheritHandles
) ProcessParameters
->CurrentDirectory
.Handle
= NULL
;
656 /* Check if the user passed in an environment */
659 /* We should've made it part of the parameters block, enforce this */
660 ASSERT(ProcessParameters
->Environment
== lpEnvironment
);
661 lpEnvironment
= ProcessParameters
->Environment
;
665 /* The user did not, so use the one from the current PEB */
668 lpEnvironment
= Peb
->ProcessParameters
->Environment
;
671 /* Save pointer and start lookup */
672 ScanChar
= lpEnvironment
;
675 /* Find the environment size */
676 while ((ScanChar
[0]) || (ScanChar
[1])) ++ScanChar
;
677 ScanChar
+= (2 * sizeof(UNICODE_NULL
));
678 EnviroSize
= (ULONG_PTR
)ScanChar
- (ULONG_PTR
)lpEnvironment
;
680 /* Allocate and Initialize new Environment Block */
682 ProcessParameters
->Environment
= NULL
;
683 Status
= NtAllocateVirtualMemory(ProcessHandle
,
684 (PVOID
*)&ProcessParameters
->Environment
,
689 if (!NT_SUCCESS(Status
)) goto FailPath
;
691 /* Write the Environment Block */
692 Status
= NtWriteVirtualMemory(ProcessHandle
,
693 ProcessParameters
->Environment
,
698 /* No longer need the PEB lock anymore */
706 /* Check if the write failed */
707 if (!NT_SUCCESS(Status
)) goto FailPath
;
710 /* Write new parameters */
711 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
712 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
713 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
714 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
715 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
716 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
717 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
718 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
719 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
721 /* Write the handles only if we have to */
722 if (StartupInfo
->dwFlags
&
723 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
725 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
726 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
727 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
730 /* Use Special Flags for BasepInitConsole in Kernel32 */
731 if (CreationFlags
& DETACHED_PROCESS
)
733 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
735 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
737 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
739 else if (CreationFlags
& CREATE_NO_WINDOW
)
741 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
745 /* Inherit our Console Handle */
746 ProcessParameters
->ConsoleHandle
= Peb
->ProcessParameters
->ConsoleHandle
;
748 /* Make sure that the shell isn't trampling on our handles first */
749 if (!(StartupInfo
->dwFlags
&
750 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
752 /* Copy the handle if we are inheriting or if it's a console handle */
753 if ((InheritHandles
) ||
754 (IsConsoleHandle(Peb
->ProcessParameters
->StandardInput
)))
756 ProcessParameters
->StandardInput
= Peb
->ProcessParameters
->StandardInput
;
758 if ((InheritHandles
) ||
759 (IsConsoleHandle(Peb
->ProcessParameters
->StandardOutput
)))
761 ProcessParameters
->StandardOutput
= Peb
->ProcessParameters
->StandardOutput
;
763 if ((InheritHandles
) ||
764 (IsConsoleHandle(Peb
->ProcessParameters
->StandardError
)))
766 ProcessParameters
->StandardError
= Peb
->ProcessParameters
->StandardError
;
771 /* Also set the Console Flag */
772 if ((CreationFlags
& CREATE_NEW_PROCESS_GROUP
) &&
773 (!(CreationFlags
& CREATE_NEW_CONSOLE
)))
775 ProcessParameters
->ConsoleFlags
= 1;
778 /* Check if there's a .local file present */
779 if (ParameterFlags
& 1)
781 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_LOCAL_DLL_PATH
;
784 /* Check if we failed to open the IFEO key */
785 if (ParameterFlags
& 2)
787 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_IMAGE_KEY_MISSING
;
790 /* Allocate memory for the parameter block */
791 Size
= ProcessParameters
->Length
;
792 RemoteParameters
= NULL
;
793 Status
= NtAllocateVirtualMemory(ProcessHandle
,
794 (PVOID
*)&RemoteParameters
,
799 if (!NT_SUCCESS(Status
)) goto FailPath
;
801 /* Set the allocated size */
802 ProcessParameters
->MaximumLength
= Size
;
804 /* Handle some Parameter Flags */
805 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
806 RTL_USER_PROCESS_PARAMETERS_PROFILE_USER
: 0;
807 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
808 RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL
: 0;
809 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
810 RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER
: 0;
811 ProcessParameters
->Flags
|= (Peb
->ProcessParameters
->Flags
&
812 RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_CHECKS
);
814 /* Write the Parameter Block */
815 Status
= NtWriteVirtualMemory(ProcessHandle
,
818 ProcessParameters
->Length
,
820 if (!NT_SUCCESS(Status
)) goto FailPath
;
822 /* Write the PEB Pointer */
823 Status
= NtWriteVirtualMemory(ProcessHandle
,
824 &RemotePeb
->ProcessParameters
,
828 if (!NT_SUCCESS(Status
)) goto FailPath
;
830 /* Check if there's any app compat data to write */
831 RemoteAppCompatData
= NULL
;
834 /* Allocate some space for the application compatibility data */
835 Size
= AppCompatDataSize
;
836 Status
= NtAllocateVirtualMemory(ProcessHandle
,
837 &RemoteAppCompatData
,
842 if (!NT_SUCCESS(Status
)) goto FailPath
;
844 /* Write the application compatibility data */
845 Status
= NtWriteVirtualMemory(ProcessHandle
,
850 if (!NT_SUCCESS(Status
)) goto FailPath
;
853 /* Write the PEB Pointer to the app compat data (might be NULL) */
854 Status
= NtWriteVirtualMemory(ProcessHandle
,
855 &RemotePeb
->pShimData
,
856 &RemoteAppCompatData
,
859 if (!NT_SUCCESS(Status
)) goto FailPath
;
861 /* Now write Peb->ImageSubSystem */
864 NtWriteVirtualMemory(ProcessHandle
,
865 &RemotePeb
->ImageSubsystem
,
867 sizeof(ImageSubsystem
),
876 if (HavePebLock
) RtlReleasePebLock();
877 RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath
.Buffer
);
878 if (ProcessParameters
) RtlDestroyProcessParameters(ProcessParameters
);
881 DPRINT1("Failure to create process parameters: %lx\n", Status
);
882 BaseSetLastNTError(Status
);
889 InitCommandLines(VOID
)
893 /* Read the UNICODE_STRING from the PEB */
894 BaseUnicodeCommandLine
= NtCurrentPeb()->ProcessParameters
->CommandLine
;
896 /* Convert to ANSI_STRING for the *A callers */
897 Status
= RtlUnicodeStringToAnsiString(&BaseAnsiCommandLine
,
898 &BaseUnicodeCommandLine
,
900 if (!NT_SUCCESS(Status
)) RtlInitEmptyAnsiString(&BaseAnsiCommandLine
, 0, 0);
903 /* PUBLIC FUNCTIONS ***********************************************************/
910 GetProcessAffinityMask(IN HANDLE hProcess
,
911 OUT PDWORD_PTR lpProcessAffinityMask
,
912 OUT PDWORD_PTR lpSystemAffinityMask
)
914 PROCESS_BASIC_INFORMATION ProcessInfo
;
917 /* Query information on the process from the kernel */
918 Status
= NtQueryInformationProcess(hProcess
,
919 ProcessBasicInformation
,
921 sizeof(PROCESS_BASIC_INFORMATION
),
923 if (!NT_SUCCESS(Status
))
926 BaseSetLastNTError(Status
);
930 /* Copy the affinity mask, and get the system one from our shared data */
931 *lpProcessAffinityMask
= (DWORD
)ProcessInfo
.AffinityMask
;
932 *lpSystemAffinityMask
= (DWORD
)BaseStaticServerData
->SysInfo
.ActiveProcessorsAffinityMask
;
941 SetProcessAffinityMask(IN HANDLE hProcess
,
942 IN DWORD_PTR dwProcessAffinityMask
)
946 /* Directly set the affinity mask */
947 Status
= NtSetInformationProcess(hProcess
,
949 (PVOID
)&dwProcessAffinityMask
,
951 if (!NT_SUCCESS(Status
))
954 BaseSetLastNTError(Status
);
958 /* Everything was ok */
967 GetProcessShutdownParameters(OUT LPDWORD lpdwLevel
,
968 OUT LPDWORD lpdwFlags
)
971 BASE_API_MESSAGE ApiMessage
;
972 PBASE_GETSET_PROCESS_SHUTDOWN_PARAMS ShutdownParametersRequest
= &ApiMessage
.Data
.ShutdownParametersRequest
;
974 /* Ask CSRSS for shutdown information */
975 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
977 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepGetProcessShutdownParam
),
978 sizeof(BASE_GETSET_PROCESS_SHUTDOWN_PARAMS
));
979 if (!NT_SUCCESS(Status
))
981 /* Return the failure from CSRSS */
982 BaseSetLastNTError(Status
);
986 /* Get the data back */
987 *lpdwLevel
= ShutdownParametersRequest
->ShutdownLevel
;
988 *lpdwFlags
= ShutdownParametersRequest
->ShutdownFlags
;
997 SetProcessShutdownParameters(IN DWORD dwLevel
,
1001 BASE_API_MESSAGE ApiMessage
;
1002 PBASE_GETSET_PROCESS_SHUTDOWN_PARAMS ShutdownParametersRequest
= &ApiMessage
.Data
.ShutdownParametersRequest
;
1004 /* Write the data into the CSRSS request and send it */
1005 ShutdownParametersRequest
->ShutdownLevel
= dwLevel
;
1006 ShutdownParametersRequest
->ShutdownFlags
= dwFlags
;
1007 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
1009 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepSetProcessShutdownParam
),
1010 sizeof(BASE_GETSET_PROCESS_SHUTDOWN_PARAMS
));
1011 if (!NT_SUCCESS(Status
))
1013 /* Return the failure from CSRSS */
1014 BaseSetLastNTError(Status
);
1027 GetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1028 OUT PSIZE_T lpMinimumWorkingSetSize
,
1029 OUT PSIZE_T lpMaximumWorkingSetSize
,
1032 QUOTA_LIMITS_EX QuotaLimits
;
1035 /* Query the kernel about this */
1036 Status
= NtQueryInformationProcess(hProcess
,
1039 sizeof(QUOTA_LIMITS_EX
),
1041 if (!NT_SUCCESS(Status
))
1044 BaseSetLastNTError(Status
);
1048 /* Copy the quota information out */
1049 *lpMinimumWorkingSetSize
= QuotaLimits
.MinimumWorkingSetSize
;
1050 *lpMaximumWorkingSetSize
= QuotaLimits
.MaximumWorkingSetSize
;
1051 *Flags
= QuotaLimits
.Flags
;
1060 GetProcessWorkingSetSize(IN HANDLE hProcess
,
1061 OUT PSIZE_T lpMinimumWorkingSetSize
,
1062 OUT PSIZE_T lpMaximumWorkingSetSize
)
1065 return GetProcessWorkingSetSizeEx(hProcess
,
1066 lpMinimumWorkingSetSize
,
1067 lpMaximumWorkingSetSize
,
1076 SetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1077 IN SIZE_T dwMinimumWorkingSetSize
,
1078 IN SIZE_T dwMaximumWorkingSetSize
,
1081 QUOTA_LIMITS_EX QuotaLimits
;
1082 NTSTATUS Status
, ReturnStatus
;
1085 ULONG Privilege
= SE_INC_BASE_PRIORITY_PRIVILEGE
;
1087 /* Zero out the input structure */
1088 RtlZeroMemory(&QuotaLimits
, sizeof(QuotaLimits
));
1090 /* Check if the caller sent any limits */
1091 if ((dwMinimumWorkingSetSize
) && (dwMaximumWorkingSetSize
))
1093 /* Write the quota information */
1094 QuotaLimits
.MinimumWorkingSetSize
= dwMinimumWorkingSetSize
;
1095 QuotaLimits
.MaximumWorkingSetSize
= dwMaximumWorkingSetSize
;
1096 QuotaLimits
.Flags
= Flags
;
1098 /* Acquire the required privilege */
1099 Status
= RtlAcquirePrivilege(&Privilege
, 1, 0, &State
);
1101 /* Request the new quotas */
1102 ReturnStatus
= NtSetInformationProcess(hProcess
,
1105 sizeof(QuotaLimits
));
1106 Result
= NT_SUCCESS(ReturnStatus
);
1107 if (NT_SUCCESS(Status
))
1109 /* Release the privilege and set succes code */
1110 ASSERT(State
!= NULL
);
1111 RtlReleasePrivilege(State
);
1117 /* No limits, fail the call */
1118 ReturnStatus
= STATUS_INVALID_PARAMETER
;
1122 /* Return result code, set error code if this was a failure */
1123 if (!Result
) BaseSetLastNTError(ReturnStatus
);
1132 SetProcessWorkingSetSize(IN HANDLE hProcess
,
1133 IN SIZE_T dwMinimumWorkingSetSize
,
1134 IN SIZE_T dwMaximumWorkingSetSize
)
1136 /* Call the newer API */
1137 return SetProcessWorkingSetSizeEx(hProcess
,
1138 dwMinimumWorkingSetSize
,
1139 dwMaximumWorkingSetSize
,
1148 GetProcessTimes(IN HANDLE hProcess
,
1149 IN LPFILETIME lpCreationTime
,
1150 IN LPFILETIME lpExitTime
,
1151 IN LPFILETIME lpKernelTime
,
1152 IN LPFILETIME lpUserTime
)
1154 KERNEL_USER_TIMES Kut
;
1157 /* Query the times */
1158 Status
= NtQueryInformationProcess(hProcess
,
1163 if (!NT_SUCCESS(Status
))
1165 /* Handle failure */
1166 BaseSetLastNTError(Status
);
1170 /* Copy all the times and return success */
1171 lpCreationTime
->dwLowDateTime
= Kut
.CreateTime
.u
.LowPart
;
1172 lpCreationTime
->dwHighDateTime
= Kut
.CreateTime
.u
.HighPart
;
1173 lpExitTime
->dwLowDateTime
= Kut
.ExitTime
.u
.LowPart
;
1174 lpExitTime
->dwHighDateTime
= Kut
.ExitTime
.u
.HighPart
;
1175 lpKernelTime
->dwLowDateTime
= Kut
.KernelTime
.u
.LowPart
;
1176 lpKernelTime
->dwHighDateTime
= Kut
.KernelTime
.u
.HighPart
;
1177 lpUserTime
->dwLowDateTime
= Kut
.UserTime
.u
.LowPart
;
1178 lpUserTime
->dwHighDateTime
= Kut
.UserTime
.u
.HighPart
;
1187 GetCurrentProcess(VOID
)
1189 return (HANDLE
)NtCurrentProcess();
1197 GetCurrentThread(VOID
)
1199 return (HANDLE
)NtCurrentThread();
1207 GetCurrentProcessId(VOID
)
1209 return HandleToUlong(NtCurrentTeb()->ClientId
.UniqueProcess
);
1217 GetExitCodeProcess(IN HANDLE hProcess
,
1218 IN LPDWORD lpExitCode
)
1220 PROCESS_BASIC_INFORMATION ProcessBasic
;
1223 /* Ask the kernel */
1224 Status
= NtQueryInformationProcess(hProcess
,
1225 ProcessBasicInformation
,
1227 sizeof(PROCESS_BASIC_INFORMATION
),
1229 if (!NT_SUCCESS(Status
))
1231 /* We failed, was this because this is a VDM process? */
1232 if (BaseCheckForVDM(hProcess
, lpExitCode
) == TRUE
) return TRUE
;
1234 /* Not a VDM process, fail the call */
1235 BaseSetLastNTError(Status
);
1239 /* Succes case, return the exit code */
1240 *lpExitCode
= (DWORD
)ProcessBasic
.ExitStatus
;
1249 GetProcessId(IN HANDLE Process
)
1251 PROCESS_BASIC_INFORMATION ProcessBasic
;
1254 /* Query the kernel */
1255 Status
= NtQueryInformationProcess(Process
,
1256 ProcessBasicInformation
,
1258 sizeof(PROCESS_BASIC_INFORMATION
),
1260 if (!NT_SUCCESS(Status
))
1262 /* Handle failure */
1263 BaseSetLastNTError(Status
);
1267 /* Return the PID */
1268 return (DWORD
)ProcessBasic
.UniqueProcessId
;
1276 OpenProcess(IN DWORD dwDesiredAccess
,
1277 IN BOOL bInheritHandle
,
1278 IN DWORD dwProcessId
)
1281 HANDLE ProcessHandle
;
1282 OBJECT_ATTRIBUTES ObjectAttributes
;
1285 /* Setup the input client ID structure */
1286 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
1287 ClientId
.UniqueThread
= 0;
1289 /* This is needed just to define the inheritance flags */
1290 InitializeObjectAttributes(&ObjectAttributes
,
1292 (bInheritHandle
? OBJ_INHERIT
: 0),
1296 /* Now try to open the process */
1297 Status
= NtOpenProcess(&ProcessHandle
,
1301 if (!NT_SUCCESS(Status
))
1303 /* Handle failure */
1304 BaseSetLastNTError(Status
);
1308 /* Otherwise return a handle to the process */
1309 return ProcessHandle
;
1317 RegisterWaitForInputIdle(IN WaitForInputIdleType lpfnRegisterWaitForInputIdle
)
1319 /* Write the global function pointer */
1320 UserWaitForInputIdleRoutine
= lpfnRegisterWaitForInputIdle
;
1328 GetStartupInfoW(IN LPSTARTUPINFOW lpStartupInfo
)
1330 PRTL_USER_PROCESS_PARAMETERS Params
;
1332 /* Get the process parameters */
1333 Params
= NtCurrentPeb()->ProcessParameters
;
1335 /* Copy the data out of there */
1336 lpStartupInfo
->cb
= sizeof(STARTUPINFOW
);
1337 lpStartupInfo
->lpReserved
= Params
->ShellInfo
.Buffer
;
1338 lpStartupInfo
->lpDesktop
= Params
->DesktopInfo
.Buffer
;
1339 lpStartupInfo
->lpTitle
= Params
->WindowTitle
.Buffer
;
1340 lpStartupInfo
->dwX
= Params
->StartingX
;
1341 lpStartupInfo
->dwY
= Params
->StartingY
;
1342 lpStartupInfo
->dwXSize
= Params
->CountX
;
1343 lpStartupInfo
->dwYSize
= Params
->CountY
;
1344 lpStartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1345 lpStartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1346 lpStartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1347 lpStartupInfo
->dwFlags
= Params
->WindowFlags
;
1348 lpStartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1349 lpStartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1350 lpStartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1352 /* Check if the standard handles are being used for other features */
1353 if (lpStartupInfo
->dwFlags
& (STARTF_USESTDHANDLES
|
1355 STARTF_SHELLPRIVATE
))
1357 /* These are, so copy the standard handles too */
1358 lpStartupInfo
->hStdInput
= Params
->StandardInput
;
1359 lpStartupInfo
->hStdOutput
= Params
->StandardOutput
;
1360 lpStartupInfo
->hStdError
= Params
->StandardError
;
1369 GetStartupInfoA(IN LPSTARTUPINFOA lpStartupInfo
)
1371 PRTL_USER_PROCESS_PARAMETERS Params
;
1372 ANSI_STRING TitleString
, ShellString
, DesktopString
;
1373 LPSTARTUPINFOA StartupInfo
;
1376 /* Get the cached information as well as the PEB parameters */
1377 StartupInfo
= BaseAnsiStartupInfo
;
1378 Params
= NtCurrentPeb()->ProcessParameters
;
1380 /* Check if this is the first time we have to get the cached version */
1381 while (!StartupInfo
)
1383 /* Create new ANSI startup info */
1384 StartupInfo
= RtlAllocateHeap(RtlGetProcessHeap(),
1386 sizeof(*StartupInfo
));
1389 /* Zero out string pointers in case we fail to create them */
1390 StartupInfo
->lpReserved
= 0;
1391 StartupInfo
->lpDesktop
= 0;
1392 StartupInfo
->lpTitle
= 0;
1395 StartupInfo
->cb
= sizeof(*StartupInfo
);
1397 /* Copy what's already stored in the PEB */
1398 StartupInfo
->dwX
= Params
->StartingX
;
1399 StartupInfo
->dwY
= Params
->StartingY
;
1400 StartupInfo
->dwXSize
= Params
->CountX
;
1401 StartupInfo
->dwYSize
= Params
->CountY
;
1402 StartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1403 StartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1404 StartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1405 StartupInfo
->dwFlags
= Params
->WindowFlags
;
1406 StartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1407 StartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1408 StartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1409 StartupInfo
->hStdInput
= Params
->StandardInput
;
1410 StartupInfo
->hStdOutput
= Params
->StandardOutput
;
1411 StartupInfo
->hStdError
= Params
->StandardError
;
1413 /* Copy shell info string */
1414 Status
= RtlUnicodeStringToAnsiString(&ShellString
,
1417 if (NT_SUCCESS(Status
))
1420 StartupInfo
->lpReserved
= ShellString
.Buffer
;
1422 /* Copy desktop info string */
1423 Status
= RtlUnicodeStringToAnsiString(&DesktopString
,
1424 &Params
->DesktopInfo
,
1426 if (NT_SUCCESS(Status
))
1429 StartupInfo
->lpDesktop
= DesktopString
.Buffer
;
1431 /* Copy window title string */
1432 Status
= RtlUnicodeStringToAnsiString(&TitleString
,
1433 &Params
->WindowTitle
,
1435 if (NT_SUCCESS(Status
))
1438 StartupInfo
->lpTitle
= TitleString
.Buffer
;
1440 /* We finished with the ANSI version, try to cache it */
1441 if (!InterlockedCompareExchangePointer(&BaseAnsiStartupInfo
,
1445 /* We were the first thread through, use the data */
1449 /* Someone beat us to it, use their data instead */
1450 StartupInfo
= BaseAnsiStartupInfo
;
1451 Status
= STATUS_SUCCESS
;
1453 /* We're going to free our own stuff, but not raise */
1454 RtlFreeAnsiString(&TitleString
);
1456 RtlFreeAnsiString(&DesktopString
);
1458 RtlFreeAnsiString(&ShellString
);
1460 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
);
1464 /* No memory, fail */
1465 Status
= STATUS_NO_MEMORY
;
1468 /* Raise an error unless we got here due to the race condition */
1469 if (!NT_SUCCESS(Status
)) RtlRaiseStatus(Status
);
1472 /* Now copy from the cached ANSI version */
1473 lpStartupInfo
->cb
= StartupInfo
->cb
;
1474 lpStartupInfo
->lpReserved
= StartupInfo
->lpReserved
;
1475 lpStartupInfo
->lpDesktop
= StartupInfo
->lpDesktop
;
1476 lpStartupInfo
->lpTitle
= StartupInfo
->lpTitle
;
1477 lpStartupInfo
->dwX
= StartupInfo
->dwX
;
1478 lpStartupInfo
->dwY
= StartupInfo
->dwY
;
1479 lpStartupInfo
->dwXSize
= StartupInfo
->dwXSize
;
1480 lpStartupInfo
->dwYSize
= StartupInfo
->dwYSize
;
1481 lpStartupInfo
->dwXCountChars
= StartupInfo
->dwXCountChars
;
1482 lpStartupInfo
->dwYCountChars
= StartupInfo
->dwYCountChars
;
1483 lpStartupInfo
->dwFillAttribute
= StartupInfo
->dwFillAttribute
;
1484 lpStartupInfo
->dwFlags
= StartupInfo
->dwFlags
;
1485 lpStartupInfo
->wShowWindow
= StartupInfo
->wShowWindow
;
1486 lpStartupInfo
->cbReserved2
= StartupInfo
->cbReserved2
;
1487 lpStartupInfo
->lpReserved2
= StartupInfo
->lpReserved2
;
1489 /* Check if the shell is hijacking the handles for other features */
1490 if (lpStartupInfo
->dwFlags
&
1491 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
1493 /* It isn't, so we can return the raw values */
1494 lpStartupInfo
->hStdInput
= StartupInfo
->hStdInput
;
1495 lpStartupInfo
->hStdOutput
= StartupInfo
->hStdOutput
;
1496 lpStartupInfo
->hStdError
= StartupInfo
->hStdError
;
1500 /* It is, so make sure nobody uses these as console handles */
1501 lpStartupInfo
->hStdInput
= INVALID_HANDLE_VALUE
;
1502 lpStartupInfo
->hStdOutput
= INVALID_HANDLE_VALUE
;
1503 lpStartupInfo
->hStdError
= INVALID_HANDLE_VALUE
;
1512 FlushInstructionCache(IN HANDLE hProcess
,
1513 IN LPCVOID lpBaseAddress
,
1518 /* Call the native function */
1519 Status
= NtFlushInstructionCache(hProcess
, (PVOID
)lpBaseAddress
, dwSize
);
1520 if (!NT_SUCCESS(Status
))
1522 /* Handle failure case */
1523 BaseSetLastNTError(Status
);
1536 ExitProcess(IN UINT uExitCode
)
1538 BASE_API_MESSAGE ApiMessage
;
1539 PBASE_EXIT_PROCESS ExitProcessRequest
= &ApiMessage
.Data
.ExitProcessRequest
;
1541 ASSERT(!BaseRunningInServerProcess
);
1545 /* Acquire the PEB lock */
1546 RtlAcquirePebLock();
1548 /* Kill all the threads */
1549 NtTerminateProcess(NULL
, 0);
1551 /* Unload all DLLs */
1552 LdrShutdownProcess();
1554 /* Notify Base Server of process termination */
1555 ExitProcessRequest
->uExitCode
= uExitCode
;
1556 CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
1558 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepExitProcess
),
1559 sizeof(BASE_EXIT_PROCESS
));
1561 /* Now do it again */
1562 NtTerminateProcess(NtCurrentProcess(), uExitCode
);
1566 /* Release the PEB lock */
1567 RtlReleasePebLock();
1571 /* should never get here */
1581 TerminateProcess(IN HANDLE hProcess
,
1586 /* Check if no handle was passed in */
1589 /* Set error code */
1590 SetLastError(ERROR_INVALID_HANDLE
);
1594 /* Otherwise, try to terminate the process */
1595 Status
= NtTerminateProcess(hProcess
, uExitCode
);
1596 if (NT_SUCCESS(Status
)) return TRUE
;
1598 /* It failed, convert error code */
1599 BaseSetLastNTError(Status
);
1602 /* This is the failure path */
1611 FatalAppExitA(UINT uAction
,
1612 LPCSTR lpMessageText
)
1614 PUNICODE_STRING MessageTextU
;
1615 ANSI_STRING MessageText
;
1618 /* Initialize the string using the static TEB pointer */
1619 MessageTextU
= &NtCurrentTeb()->StaticUnicodeString
;
1620 RtlInitAnsiString(&MessageText
, (LPSTR
)lpMessageText
);
1622 /* Convert to unicode and just exit normally if this failed */
1623 Status
= RtlAnsiStringToUnicodeString(MessageTextU
, &MessageText
, FALSE
);
1624 if (!NT_SUCCESS(Status
)) ExitProcess(0);
1626 /* Call the Wide function */
1627 FatalAppExitW(uAction
, MessageTextU
->Buffer
);
1635 FatalAppExitW(IN UINT uAction
,
1636 IN LPCWSTR lpMessageText
)
1638 UNICODE_STRING UnicodeString
;
1642 /* Setup the string to print out */
1643 RtlInitUnicodeString(&UnicodeString
, lpMessageText
);
1645 /* Display the hard error no matter what */
1646 Status
= NtRaiseHardError(STATUS_FATAL_APP_EXIT
| HARDERROR_OVERRIDE_ERRORMODE
,
1649 (PULONG_PTR
)&UnicodeString
,
1653 /* Give the user a chance to abort */
1654 if ((NT_SUCCESS(Status
)) && (Response
== ResponseCancel
)) return;
1656 /* Otherwise kill the process */
1665 FatalExit(IN
int ExitCode
)
1668 /* On Checked builds, Windows gives you a nice little debugger UI */
1670 DbgPrint("FatalExit...\n");
1675 DbgPrompt( "A (Abort), B (Break), I (Ignore)? ", ch
, sizeof(ch
));
1683 ExitProcess(ExitCode
);
1690 /* On other builds, just kill the process */
1691 ExitProcess(ExitCode
);
1699 GetPriorityClass(IN HANDLE hProcess
)
1702 PROCESS_PRIORITY_CLASS PriorityClass
;
1704 /* Query the kernel */
1705 Status
= NtQueryInformationProcess(hProcess
,
1706 ProcessPriorityClass
,
1708 sizeof(PROCESS_PRIORITY_CLASS
),
1710 if (NT_SUCCESS(Status
))
1712 /* Handle the conversion from NT to Win32 classes */
1713 switch (PriorityClass
.PriorityClass
)
1715 case PROCESS_PRIORITY_CLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
1716 case PROCESS_PRIORITY_CLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
1717 case PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
1718 case PROCESS_PRIORITY_CLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
1719 case PROCESS_PRIORITY_CLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
1720 case PROCESS_PRIORITY_CLASS_NORMAL
: default: return NORMAL_PRIORITY_CLASS
;
1725 BaseSetLastNTError(Status
);
1734 SetPriorityClass(IN HANDLE hProcess
,
1735 IN DWORD dwPriorityClass
)
1739 PROCESS_PRIORITY_CLASS PriorityClass
;
1741 /* Handle conversion from Win32 to NT priority classes */
1742 switch (dwPriorityClass
)
1744 case IDLE_PRIORITY_CLASS
:
1745 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_IDLE
;
1748 case BELOW_NORMAL_PRIORITY_CLASS
:
1749 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
1752 case NORMAL_PRIORITY_CLASS
:
1753 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
1756 case ABOVE_NORMAL_PRIORITY_CLASS
:
1757 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
1760 case HIGH_PRIORITY_CLASS
:
1761 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1764 case REALTIME_PRIORITY_CLASS
:
1765 /* Try to acquire the privilege. If it fails, just use HIGH */
1766 State
= BasepIsRealtimeAllowed(TRUE
);
1767 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1768 PriorityClass
.PriorityClass
+= (State
!= NULL
);
1772 /* Unrecognized priority classes don't make it to the kernel */
1773 SetLastError(ERROR_INVALID_PARAMETER
);
1777 /* Send the request to the kernel, and don't touch the foreground flag */
1778 PriorityClass
.Foreground
= FALSE
;
1779 Status
= NtSetInformationProcess(hProcess
,
1780 ProcessPriorityClass
,
1782 sizeof(PROCESS_PRIORITY_CLASS
));
1784 /* Release the privilege if we had it */
1785 if (State
) RtlReleasePrivilege(State
);
1786 if (!NT_SUCCESS(Status
))
1788 /* Handle error path */
1789 BaseSetLastNTError(Status
);
1802 GetProcessVersion(IN DWORD ProcessId
)
1805 PIMAGE_NT_HEADERS NtHeader
;
1806 PIMAGE_DOS_HEADER DosHeader
;
1808 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
1811 HANDLE ProcessHandle
= NULL
;
1813 USHORT VersionData
[2];
1816 /* We'll be accessing stuff that can fault, so protect everything with SEH */
1819 /* It this an in-process or out-of-process request? */
1820 if (!(ProcessId
) || (GetCurrentProcessId() == ProcessId
))
1822 /* It's in-process, so just read our own header */
1823 NtHeader
= RtlImageNtHeader(NtCurrentPeb()->ImageBaseAddress
);
1826 /* Unable to read the NT header, something is wrong here... */
1827 Status
= STATUS_INVALID_IMAGE_FORMAT
;
1831 /* Get the version straight out of the NT header */
1832 Version
= MAKELONG(NtHeader
->OptionalHeader
.MinorSubsystemVersion
,
1833 NtHeader
->OptionalHeader
.MajorSubsystemVersion
);
1837 /* Out-of-process, so open it */
1838 ProcessHandle
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
,
1841 if (!ProcessHandle
) _SEH2_YIELD(return 0);
1843 /* Try to find out where its PEB lives */
1844 Status
= NtQueryInformationProcess(ProcessHandle
,
1845 ProcessBasicInformation
,
1847 sizeof(ProcessBasicInfo
),
1850 if (!NT_SUCCESS(Status
)) goto Error
;
1851 Peb
= ProcessBasicInfo
.PebBaseAddress
;
1853 /* Now that we have the PEB, read the image base address out of it */
1854 Result
= ReadProcessMemory(ProcessHandle
,
1855 &Peb
->ImageBaseAddress
,
1857 sizeof(BaseAddress
),
1859 if (!Result
) goto Error
;
1861 /* Now read the e_lfanew (offset to NT header) from the base */
1862 DosHeader
= BaseAddress
;
1863 Result
= ReadProcessMemory(ProcessHandle
,
1864 &DosHeader
->e_lfanew
,
1868 if (!Result
) goto Error
;
1870 /* And finally, read the NT header itself by adding the offset */
1871 NtHeader
= (PVOID
)((ULONG_PTR
)BaseAddress
+ e_lfanew
);
1872 Result
= ReadProcessMemory(ProcessHandle
,
1873 &NtHeader
->OptionalHeader
.MajorSubsystemVersion
,
1875 sizeof(VersionData
),
1877 if (!Result
) goto Error
;
1879 /* Get the version straight out of the NT header */
1880 Version
= MAKELONG(VersionData
[0], VersionData
[1]);
1883 /* If there was an error anywhere, set the last error */
1884 if (!NT_SUCCESS(Status
)) BaseSetLastNTError(Status
);
1889 /* Close the process handle */
1890 if (ProcessHandle
) CloseHandle(ProcessHandle
);
1894 /* And return the version data */
1903 GetProcessIoCounters(IN HANDLE hProcess
,
1904 OUT PIO_COUNTERS lpIoCounters
)
1908 /* Query the kernel. Structures are identical, so let it do the copy too. */
1909 Status
= NtQueryInformationProcess(hProcess
,
1912 sizeof(IO_COUNTERS
),
1914 if (!NT_SUCCESS(Status
))
1916 /* Handle error path */
1917 BaseSetLastNTError(Status
);
1930 GetProcessPriorityBoost(IN HANDLE hProcess
,
1931 OUT PBOOL pDisablePriorityBoost
)
1934 ULONG PriorityBoost
;
1936 /* Query the kernel */
1937 Status
= NtQueryInformationProcess(hProcess
,
1938 ProcessPriorityBoost
,
1942 if (NT_SUCCESS(Status
))
1944 /* Convert from ULONG to a BOOL */
1945 *pDisablePriorityBoost
= PriorityBoost
? TRUE
: FALSE
;
1949 /* Handle error path */
1950 BaseSetLastNTError(Status
);
1959 SetProcessPriorityBoost(IN HANDLE hProcess
,
1960 IN BOOL bDisablePriorityBoost
)
1963 ULONG PriorityBoost
;
1965 /* Enforce that this is a BOOL, and send it to the kernel as a ULONG */
1966 PriorityBoost
= (bDisablePriorityBoost
? TRUE
: FALSE
);
1967 Status
= NtSetInformationProcess(hProcess
,
1968 ProcessPriorityBoost
,
1971 if (!NT_SUCCESS(Status
))
1973 /* Handle error path */
1974 BaseSetLastNTError(Status
);
1987 GetProcessHandleCount(IN HANDLE hProcess
,
1988 OUT PDWORD pdwHandleCount
)
1993 /* Query the kernel */
1994 Status
= NtQueryInformationProcess(hProcess
,
1999 if (NT_SUCCESS(Status
))
2001 /* Copy the count and return sucecss */
2002 *pdwHandleCount
= phc
;
2006 /* Handle error path */
2007 BaseSetLastNTError(Status
);
2016 IsWow64Process(IN HANDLE hProcess
,
2017 OUT PBOOL Wow64Process
)
2022 /* Query the kernel */
2023 Status
= NtQueryInformationProcess(hProcess
,
2024 ProcessWow64Information
,
2028 if (!NT_SUCCESS(Status
))
2030 /* Handle error path */
2031 BaseSetLastNTError(Status
);
2035 /* Enforce this is a BOOL, and return success */
2036 *Wow64Process
= (pbi
!= 0);
2045 GetCommandLineA(VOID
)
2047 return BaseAnsiCommandLine
.Buffer
;
2055 GetCommandLineW(VOID
)
2057 return BaseUnicodeCommandLine
.Buffer
;
2065 ReadProcessMemory(IN HANDLE hProcess
,
2066 IN LPCVOID lpBaseAddress
,
2069 OUT SIZE_T
* lpNumberOfBytesRead
)
2074 Status
= NtReadVirtualMemory(hProcess
,
2075 (PVOID
)lpBaseAddress
,
2080 /* In user-mode, this parameter is optional */
2081 if (lpNumberOfBytesRead
) *lpNumberOfBytesRead
= nSize
;
2082 if (!NT_SUCCESS(Status
))
2085 BaseSetLastNTError(Status
);
2089 /* Return success */
2098 WriteProcessMemory(IN HANDLE hProcess
,
2099 IN LPVOID lpBaseAddress
,
2100 IN LPCVOID lpBuffer
,
2102 OUT SIZE_T
*lpNumberOfBytesWritten
)
2110 /* Set parameters for protect call */
2112 Base
= lpBaseAddress
;
2114 /* Check the current status */
2115 Status
= NtProtectVirtualMemory(hProcess
,
2118 PAGE_EXECUTE_READWRITE
,
2120 if (NT_SUCCESS(Status
))
2122 /* Check if we are unprotecting */
2123 UnProtect
= OldValue
& (PAGE_READWRITE
|
2125 PAGE_EXECUTE_READWRITE
|
2126 PAGE_EXECUTE_WRITECOPY
) ? FALSE
: TRUE
;
2129 /* Set the new protection */
2130 Status
= NtProtectVirtualMemory(hProcess
,
2136 /* Write the memory */
2137 Status
= NtWriteVirtualMemory(hProcess
,
2143 /* In Win32, the parameter is optional, so handle this case */
2144 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2146 if (!NT_SUCCESS(Status
))
2149 BaseSetLastNTError(Status
);
2153 /* Flush the ITLB */
2154 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2159 /* Check if we were read only */
2160 if (OldValue
& (PAGE_NOACCESS
| PAGE_READONLY
))
2162 /* Restore protection and fail */
2163 NtProtectVirtualMemory(hProcess
,
2168 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2170 /* Note: This is what Windows returns and code depends on it */
2171 return STATUS_ACCESS_VIOLATION
;
2174 /* Otherwise, do the write */
2175 Status
= NtWriteVirtualMemory(hProcess
,
2181 /* In Win32, the parameter is optional, so handle this case */
2182 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2184 /* And restore the protection */
2185 NtProtectVirtualMemory(hProcess
,
2190 if (!NT_SUCCESS(Status
))
2193 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2195 /* Note: This is what Windows returns and code depends on it */
2196 return STATUS_ACCESS_VIOLATION
;
2199 /* Flush the ITLB */
2200 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2207 BaseSetLastNTError(Status
);
2217 ProcessIdToSessionId(IN DWORD dwProcessId
,
2218 OUT PDWORD pSessionId
)
2220 PROCESS_SESSION_INFORMATION SessionInformation
;
2221 OBJECT_ATTRIBUTES ObjectAttributes
;
2223 HANDLE ProcessHandle
;
2226 /* Do a quick check if the pointer is not writable */
2227 if (IsBadWritePtr(pSessionId
, sizeof(DWORD
)))
2230 SetLastError(ERROR_INVALID_PARAMETER
);
2234 /* Open the process passed in by ID */
2235 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
2236 ClientId
.UniqueThread
= 0;
2237 InitializeObjectAttributes(&ObjectAttributes
, NULL
, 0, NULL
, NULL
);
2238 Status
= NtOpenProcess(&ProcessHandle
,
2239 PROCESS_QUERY_INFORMATION
,
2242 if (NT_SUCCESS(Status
))
2244 /* Query the session ID from the kernel */
2245 Status
= NtQueryInformationProcess(ProcessHandle
,
2246 ProcessSessionInformation
,
2247 &SessionInformation
,
2248 sizeof(SessionInformation
),
2251 /* Close the handle and check if we suceeded */
2252 NtClose(ProcessHandle
);
2253 if (NT_SUCCESS(Status
))
2255 /* Return the session ID */
2256 *pSessionId
= SessionInformation
.SessionId
;
2261 /* Set error code and fail */
2262 BaseSetLastNTError(Status
);
2267 #define AddToHandle(x,y) (x) = (HANDLE)((ULONG_PTR)(x) | (y));
2268 #define RemoveFromHandle(x,y) (x) = (HANDLE)((ULONG_PTR)(x) & ~(y));
2269 C_ASSERT(PROCESS_PRIORITY_CLASS_REALTIME
== (PROCESS_PRIORITY_CLASS_HIGH
+ 1));
2276 CreateProcessInternalW(IN HANDLE hUserToken
,
2277 IN LPCWSTR lpApplicationName
,
2278 IN LPWSTR lpCommandLine
,
2279 IN LPSECURITY_ATTRIBUTES lpProcessAttributes
,
2280 IN LPSECURITY_ATTRIBUTES lpThreadAttributes
,
2281 IN BOOL bInheritHandles
,
2282 IN DWORD dwCreationFlags
,
2283 IN LPVOID lpEnvironment
,
2284 IN LPCWSTR lpCurrentDirectory
,
2285 IN LPSTARTUPINFOW lpStartupInfo
,
2286 IN LPPROCESS_INFORMATION lpProcessInformation
,
2287 OUT PHANDLE hNewToken
)
2290 // Core variables used for creating the initial process and thread
2292 SECURITY_ATTRIBUTES LocalThreadAttributes
, LocalProcessAttributes
;
2293 OBJECT_ATTRIBUTES LocalObjectAttributes
;
2294 POBJECT_ATTRIBUTES ObjectAttributes
;
2295 SECTION_IMAGE_INFORMATION ImageInformation
;
2296 IO_STATUS_BLOCK IoStatusBlock
;
2298 ULONG NoWindow
, RegionSize
, StackSize
, ErrorCode
, Flags
;
2299 USHORT ImageMachine
;
2300 ULONG ParameterFlags
, PrivilegeValue
, HardErrorMode
, ErrorResponse
;
2301 ULONG_PTR ErrorParameters
[2];
2302 BOOLEAN InJob
, SaferNeeded
, UseLargePages
, HavePrivilege
;
2303 BOOLEAN QuerySection
, SkipSaferAndAppCompat
;
2305 BASE_API_MESSAGE CsrMsg
;
2306 PBASE_CREATE_PROCESS CreateProcessMsg
;
2307 PCSR_CAPTURE_BUFFER CaptureBuffer
;
2308 PVOID BaseAddress
, PrivilegeState
, RealTimePrivilegeState
;
2309 HANDLE DebugHandle
, TokenHandle
, JobHandle
, KeyHandle
, ThreadHandle
;
2310 HANDLE FileHandle
, SectionHandle
, ProcessHandle
;
2312 PROCESS_PRIORITY_CLASS PriorityClass
;
2313 NTSTATUS Status
, Status1
, ImageDbgStatus
;
2314 PPEB Peb
, RemotePeb
;
2316 INITIAL_TEB InitialTeb
;
2318 PIMAGE_NT_HEADERS NtHeaders
;
2319 STARTUPINFOW StartupInfo
;
2320 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
;
2321 UNICODE_STRING DebuggerString
;
2324 // Variables used for command-line and argument parsing
2329 ULONG Length
, CurdirLength
, CmdQuoteLength
;
2330 ULONG CmdLineLength
, ResultSize
;
2331 PWCHAR QuotedCmdLine
, AnsiCmdCommand
, ExtBuffer
, CurrentDirectory
;
2332 PWCHAR NullBuffer
, ScanString
, NameBuffer
, SearchPath
, DebuggerCmdLine
;
2333 ANSI_STRING AnsiEnv
;
2334 UNICODE_STRING UnicodeEnv
, PathName
;
2335 BOOLEAN SearchRetry
, QuotesNeeded
, CmdLineIsAppName
, HasQuotes
;
2338 // Variables used for Fusion/SxS (Side-by-Side Assemblies)
2340 RTL_PATH_TYPE SxsPathType
, PathType
;
2341 #if _SXS_SUPPORT_ENABLED_
2342 PRTL_BUFFER ByteBuffer
;
2343 PRTL_UNICODE_STRING_BUFFER ThisBuffer
, Buffer
, SxsStaticBuffers
[5];
2344 PRTL_UNICODE_STRING_BUFFER
* BufferHead
, SxsStringBuffer
;
2345 RTL_UNICODE_STRING_BUFFER SxsWin32ManifestPath
, SxsNtManifestPath
;
2346 RTL_UNICODE_STRING_BUFFER SxsWin32PolicyPath
, SxsNtPolicyPath
;
2347 RTL_UNICODE_STRING_BUFFER SxsWin32AssemblyDirectory
;
2348 BASE_MSG_SXS_HANDLES MappedHandles
, Handles
, FileHandles
;
2349 PVOID CapturedStrings
[3];
2350 SXS_WIN32_NT_PATH_PAIR ExePathPair
, ManifestPathPair
, PolicyPathPair
;
2351 SXS_OVERRIDE_MANIFEST OverrideMannifest
;
2352 UNICODE_STRING FreeString
, SxsNtExePath
;
2353 PWCHAR SxsConglomeratedBuffer
, StaticBuffer
;
2354 ULONG ConglomeratedBufferSizeBytes
, StaticBufferSize
, i
;
2359 // Variables used for path conversion (and partially Fusion/SxS)
2361 PWCHAR FilePart
, PathBuffer
, FreeBuffer
;
2362 BOOLEAN TranslationStatus
;
2363 RTL_RELATIVE_NAME_U SxsWin32RelativePath
;
2364 UNICODE_STRING PathBufferString
, SxsWin32ExePath
;
2367 // Variables used by Application Compatibility (and partially Fusion/SxS)
2369 PVOID AppCompatSxsData
, AppCompatData
;
2370 ULONG AppCompatSxsDataSize
, AppCompatDataSize
;
2372 // Variables used by VDM (Virtual Dos Machine) and WOW32 (16-bit Support)
2374 ULONG BinarySubType
, VdmBinaryType
, VdmTask
, VdmReserve
;
2376 BOOLEAN UseVdmReserve
;
2377 HANDLE VdmWaitObject
;
2378 ANSI_STRING VdmAnsiEnv
;
2379 UNICODE_STRING VdmString
, VdmUnicodeEnv
;
2381 PBASE_CHECK_VDM VdmMsg
;
2383 /* Zero out the initial core variables and handles */
2384 QuerySection
= FALSE
;
2386 SkipSaferAndAppCompat
= TRUE
; // HACK for making .bat/.cmd launch working again.
2393 SectionHandle
= NULL
;
2394 ProcessHandle
= NULL
;
2395 ThreadHandle
= NULL
;
2396 BaseAddress
= (PVOID
)1;
2398 /* Zero out initial SxS and Application Compatibility state */
2399 AppCompatData
= NULL
;
2400 AppCompatDataSize
= 0;
2401 AppCompatSxsData
= NULL
;
2402 AppCompatSxsDataSize
= 0;
2403 CaptureBuffer
= NULL
;
2404 #if _SXS_SUPPORT_ENABLED_
2405 SxsConglomeratedBuffer
= NULL
;
2409 /* Zero out initial parsing variables -- others are initialized later */
2410 DebuggerCmdLine
= NULL
;
2416 CurrentDirectory
= NULL
;
2418 DebuggerString
.Buffer
= NULL
;
2420 QuotedCmdLine
= NULL
;
2422 /* Zero out initial VDM state */
2423 VdmAnsiEnv
.Buffer
= NULL
;
2424 VdmUnicodeEnv
.Buffer
= NULL
;
2425 VdmString
.Buffer
= NULL
;
2430 VdmWaitObject
= NULL
;
2431 UseVdmReserve
= FALSE
;
2434 /* Set message structures */
2435 CreateProcessMsg
= &CsrMsg
.Data
.CreateProcessRequest
;
2436 VdmMsg
= &CsrMsg
.Data
.CheckVDMRequest
;
2438 /* Clear the more complex structures by zeroing out their entire memory */
2439 RtlZeroMemory(&Context
, sizeof(Context
));
2440 #if _SXS_SUPPORT_ENABLED_
2441 RtlZeroMemory(&FileHandles
, sizeof(FileHandles
));
2442 RtlZeroMemory(&MappedHandles
, sizeof(MappedHandles
));
2443 RtlZeroMemory(&Handles
, sizeof(Handles
));
2445 RtlZeroMemory(&CreateProcessMsg
->Sxs
, sizeof(CreateProcessMsg
->Sxs
));
2446 RtlZeroMemory(&LocalProcessAttributes
, sizeof(LocalProcessAttributes
));
2447 RtlZeroMemory(&LocalThreadAttributes
, sizeof(LocalThreadAttributes
));
2449 /* Zero out output arguments as well */
2450 RtlZeroMemory(lpProcessInformation
, sizeof(*lpProcessInformation
));
2451 if (hNewToken
) *hNewToken
= NULL
;
2453 /* Capture the special window flag */
2454 NoWindow
= dwCreationFlags
& CREATE_NO_WINDOW
;
2455 dwCreationFlags
&= ~CREATE_NO_WINDOW
;
2457 #if _SXS_SUPPORT_ENABLED_
2458 /* Setup the SxS static string arrays and buffers */
2459 SxsStaticBuffers
[0] = &SxsWin32ManifestPath
;
2460 SxsStaticBuffers
[1] = &SxsWin32PolicyPath
;
2461 SxsStaticBuffers
[2] = &SxsWin32AssemblyDirectory
;
2462 SxsStaticBuffers
[3] = &SxsNtManifestPath
;
2463 SxsStaticBuffers
[4] = &SxsNtPolicyPath
;
2464 ExePathPair
.Win32
= &SxsWin32ExePath
;
2465 ExePathPair
.Nt
= &SxsNtExePath
;
2466 ManifestPathPair
.Win32
= &SxsWin32ManifestPath
.String
;
2467 ManifestPathPair
.Nt
= &SxsNtManifestPath
.String
;
2468 PolicyPathPair
.Win32
= &SxsWin32PolicyPath
.String
;
2469 PolicyPathPair
.Nt
= &SxsNtPolicyPath
.String
;
2472 DPRINT("CreateProcessInternalW: %S %S %lx\n", lpApplicationName
, lpCommandLine
, dwCreationFlags
);
2474 /* Finally, set our TEB and PEB */
2475 Teb
= NtCurrentTeb();
2476 Peb
= NtCurrentPeb();
2478 /* This combination is illegal (see MSDN) */
2479 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
2480 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
2482 DPRINT1("Invalid flag combo used\n");
2483 SetLastError(ERROR_INVALID_PARAMETER
);
2487 /* Convert the priority class */
2488 if (dwCreationFlags
& IDLE_PRIORITY_CLASS
)
2490 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_IDLE
;
2492 else if (dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
2494 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
2496 else if (dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
2498 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
2500 else if (dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
2502 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
2504 else if (dwCreationFlags
& HIGH_PRIORITY_CLASS
)
2506 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
2508 else if (dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
2510 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
2511 PriorityClass
.PriorityClass
+= (BasepIsRealtimeAllowed(FALSE
) != NULL
);
2515 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_INVALID
;
2518 /* Done with the priority masks, so get rid of them */
2519 PriorityClass
.Foreground
= FALSE
;
2520 dwCreationFlags
&= ~(NORMAL_PRIORITY_CLASS
|
2521 IDLE_PRIORITY_CLASS
|
2522 HIGH_PRIORITY_CLASS
|
2523 REALTIME_PRIORITY_CLASS
|
2524 BELOW_NORMAL_PRIORITY_CLASS
|
2525 ABOVE_NORMAL_PRIORITY_CLASS
);
2527 /* You cannot request both a shared and a separate WoW VDM */
2528 if ((dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
) &&
2529 (dwCreationFlags
& CREATE_SHARED_WOW_VDM
))
2531 /* Fail such nonsensical attempts */
2532 DPRINT1("Invalid WOW flags\n");
2533 SetLastError(ERROR_INVALID_PARAMETER
);
2536 else if (!(dwCreationFlags
& CREATE_SHARED_WOW_VDM
) &&
2537 (BaseStaticServerData
->DefaultSeparateVDM
))
2539 /* A shared WoW VDM was not requested but system enforces separation */
2540 dwCreationFlags
|= CREATE_SEPARATE_WOW_VDM
;
2543 /* If a shared WoW VDM is used, make sure the process isn't in a job */
2544 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
) &&
2545 (NtIsProcessInJob(NtCurrentProcess(), NULL
)))
2547 /* Remove the shared flag and add the separate flag */
2548 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
2549 CREATE_SEPARATE_WOW_VDM
;
2552 /* Convert the environment */
2553 if ((lpEnvironment
) && !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
2555 /* Scan the environment to calculate its Unicode size */
2556 AnsiEnv
.Buffer
= pcScan
= (PCHAR
)lpEnvironment
;
2557 while ((*pcScan
) || (*(pcScan
+ 1))) ++pcScan
;
2559 /* Create our ANSI String */
2560 AnsiEnv
.Length
= pcScan
- (PCHAR
)lpEnvironment
+ sizeof(ANSI_NULL
);
2561 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ sizeof(ANSI_NULL
);
2563 /* Allocate memory for the Unicode Environment */
2564 UnicodeEnv
.Buffer
= NULL
;
2565 RegionSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
2566 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
2567 (PVOID
)&UnicodeEnv
.Buffer
,
2572 if (!NT_SUCCESS(Status
))
2575 BaseSetLastNTError(Status
);
2579 /* Use the allocated size and convert */
2580 UnicodeEnv
.MaximumLength
= (USHORT
)RegionSize
;
2581 Status
= RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
2582 if (!NT_SUCCESS(Status
))
2585 NtFreeVirtualMemory(NtCurrentProcess(),
2586 (PVOID
)&UnicodeEnv
.Buffer
,
2589 BaseSetLastNTError(Status
);
2593 /* Now set the Unicode environment as the environment string pointer */
2594 lpEnvironment
= UnicodeEnv
.Buffer
;
2597 /* Make a copy of the caller's startup info since we'll modify it */
2598 StartupInfo
= *lpStartupInfo
;
2600 /* Check if private data is being sent on the same channel as std handles */
2601 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
2602 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
2604 /* Cannot use the std handles since we have monitor/hotkey values */
2605 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
2608 /* If there's a debugger, or we have to launch cmd.exe, we go back here */
2610 /* New iteration -- free any existing name buffer */
2613 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2617 /* New iteration -- free any existing free buffer */
2620 RtlFreeHeap(RtlGetProcessHeap(), 0, FreeBuffer
);
2624 /* New iteration -- close any existing file handle */
2627 NtClose(FileHandle
);
2631 /* Set the initial parsing state. This code can loop -- don't move this! */
2634 QuotesNeeded
= FALSE
;
2635 CmdLineIsAppName
= FALSE
;
2637 /* First check if we don't have an application name */
2638 if (!lpApplicationName
)
2640 /* This should be the first time we attempt creating one */
2641 ASSERT(NameBuffer
== NULL
);
2643 /* Allocate a buffer to hold it */
2644 NameBuffer
= RtlAllocateHeap(RtlGetProcessHeap(),
2646 MAX_PATH
* sizeof(WCHAR
));
2649 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2654 /* Initialize the application name and our parsing parameters */
2655 lpApplicationName
= NullBuffer
= ScanString
= lpCommandLine
;
2657 /* Check for an initial quote*/
2658 if (*lpCommandLine
== L
'\"')
2660 /* We found a quote, keep searching for another one */
2661 SearchRetry
= FALSE
;
2663 lpApplicationName
= ScanString
;
2666 /* Have we found the terminating quote? */
2667 if (*ScanString
== L
'\"')
2669 /* We're done, get out of here */
2670 NullBuffer
= ScanString
;
2675 /* Keep searching for the quote */
2677 NullBuffer
= ScanString
;
2683 /* We simply make the application name be the command line*/
2684 lpApplicationName
= lpCommandLine
;
2687 /* Check if it starts with a space or tab */
2688 if ((*ScanString
== L
' ') || (*ScanString
== L
'\t'))
2690 /* Break out of the search loop */
2691 NullBuffer
= ScanString
;
2695 /* Keep searching for a space or tab */
2697 NullBuffer
= ScanString
;
2701 /* We have found the end of the application name, terminate it */
2702 SaveChar
= *NullBuffer
;
2703 *NullBuffer
= UNICODE_NULL
;
2705 /* New iteration -- free any existing saved path */
2708 RtlFreeHeap(RtlGetProcessHeap(), 0, SearchPath
);
2712 /* Now compute the final EXE path based on the name */
2713 SearchPath
= BaseComputeProcessExePath((LPWSTR
)lpApplicationName
);
2714 DPRINT("Search Path: %S\n", SearchPath
);
2717 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2722 /* And search for the executable in the search path */
2723 Length
= SearchPathW(SearchPath
,
2730 /* Did we find it? */
2731 if ((Length
) && (Length
< MAX_PATH
))
2733 /* Get file attributes */
2734 CurdirLength
= GetFileAttributesW(NameBuffer
);
2735 if ((CurdirLength
!= 0xFFFFFFFF) &&
2736 (CurdirLength
& FILE_ATTRIBUTE_DIRECTORY
))
2738 /* This was a directory, fail later on */
2748 DPRINT("Length: %lu Buffer: %S\n", Length
, NameBuffer
);
2750 /* Check if there was a failure in SearchPathW */
2751 if ((Length
) && (Length
< MAX_PATH
))
2753 /* Everything looks good, restore the name */
2754 *NullBuffer
= SaveChar
;
2755 lpApplicationName
= NameBuffer
;
2759 /* Check if this was a relative path, which would explain it */
2760 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
2761 if (PathType
!= RtlPathTypeRelative
)
2763 /* This should fail, and give us a detailed LastError */
2764 FileHandle
= CreateFileW(lpApplicationName
,
2770 FILE_ATTRIBUTE_NORMAL
,
2772 if (FileHandle
!= INVALID_HANDLE_VALUE
)
2774 /* It worked? Return a generic error */
2775 CloseHandle(FileHandle
);
2777 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2782 /* Path was absolute, which means it doesn't exist */
2783 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2786 /* Did we already fail once? */
2789 /* Set the error code */
2790 SetLastError(ErrorCode
);
2794 /* Not yet, cache it */
2795 ErrorCode
= GetLastError();
2798 /* Put back the command line */
2799 *NullBuffer
= SaveChar
;
2800 lpApplicationName
= NameBuffer
;
2802 /* It's possible there's whitespace in the directory name */
2803 if (!(*ScanString
) || !(SearchRetry
))
2805 /* Not the case, give up completely */
2810 /* There are spaces, so keep trying the next possibility */
2812 NullBuffer
= ScanString
;
2814 /* We will have to add a quote, since there is a space */
2815 QuotesNeeded
= TRUE
;
2820 else if (!(lpCommandLine
) || !(*lpCommandLine
))
2822 /* We don't have a command line, so just use the application name */
2823 CmdLineIsAppName
= TRUE
;
2824 lpCommandLine
= (LPWSTR
)lpApplicationName
;
2827 /* Convert the application name to its NT path */
2828 TranslationStatus
= RtlDosPathNameToRelativeNtPathName_U(lpApplicationName
,
2831 &SxsWin32RelativePath
);
2832 if (!TranslationStatus
)
2834 /* Path must be invaild somehow, bail out */
2835 DPRINT1("Path translation for SxS failed\n");
2836 SetLastError(ERROR_PATH_NOT_FOUND
);
2841 /* Setup the buffer that needs to be freed at the end */
2842 ASSERT(FreeBuffer
== NULL
);
2843 FreeBuffer
= PathName
.Buffer
;
2845 /* Check what kind of path the application is, for SxS (Fusion) purposes */
2846 RtlInitUnicodeString(&SxsWin32ExePath
, lpApplicationName
);
2847 SxsPathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
2848 if ((SxsPathType
!= RtlPathTypeDriveAbsolute
) &&
2849 (SxsPathType
!= RtlPathTypeLocalDevice
) &&
2850 (SxsPathType
!= RtlPathTypeRootLocalDevice
) &&
2851 (SxsPathType
!= RtlPathTypeUncAbsolute
))
2853 /* Relative-type path, get the full path */
2854 RtlInitEmptyUnicodeString(&PathBufferString
, NULL
, 0);
2855 Status
= RtlGetFullPathName_UstrEx(&SxsWin32ExePath
,
2863 if (!NT_SUCCESS(Status
))
2865 /* Fail the rest of the create */
2866 RtlReleaseRelativeName(&SxsWin32RelativePath
);
2867 BaseSetLastNTError(Status
);
2872 /* Use this full path as the SxS path */
2873 SxsWin32ExePath
= PathBufferString
;
2874 PathBuffer
= PathBufferString
.Buffer
;
2875 PathBufferString
.Buffer
= NULL
;
2876 DPRINT("SxS Path: %S\n", PathBuffer
);
2879 /* Also set the .EXE path based on the path name */
2880 #if _SXS_SUPPORT_ENABLED_
2881 SxsNtExePath
= PathName
;
2883 if (SxsWin32RelativePath
.RelativeName
.Length
)
2885 /* If it's relative, capture the relative name */
2886 PathName
= SxsWin32RelativePath
.RelativeName
;
2890 /* Otherwise, it's absolute, make sure no relative dir is used */
2891 SxsWin32RelativePath
.ContainingDirectory
= NULL
;
2894 /* Now use the path name, and the root path, to try opening the app */
2895 DPRINT("Path: %wZ. Dir: %p\n", &PathName
, SxsWin32RelativePath
.ContainingDirectory
);
2896 InitializeObjectAttributes(&LocalObjectAttributes
,
2898 OBJ_CASE_INSENSITIVE
,
2899 SxsWin32RelativePath
.ContainingDirectory
,
2901 Status
= NtOpenFile(&FileHandle
,
2903 FILE_READ_ATTRIBUTES
|
2906 &LocalObjectAttributes
,
2908 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2909 FILE_SYNCHRONOUS_IO_NONALERT
|
2910 FILE_NON_DIRECTORY_FILE
);
2911 if (!NT_SUCCESS(Status
))
2913 /* Try to open the app just for execute purposes instead */
2914 Status
= NtOpenFile(&FileHandle
,
2915 SYNCHRONIZE
| FILE_EXECUTE
,
2916 &LocalObjectAttributes
,
2918 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2919 FILE_SYNCHRONOUS_IO_NONALERT
|
2920 FILE_NON_DIRECTORY_FILE
);
2923 /* Cleanup in preparation for failure or success */
2924 RtlReleaseRelativeName(&SxsWin32RelativePath
);
2925 if (!NT_SUCCESS(Status
))
2927 /* Failure path, try to understand why */
2928 DPRINT1("Open file failed: %lx\n", Status
);
2929 if (RtlIsDosDeviceName_U(lpApplicationName
))
2931 /* If a device is being executed, return this special error code */
2932 SetLastError(ERROR_BAD_DEVICE
);
2938 /* Otherwise return the converted NT error code */
2939 BaseSetLastNTError(Status
);
2945 /* Did the caller specify a desktop? */
2946 if (!StartupInfo
.lpDesktop
)
2948 /* Use the one from the current process */
2949 StartupInfo
.lpDesktop
= Peb
->ProcessParameters
->DesktopInfo
.Buffer
;
2952 /* Create a section for this file */
2953 Status
= NtCreateSection(&SectionHandle
,
2960 DPRINT("Section status: %lx\n", Status
);
2961 if (NT_SUCCESS(Status
))
2963 /* Are we running on Windows Embedded, Datacenter, Blade or Starter? */
2964 if (SharedUserData
->SuiteMask
& (VER_SUITE_EMBEDDEDNT
|
2965 VER_SUITE_DATACENTER
|
2966 VER_SUITE_PERSONAL
|
2969 /* These SKUs do not allow running certain applications */
2970 Status
= BasepCheckWebBladeHashes(FileHandle
);
2971 if (Status
== STATUS_ACCESS_DENIED
)
2973 /* And this is one of them! */
2974 DPRINT1("Invalid Blade hashes!\n");
2975 SetLastError(ERROR_ACCESS_DISABLED_WEBBLADE
);
2980 /* Did we get some other failure? */
2981 if (!NT_SUCCESS(Status
))
2983 /* If we couldn't check the hashes, assume nefariousness */
2984 DPRINT1("Tampered Blade hashes!\n");
2985 SetLastError(ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER
);
2991 /* Now do Winsafer, etc, checks */
2992 Status
= BasepIsProcessAllowed((LPWSTR
)lpApplicationName
);
2993 if (!NT_SUCCESS(Status
))
2995 /* Fail if we're not allowed to launch the process */
2996 DPRINT1("Process not allowed to launch: %lx\n", Status
);
2997 BaseSetLastNTError(Status
);
3000 NtClose(SectionHandle
);
3001 SectionHandle
= NULL
;
3007 /* Is a DOS VDM being forced, but we already have a WOW32 instance ready? */
3008 if ((dwCreationFlags
& CREATE_FORCEDOS
) &&
3009 (BaseStaticServerData
->IsWowTaskReady
))
3011 /* This request can't be satisfied, instead, a separate VDM is needed */
3012 dwCreationFlags
&= ~(CREATE_FORCEDOS
| CREATE_SHARED_WOW_VDM
);
3013 dwCreationFlags
|= CREATE_SEPARATE_WOW_VDM
;
3015 /* Set a failure code, ask for VDM reservation */
3016 Status
= STATUS_INVALID_IMAGE_WIN_16
;
3017 UseVdmReserve
= TRUE
;
3019 /* Close the current handle */
3020 NtClose(SectionHandle
);
3021 SectionHandle
= NULL
;
3023 /* Don't query the section later */
3024 QuerySection
= FALSE
;
3028 /* Did we already do these checks? */
3029 if (!SkipSaferAndAppCompat
)
3031 /* Is everything OK so far, OR do we have an non-MZ, non-DOS app? */
3032 if ((NT_SUCCESS(Status
)) ||
3033 ((Status
== STATUS_INVALID_IMAGE_NOT_MZ
) &&
3034 !(BaseIsDosApplication(&PathName
, Status
))))
3036 /* Clear the machine type in case of failure */
3039 /* Clean any app compat data that may have accumulated */
3040 BasepFreeAppCompatData(AppCompatData
, AppCompatSxsData
);
3041 AppCompatData
= NULL
;
3042 AppCompatSxsData
= NULL
;
3044 /* Do we have a section? */
3047 /* Have we already queried it? */
3051 Status
= STATUS_SUCCESS
;
3055 /* Get some information about the executable */
3056 Status
= NtQuerySection(SectionHandle
,
3057 SectionImageInformation
,
3059 sizeof(ImageInformation
),
3063 /* Do we have section information now? */
3064 if (NT_SUCCESS(Status
))
3066 /* Don't ask for it again, save the machine type */
3067 QuerySection
= TRUE
;
3068 ImageMachine
= ImageInformation
.Machine
;
3072 /* Is there a reason/Shim we shouldn't run this application? */
3073 Status
= BasepCheckBadapp(FileHandle
,
3080 &AppCompatSxsDataSize
,
3082 if (!NT_SUCCESS(Status
))
3084 /* This is usually the status we get back */
3085 DPRINT1("App compat launch failure: %lx\n", Status
);
3086 if (Status
== STATUS_ACCESS_DENIED
)
3088 /* Convert it to something more Win32-specific */
3089 SetLastError(ERROR_CANCELLED
);
3093 /* Some other error */
3094 BaseSetLastNTError(Status
);
3097 /* Did we have a section? */
3101 NtClose(SectionHandle
);
3102 SectionHandle
= NULL
;
3112 //ASSERT((dwFusionFlags & ~SXS_APPCOMPACT_FLAG_APP_RUNNING_SAFEMODE) == 0);
3114 /* Have we already done, and do we need to do, SRP (WinSafer) checks? */
3115 if (!(SkipSaferAndAppCompat
) &&
3116 ~(dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
))
3122 case STATUS_INVALID_IMAGE_NE_FORMAT
:
3123 case STATUS_INVALID_IMAGE_PROTECT
:
3124 case STATUS_INVALID_IMAGE_WIN_16
:
3125 case STATUS_FILE_IS_OFFLINE
:
3126 /* For all DOS, 16-bit, OS/2 images, we do*/
3129 case STATUS_INVALID_IMAGE_NOT_MZ
:
3130 /* For invalid files, we don't, unless it's a .BAT file */
3131 if (BaseIsDosApplication(&PathName
, Status
)) break;
3134 /* Any other error codes we also don't */
3135 if (!NT_SUCCESS(Status
))
3137 SaferNeeded
= FALSE
;
3140 /* But for success, we do */
3144 /* Okay, so what did the checks above result in? */
3147 /* We have to call into the WinSafer library and actually check */
3148 Status
= BasepCheckWinSaferRestrictions(hUserToken
,
3149 (LPWSTR
)lpApplicationName
,
3154 if (Status
== 0xFFFFFFFF)
3156 /* Back in 2003, they didn't have an NTSTATUS for this... */
3157 DPRINT1("WinSafer blocking process launch\n");
3158 SetLastError(ERROR_ACCESS_DISABLED_BY_POLICY
);
3163 /* Other status codes are not-Safer related, just convert them */
3164 if (!NT_SUCCESS(Status
))
3166 DPRINT1("Error checking WinSafer: %lx\n", Status
);
3167 BaseSetLastNTError(Status
);
3174 /* The last step is to figure out why the section object was not created */
3177 case STATUS_INVALID_IMAGE_WIN_16
:
3179 /* 16-bit binary. Should we use WOW or does the caller force VDM? */
3180 if (!(dwCreationFlags
& CREATE_FORCEDOS
))
3182 /* Remember that we're launching WOW */
3185 /* Create the VDM environment, it's valid for WOW too */
3186 Result
= BaseCreateVDMEnvironment(lpEnvironment
,
3191 DPRINT1("VDM environment for WOW app failed\n");
3195 /* We're going to try this twice, so do a loop */
3198 /* Pick which kind of WOW mode we want to run in */
3199 VdmBinaryType
= (dwCreationFlags
&
3200 CREATE_SEPARATE_WOW_VDM
) ?
3201 BINARY_TYPE_WOW
: BINARY_TYPE_SEPARATE_WOW
;
3203 /* Get all the VDM settings and current status */
3204 Status
= BaseCheckVDM(VdmBinaryType
,
3209 (PCSR_API_MESSAGE
)VdmMsg
,
3215 /* If it worked, no need to try again */
3216 if (NT_SUCCESS(Status
)) break;
3218 /* Check if it's disallowed or if it's our second time */
3219 BaseSetLastNTError(Status
);
3220 if ((Status
== STATUS_VDM_DISALLOWED
) ||
3221 (VdmBinaryType
== BINARY_TYPE_SEPARATE_WOW
) ||
3222 (GetLastError() == ERROR_ACCESS_DENIED
))
3224 /* Fail the call -- we won't try again */
3225 DPRINT1("VDM message failure for WOW: %lx\n", Status
);
3230 /* Try one more time, but with a separate WOW instance */
3231 dwCreationFlags
|= CREATE_SEPARATE_WOW_VDM
;
3234 /* Check which VDM state we're currently in */
3235 switch (VdmMsg
->VDMState
& (VDM_NOT_LOADED
|
3239 case VDM_NOT_LOADED
:
3240 /* VDM is not fully loaded, so not that much to undo */
3241 VdmUndoLevel
= VDM_UNDO_PARTIAL
;
3243 /* Reset VDM reserve if needed */
3244 if (UseVdmReserve
) VdmReserve
= 1;
3246 /* Get the required parameters and names for launch */
3247 Result
= BaseGetVdmConfigInfo(lpCommandLine
,
3254 DPRINT1("VDM Configuration failed for WOW\n");
3255 BaseSetLastNTError(Status
);
3259 /* Update the command-line with the VDM one instead */
3260 lpCommandLine
= VdmString
.Buffer
;
3261 lpApplicationName
= NULL
;
3263 /* We don't want a console, detachment, nor a window */
3264 dwCreationFlags
|= CREATE_NO_WINDOW
;
3265 dwCreationFlags
&= ~(CREATE_NEW_CONSOLE
| DETACHED_PROCESS
);
3267 /* Force feedback on */
3268 StartupInfo
.dwFlags
|= STARTF_FORCEONFEEDBACK
;
3273 /* VDM is ready, so we have to undo everything */
3274 VdmUndoLevel
= VDM_UNDO_REUSE
;
3276 /* Check if CSRSS wants us to wait on VDM */
3277 VdmWaitObject
= VdmMsg
->WaitObjectForParent
;
3281 /* Something is wrong with VDM, we'll fail the call */
3282 DPRINT1("VDM is not ready for WOW\n");
3283 SetLastError(ERROR_NOT_READY
);
3291 /* Since to get NULL, we allocate from 0x1, account for this */
3294 /* This implies VDM is ready, so skip everything else */
3295 if (VdmWaitObject
) goto VdmShortCircuit
;
3297 /* Don't inherit handles since we're doing VDM now */
3298 bInheritHandles
= FALSE
;
3300 /* Had the user passed in environment? If so, destroy it */
3301 if ((lpEnvironment
) &&
3302 !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3304 RtlDestroyEnvironment(lpEnvironment
);
3307 /* We've already done all these checks, don't do them again */
3308 SkipSaferAndAppCompat
= TRUE
;
3312 // There is no break here on purpose, so FORCEDOS drops down!
3315 case STATUS_INVALID_IMAGE_PROTECT
:
3316 case STATUS_INVALID_IMAGE_NOT_MZ
:
3317 case STATUS_INVALID_IMAGE_NE_FORMAT
:
3319 /* We're launching an executable application */
3320 BinarySubType
= BINARY_TYPE_EXE
;
3322 /* We can drop here from other "cases" above too, so check */
3323 if ((Status
== STATUS_INVALID_IMAGE_PROTECT
) ||
3324 (Status
== STATUS_INVALID_IMAGE_NE_FORMAT
) ||
3325 (BinarySubType
= BaseIsDosApplication(&PathName
, Status
)))
3327 /* We're launching a DOS application */
3328 VdmBinaryType
= BINARY_TYPE_DOS
;
3330 /* Based on the caller environment, create a VDM one */
3331 Result
= BaseCreateVDMEnvironment(lpEnvironment
,
3336 DPRINT1("VDM environment for DOS failed\n");
3340 /* Check the current state of the VDM subsystem */
3341 Status
= BaseCheckVDM(VdmBinaryType
| BinarySubType
,
3346 (PCSR_API_MESSAGE
)VdmMsg
,
3351 if (!NT_SUCCESS(Status
))
3353 /* Failed to inquire about VDM, fail the call */
3354 DPRINT1("VDM message failure for DOS: %lx\n", Status
);
3355 BaseSetLastNTError(Status
);
3360 /* Handle possible VDM states */
3361 switch (VdmMsg
->VDMState
& (VDM_NOT_LOADED
|
3365 case VDM_NOT_LOADED
:
3366 /* If VDM is not loaded, we'll do a partial undo */
3367 VdmUndoLevel
= VDM_UNDO_PARTIAL
;
3369 /* A VDM process can't also be detached, so fail */
3370 if (dwCreationFlags
& DETACHED_PROCESS
)
3372 DPRINT1("Detached process but no VDM, not allowed\n");
3373 SetLastError(ERROR_ACCESS_DENIED
);
3377 /* Get the required parameters and names for launch */
3378 Result
= BaseGetVdmConfigInfo(lpCommandLine
,
3385 DPRINT1("VDM Configuration failed for DOS\n");
3386 BaseSetLastNTError(Status
);
3390 /* Update the command-line to launch VDM instead */
3391 lpCommandLine
= VdmString
.Buffer
;
3392 lpApplicationName
= NULL
;
3396 /* VDM is ready, so we have to undo everything */
3397 VdmUndoLevel
= VDM_UNDO_REUSE
;
3399 /* Check if CSRSS wants us to wait on VDM */
3400 VdmWaitObject
= VdmMsg
->WaitObjectForParent
;
3404 /* Something is wrong with VDM, we'll fail the call */
3405 DPRINT1("VDM is not ready for DOS\n");
3406 SetLastError(ERROR_NOT_READY
);
3414 /* Since to get NULL, we allocate from 0x1, account for this */
3417 /* This implies VDM is ready, so skip everything else */
3418 if (VdmWaitObject
) goto VdmShortCircuit
;
3420 /* Don't inherit handles since we're doing VDM now */
3421 bInheritHandles
= FALSE
;
3423 /* Had the user passed in environment? If so, destroy it */
3424 if ((lpEnvironment
) &&
3425 !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3427 RtlDestroyEnvironment(lpEnvironment
);
3430 /* Use our VDM Unicode environment instead */
3431 lpEnvironment
= VdmUnicodeEnv
.Buffer
;
3435 /* It's a batch file, get the extension */
3436 ExtBuffer
= &PathName
.Buffer
[PathName
.Length
/ sizeof(WCHAR
) - 4];
3438 /* Make sure the extensions are correct */
3439 if ((PathName
.Length
< (4 * sizeof(WCHAR
))) ||
3440 ((_wcsnicmp(ExtBuffer
, L
".bat", 4)) &&
3441 (_wcsnicmp(ExtBuffer
, L
".cmd", 4))))
3443 DPRINT1("'%wZ': Invalid EXE, and not a batch or script file\n", &PathName
);
3444 SetLastError(ERROR_BAD_EXE_FORMAT
);
3449 /* Check if we need to account for quotes around the path */
3450 CmdQuoteLength
= CmdLineIsAppName
|| HasQuotes
;
3451 if (!CmdLineIsAppName
)
3453 if (HasQuotes
) CmdQuoteLength
++;
3460 /* Calculate the length of the command line */
3461 CmdLineLength
= wcslen(lpCommandLine
);
3462 CmdLineLength
+= wcslen(CMD_STRING
);
3463 CmdLineLength
+= CmdQuoteLength
+ sizeof(ANSI_NULL
);
3464 CmdLineLength
*= sizeof(WCHAR
);
3466 /* Allocate space for the new command line */
3467 AnsiCmdCommand
= RtlAllocateHeap(RtlGetProcessHeap(),
3470 if (!AnsiCmdCommand
)
3472 BaseSetLastNTError(STATUS_NO_MEMORY
);
3478 wcscpy(AnsiCmdCommand
, CMD_STRING
);
3479 if ((CmdLineIsAppName
) || (HasQuotes
))
3481 wcscat(AnsiCmdCommand
, L
"\"");
3483 wcscat(AnsiCmdCommand
, lpCommandLine
);
3484 if ((CmdLineIsAppName
) || (HasQuotes
))
3486 wcscat(AnsiCmdCommand
, L
"\"");
3489 /* Create it as a Unicode String */
3490 RtlInitUnicodeString(&DebuggerString
, AnsiCmdCommand
);
3492 /* Set the command line to this */
3493 lpCommandLine
= DebuggerString
.Buffer
;
3494 lpApplicationName
= NULL
;
3495 DPRINT1("Retrying with: %S\n", lpCommandLine
);
3498 /* We've already done all these checks, don't do them again */
3499 SkipSaferAndAppCompat
= TRUE
;
3503 case STATUS_INVALID_IMAGE_WIN_64
:
3505 /* 64-bit binaries are not allowed to run on 32-bit ReactOS */
3506 DPRINT1("64-bit binary, failing\n");
3507 SetLastError(ERROR_EXE_MACHINE_TYPE_MISMATCH
);
3512 case STATUS_FILE_IS_OFFLINE
:
3514 /* Set the correct last error for this */
3515 DPRINT1("File is offline, failing\n");
3516 SetLastError(ERROR_FILE_OFFLINE
);
3522 /* Any other error, convert it to a generic Win32 error */
3523 if (!NT_SUCCESS(Status
))
3525 DPRINT1("Failed to create section: %lx\n", Status
);
3526 SetLastError(ERROR_BAD_EXE_FORMAT
);
3531 /* Otherwise, this must be success */
3532 ASSERT(Status
== STATUS_SUCCESS
);
3537 /* Is this not a WOW application, but a WOW32 VDM was requested for it? */
3538 if (!(IsWowApp
) && (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
3540 /* Ignore the nonsensical request */
3541 dwCreationFlags
&= ~CREATE_SEPARATE_WOW_VDM
;
3544 /* Did we already check information for the section? */
3547 /* Get some information about the executable */
3548 Status
= NtQuerySection(SectionHandle
,
3549 SectionImageInformation
,
3551 sizeof(ImageInformation
),
3553 if (!NT_SUCCESS(Status
))
3555 /* We failed, bail out */
3556 DPRINT1("Section query failed\n");
3557 BaseSetLastNTError(Status
);
3562 /* Don't check this later */
3563 QuerySection
= TRUE
;
3566 /* Check if this was linked as a DLL */
3567 if (ImageInformation
.ImageCharacteristics
& IMAGE_FILE_DLL
)
3569 /* These aren't valid images to try to execute! */
3570 DPRINT1("Trying to launch a DLL, failing\n");
3571 SetLastError(ERROR_BAD_EXE_FORMAT
);
3576 /* Don't let callers pass in this flag -- we'll only get it from IFRO */
3577 Flags
&= ~PROCESS_CREATE_FLAGS_LARGE_PAGES
;
3579 /* Clear the IFEO-missing flag, before we know for sure... */
3580 ParameterFlags
&= ~2;
3582 /* If the process is being debugged, only read IFEO if the PEB says so */
3583 if (!(dwCreationFlags
& (DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
)) ||
3584 (NtCurrentPeb()->ReadImageFileExecOptions
))
3586 /* Let's do this! Attempt to open IFEO */
3587 Status1
= LdrOpenImageFileOptionsKey(&PathName
, 0, &KeyHandle
);
3588 if (!NT_SUCCESS(Status1
))
3590 /* We failed, set the flag so we store this in the parameters */
3591 if (Status1
== STATUS_OBJECT_NAME_NOT_FOUND
) ParameterFlags
|= 2;
3595 /* Was this our first time going through this path? */
3596 if (!DebuggerCmdLine
)
3598 /* Allocate a buffer for the debugger path */
3599 DebuggerCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3601 MAX_PATH
* sizeof(WCHAR
));
3602 if (!DebuggerCmdLine
)
3604 /* Close IFEO on failure */
3605 Status1
= NtClose(KeyHandle
);
3606 ASSERT(NT_SUCCESS(Status1
));
3609 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3615 /* Now query for the debugger */
3616 Status1
= LdrQueryImageFileKeyOption(KeyHandle
,
3620 MAX_PATH
* sizeof(WCHAR
),
3622 if (!(NT_SUCCESS(Status1
)) ||
3623 (ResultSize
< sizeof(WCHAR
)) ||
3624 (DebuggerCmdLine
[0] == UNICODE_NULL
))
3626 /* If it's not there, or too small, or invalid, ignore it */
3627 RtlFreeHeap(RtlGetProcessHeap(), 0, DebuggerCmdLine
);
3628 DebuggerCmdLine
= NULL
;
3631 /* Also query if we should map with large pages */
3632 Status1
= LdrQueryImageFileKeyOption(KeyHandle
,
3636 sizeof(UseLargePages
),
3638 if ((NT_SUCCESS(Status1
)) && (UseLargePages
))
3640 /* Do it! This is the only way this flag can be set */
3641 Flags
|= PROCESS_CREATE_FLAGS_LARGE_PAGES
;
3644 /* We're done with IFEO, can close it now */
3645 Status1
= NtClose(KeyHandle
);
3646 ASSERT(NT_SUCCESS(Status1
));
3650 /* Make sure the image was compiled for this processor */
3651 if ((ImageInformation
.Machine
< SharedUserData
->ImageNumberLow
) ||
3652 (ImageInformation
.Machine
> SharedUserData
->ImageNumberHigh
))
3654 /* It was not -- raise a hard error */
3655 ErrorResponse
= ResponseOk
;
3656 ErrorParameters
[0] = (ULONG_PTR
)&PathName
;
3657 NtRaiseHardError(STATUS_IMAGE_MACHINE_TYPE_MISMATCH_EXE
,
3663 if (Peb
->ImageSubsystemMajorVersion
<= 3)
3665 /* If it's really old, return this error */
3666 SetLastError(ERROR_BAD_EXE_FORMAT
);
3670 /* Otherwise, return a more modern error */
3671 SetLastError(ERROR_EXE_MACHINE_TYPE_MISMATCH
);
3674 /* Go to the failure path */
3675 DPRINT1("Invalid image architecture: %lx\n", ImageInformation
.Machine
);
3680 /* Check if this isn't a Windows image */
3681 if ((ImageInformation
.SubSystemType
!= IMAGE_SUBSYSTEM_WINDOWS_GUI
) &&
3682 (ImageInformation
.SubSystemType
!= IMAGE_SUBSYSTEM_WINDOWS_CUI
))
3684 /* Get rid of section-related information since we'll retry */
3685 NtClose(SectionHandle
);
3686 SectionHandle
= NULL
;
3687 QuerySection
= FALSE
;
3689 /* The only other non-Windows image type we support here is POSIX */
3690 if (ImageInformation
.SubSystemType
!= IMAGE_SUBSYSTEM_POSIX_CUI
)
3692 /* Bail out if it's something else */
3693 SetLastError(ERROR_CHILD_NOT_COMPLETE
);
3698 /* Now build the command-line to have posix launch this image */
3699 Result
= BuildSubSysCommandLine(L
"POSIX /P ",
3705 /* Bail out if that failed */
3706 DPRINT1("Subsystem command line failed\n");
3710 /* And re-try launching the process, with the new command-line now */
3711 lpCommandLine
= DebuggerString
.Buffer
;
3712 lpApplicationName
= NULL
;
3714 /* We've already done all these checks, don't do them again */
3715 SkipSaferAndAppCompat
= TRUE
;
3716 DPRINT1("Retrying with: %S\n", lpCommandLine
);
3720 /* Was this image built for a version of Windows whose images we can run? */
3721 Result
= BasepIsImageVersionOk(ImageInformation
.SubSystemMajorVersion
,
3722 ImageInformation
.SubSystemMinorVersion
);
3725 /* It was not, bail out */
3726 DPRINT1("Invalid subsystem version: %hu.%hu\n",
3727 ImageInformation
.SubSystemMajorVersion
,
3728 ImageInformation
.SubSystemMinorVersion
);
3729 SetLastError(ERROR_BAD_EXE_FORMAT
);
3733 /* Check if there is a debugger associated with the application */
3734 if (DebuggerCmdLine
)
3736 /* Get the length of the command line */
3737 n
= wcslen(lpCommandLine
);
3740 /* There's no command line, use the application name instead */
3741 lpCommandLine
= (LPWSTR
)lpApplicationName
;
3742 n
= wcslen(lpCommandLine
);
3745 /* Protect against overflow */
3746 if (n
> UNICODE_STRING_MAX_CHARS
)
3748 BaseSetLastNTError(STATUS_NAME_TOO_LONG
);
3753 /* Now add the length of the debugger command-line */
3754 n
+= wcslen(DebuggerCmdLine
);
3756 /* Again make sure we don't overflow */
3757 if (n
> UNICODE_STRING_MAX_CHARS
)
3759 BaseSetLastNTError(STATUS_NAME_TOO_LONG
);
3764 /* Account for the quotes and space between the two */
3765 n
+= sizeof("\" \"") - sizeof(ANSI_NULL
);
3767 /* Convert to bytes, and make sure we don't overflow */
3769 if (n
> UNICODE_STRING_MAX_BYTES
)
3771 BaseSetLastNTError(STATUS_NAME_TOO_LONG
);
3776 /* Allocate space for the string */
3777 DebuggerString
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(), 0, n
);
3778 if (!DebuggerString
.Buffer
)
3780 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3785 /* Set the length */
3786 RtlInitEmptyUnicodeString(&DebuggerString
,
3787 DebuggerString
.Buffer
,
3790 /* Now perform the command line creation */
3791 ImageDbgStatus
= RtlAppendUnicodeToString(&DebuggerString
,
3793 ASSERT(NT_SUCCESS(ImageDbgStatus
));
3794 ImageDbgStatus
= RtlAppendUnicodeToString(&DebuggerString
, L
" ");
3795 ASSERT(NT_SUCCESS(ImageDbgStatus
));
3796 ImageDbgStatus
= RtlAppendUnicodeToString(&DebuggerString
, lpCommandLine
);
3797 ASSERT(NT_SUCCESS(ImageDbgStatus
));
3799 /* Make sure it all looks nice */
3800 DbgPrint("BASE: Calling debugger with '%wZ'\n", &DebuggerString
);
3802 /* Update the command line and application name */
3803 lpCommandLine
= DebuggerString
.Buffer
;
3804 lpApplicationName
= NULL
;
3806 /* Close all temporary state */
3807 NtClose(SectionHandle
);
3808 SectionHandle
= NULL
;
3809 QuerySection
= FALSE
;
3811 /* Free all temporary memory */
3812 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
3814 RtlFreeHeap(RtlGetProcessHeap(), 0, FreeBuffer
);
3816 RtlFreeHeap(RtlGetProcessHeap(), 0, DebuggerCmdLine
);
3817 DebuggerCmdLine
= NULL
;
3818 DPRINT1("Retrying with: %S\n", lpCommandLine
);
3822 /* Initialize the process object attributes */
3823 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
3824 lpProcessAttributes
,
3826 if ((hUserToken
) && (lpProcessAttributes
))
3828 /* Auggment them with information from the user */
3830 LocalProcessAttributes
= *lpProcessAttributes
;
3831 LocalProcessAttributes
.lpSecurityDescriptor
= NULL
;
3832 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
3833 &LocalProcessAttributes
,
3837 /* Check if we're going to be debugged */
3838 if (dwCreationFlags
& DEBUG_PROCESS
)
3840 /* Set process flag */
3841 Flags
|= PROCESS_CREATE_FLAGS_BREAKAWAY
;
3844 /* Check if we're going to be debugged */
3845 if (dwCreationFlags
& (DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
))
3847 /* Connect to DbgUi */
3848 Status
= DbgUiConnectToDbg();
3849 if (!NT_SUCCESS(Status
))
3851 DPRINT1("Failed to connect to DbgUI!\n");
3852 BaseSetLastNTError(Status
);
3857 /* Get the debug object */
3858 DebugHandle
= DbgUiGetThreadDebugObject();
3860 /* Check if only this process will be debugged */
3861 if (dwCreationFlags
& DEBUG_ONLY_THIS_PROCESS
)
3863 /* Set process flag */
3864 Flags
|= PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT
;
3868 /* Set inherit flag */
3869 if (bInheritHandles
) Flags
|= PROCESS_CREATE_FLAGS_INHERIT_HANDLES
;
3871 /* Check if the process should be created with large pages */
3872 HavePrivilege
= FALSE
;
3873 PrivilegeState
= NULL
;
3874 if (Flags
& PROCESS_CREATE_FLAGS_LARGE_PAGES
)
3876 /* Acquire the required privilege so that the kernel won't fail the call */
3877 PrivilegeValue
= SE_LOCK_MEMORY_PRIVILEGE
;
3878 Status
= RtlAcquirePrivilege(&PrivilegeValue
, TRUE
, FALSE
, &PrivilegeState
);
3879 if (NT_SUCCESS(Status
))
3881 /* Remember to release it later */
3882 HavePrivilege
= TRUE
;
3886 /* Save the current TIB value since kernel overwrites it to store PEB */
3887 TibValue
= Teb
->NtTib
.ArbitraryUserPointer
;
3889 /* Tell the kernel to create the process */
3890 Status
= NtCreateProcessEx(&ProcessHandle
,
3900 /* Load the PEB address from the hacky location where the kernel stores it */
3901 RemotePeb
= Teb
->NtTib
.ArbitraryUserPointer
;
3903 /* And restore the old TIB value */
3904 Teb
->NtTib
.ArbitraryUserPointer
= TibValue
;
3906 /* Release the large page privilege if we had acquired it */
3907 if (HavePrivilege
) RtlReleasePrivilege(PrivilegeState
);
3909 /* And now check if the kernel failed to create the process */
3910 if (!NT_SUCCESS(Status
))
3912 /* Go to failure path */
3913 DPRINT1("Failed to create process: %lx\n", Status
);
3914 BaseSetLastNTError(Status
);
3919 /* Check if there is a priority class to set */
3920 if (PriorityClass
.PriorityClass
)
3922 /* Reset current privilege state */
3923 RealTimePrivilegeState
= NULL
;
3925 /* Is realtime priority being requested? */
3926 if (PriorityClass
.PriorityClass
== PROCESS_PRIORITY_CLASS_REALTIME
)
3928 /* Check if the caller has real-time access, and enable it if so */
3929 RealTimePrivilegeState
= BasepIsRealtimeAllowed(TRUE
);
3932 /* Set the new priority class and release the privilege */
3933 Status
= NtSetInformationProcess(ProcessHandle
,
3934 ProcessPriorityClass
,
3936 sizeof(PROCESS_PRIORITY_CLASS
));
3937 if (RealTimePrivilegeState
) RtlReleasePrivilege(RealTimePrivilegeState
);
3939 /* Check if we failed to set the priority class */
3940 if (!NT_SUCCESS(Status
))
3942 /* Bail out on failure */
3943 DPRINT1("Failed to set priority class: %lx\n", Status
);
3944 BaseSetLastNTError(Status
);
3950 /* Check if the caller wants the default error mode */
3951 if (dwCreationFlags
& CREATE_DEFAULT_ERROR_MODE
)
3953 /* Set Error Mode to only fail on critical errors */
3954 HardErrorMode
= SEM_FAILCRITICALERRORS
;
3955 NtSetInformationProcess(ProcessHandle
,
3956 ProcessDefaultHardErrorMode
,
3961 /* Check if this was a VDM binary */
3964 /* Update VDM by telling it the process has now been created */
3965 VdmWaitObject
= ProcessHandle
;
3966 Result
= BaseUpdateVDMEntry(VdmEntryUpdateProcess
,
3971 /* Bail out on failure */
3972 DPRINT1("Failed to update VDM with wait object\n");
3973 VdmWaitObject
= NULL
;
3977 /* At this point, a failure means VDM has to undo all the state */
3978 VdmUndoLevel
|= VDM_UNDO_FULL
;
3981 /* Check if VDM needed reserved low-memory */
3984 /* Reserve the requested allocation */
3985 Status
= NtAllocateVirtualMemory(ProcessHandle
,
3990 PAGE_EXECUTE_READWRITE
);
3991 if (!NT_SUCCESS(Status
))
3993 /* Bail out on failure */
3994 DPRINT1("Failed to reserved memory for VDM: %lx\n", Status
);
3995 BaseSetLastNTError(Status
);
4001 /* Check if we've already queried information on the section */
4004 /* We haven't, so get some information about the executable */
4005 Status
= NtQuerySection(SectionHandle
,
4006 SectionImageInformation
,
4008 sizeof(ImageInformation
),
4010 if (!NT_SUCCESS(Status
))
4012 /* Bail out on failure */
4013 DPRINT1("Failed to query section: %lx\n", Status
);
4014 BaseSetLastNTError(Status
);
4019 /* If we encounter a restart, don't re-query this information again */
4020 QuerySection
= TRUE
;
4023 /* Do we need to apply SxS to this image? */
4024 if (!(ImageInformation
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NO_ISOLATION
))
4026 /* Too bad, we don't support this yet */
4027 DPRINT1("Image should receive SxS Fusion Isolation\n");
4030 /* There's some SxS flag that we need to set if fusion flags have 1 set */
4031 if (FusionFlags
& 1) CreateProcessMsg
->Sxs
.Flags
|= 0x10;
4033 /* Check if we have a current directory */
4034 if (lpCurrentDirectory
)
4036 /* Allocate a buffer so we can keep a Unicode copy */
4037 DPRINT1("Current directory: %S\n", lpCurrentDirectory
);
4038 CurrentDirectory
= RtlAllocateHeap(RtlGetProcessHeap(),
4040 (MAX_PATH
* sizeof(WCHAR
)) +
4041 sizeof(UNICODE_NULL
));
4042 if (!CurrentDirectory
)
4044 /* Bail out if this failed */
4045 BaseSetLastNTError(STATUS_NO_MEMORY
);
4050 /* Get the length in Unicode */
4051 Length
= GetFullPathNameW(lpCurrentDirectory
,
4055 if (Length
> MAX_PATH
)
4057 /* The directory is too long, so bail out */
4058 SetLastError(ERROR_DIRECTORY
);
4063 /* Make sure the directory is actually valid */
4064 CurdirLength
= GetFileAttributesW(CurrentDirectory
);
4065 if ((CurdirLength
== 0xffffffff) ||
4066 !(CurdirLength
& FILE_ATTRIBUTE_DIRECTORY
))
4068 /* It isn't, so bail out */
4069 DPRINT1("Current directory is invalid\n");
4070 SetLastError(ERROR_DIRECTORY
);
4076 /* Insert quotes if needed */
4077 if ((QuotesNeeded
) || (CmdLineIsAppName
))
4079 /* Allocate our buffer, plus enough space for quotes and a NULL */
4080 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
4082 (wcslen(lpCommandLine
) * sizeof(WCHAR
)) +
4083 (2 * sizeof(L
'\"') + sizeof(UNICODE_NULL
)));
4086 /* Copy the first quote */
4087 wcscpy(QuotedCmdLine
, L
"\"");
4089 /* Save the current null-character */
4092 SaveChar
= *NullBuffer
;
4093 *NullBuffer
= UNICODE_NULL
;
4096 /* Copy the command line and the final quote */
4097 wcscat(QuotedCmdLine
, lpCommandLine
);
4098 wcscat(QuotedCmdLine
, L
"\"");
4100 /* Copy the null-char back */
4103 *NullBuffer
= SaveChar
;
4104 wcscat(QuotedCmdLine
, NullBuffer
);
4109 /* We can't put quotes around the thing, so try it anyway */
4110 if (QuotesNeeded
) QuotesNeeded
= FALSE
;
4111 if (CmdLineIsAppName
) CmdLineIsAppName
= FALSE
;
4115 /* Use isolation if needed */
4116 if (CreateProcessMsg
->Sxs
.Flags
& 1) ParameterFlags
|= 1;
4118 /* Set the new command-line if needed */
4119 if ((QuotesNeeded
) || (CmdLineIsAppName
)) lpCommandLine
= QuotedCmdLine
;
4121 /* Call the helper function in charge of RTL_USER_PROCESS_PARAMETERS */
4122 Result
= BasePushProcessParameters(ParameterFlags
,
4130 dwCreationFlags
| NoWindow
,
4132 IsWowApp
? IMAGE_SUBSYSTEM_WINDOWS_GUI
: 0,
4137 /* The remote process would have an undefined state, so fail the call */
4138 DPRINT1("BasePushProcessParameters failed\n");
4142 /* Free the VDM command line string as it's no longer needed */
4143 RtlFreeUnicodeString(&VdmString
);
4144 VdmString
.Buffer
= NULL
;
4146 /* Non-VDM console applications usually inherit handles unless specified */
4147 if (!(VdmBinaryType
) &&
4148 !(bInheritHandles
) &&
4149 !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
4150 !(dwCreationFlags
& (CREATE_NO_WINDOW
|
4151 CREATE_NEW_CONSOLE
|
4152 DETACHED_PROCESS
)) &&
4153 (ImageInformation
.SubSystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
))
4155 /* Get the remote parameters */
4156 Status
= NtReadVirtualMemory(ProcessHandle
,
4157 &RemotePeb
->ProcessParameters
,
4159 sizeof(PRTL_USER_PROCESS_PARAMETERS
),
4161 if (NT_SUCCESS(Status
))
4163 /* Duplicate standard input unless it's a console handle */
4164 if (!IsConsoleHandle(Peb
->ProcessParameters
->StandardInput
))
4166 StuffStdHandle(ProcessHandle
,
4167 Peb
->ProcessParameters
->StandardInput
,
4168 &ProcessParameters
->StandardInput
);
4171 /* Duplicate standard output unless it's a console handle */
4172 if (!IsConsoleHandle(Peb
->ProcessParameters
->StandardOutput
))
4174 StuffStdHandle(ProcessHandle
,
4175 Peb
->ProcessParameters
->StandardOutput
,
4176 &ProcessParameters
->StandardOutput
);
4179 /* Duplicate standard error unless it's a console handle */
4180 if (!IsConsoleHandle(Peb
->ProcessParameters
->StandardError
))
4182 StuffStdHandle(ProcessHandle
,
4183 Peb
->ProcessParameters
->StandardError
,
4184 &ProcessParameters
->StandardError
);
4189 /* Create the Thread's Stack */
4190 StackSize
= max(256 * 1024, ImageInformation
.MaximumStackSize
);
4191 Status
= BaseCreateStack(ProcessHandle
,
4192 ImageInformation
.CommittedStackSize
,
4195 if (!NT_SUCCESS(Status
))
4197 DPRINT1("Creating the thread stack failed: %lx\n", Status
);
4198 BaseSetLastNTError(Status
);
4203 /* Create the Thread's Context */
4204 BaseInitializeContext(&Context
,
4206 ImageInformation
.TransferAddress
,
4207 InitialTeb
.StackBase
,
4210 /* Convert the thread attributes */
4211 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
4214 if ((hUserToken
) && (lpThreadAttributes
))
4216 /* If the caller specified a user token, zero the security descriptor */
4217 LocalThreadAttributes
= *lpThreadAttributes
;
4218 LocalThreadAttributes
.lpSecurityDescriptor
= NULL
;
4219 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
4220 &LocalThreadAttributes
,
4224 /* Create the Kernel Thread Object */
4225 Status
= NtCreateThread(&ThreadHandle
,
4233 if (!NT_SUCCESS(Status
))
4235 /* A process is not allowed to exist without a main thread, so fail */
4236 DPRINT1("Creating the main thread failed: %lx\n", Status
);
4237 BaseSetLastNTError(Status
);
4242 /* Begin filling out the CSRSS message, first with our IDs and handles */
4243 CreateProcessMsg
->ProcessHandle
= ProcessHandle
;
4244 CreateProcessMsg
->ThreadHandle
= ThreadHandle
;
4245 CreateProcessMsg
->ClientId
= ClientId
;
4247 /* Write the remote PEB address and clear it locally, we no longer use it */
4248 CreateProcessMsg
->PebAddressNative
= RemotePeb
;
4249 CreateProcessMsg
->PebAddressWow64
= (ULONG
)RemotePeb
;
4252 /* Now check what kind of architecture this image was made for */
4253 switch (ImageInformation
.Machine
)
4255 /* IA32, IA64 and AMD64 are supported in Server 2003 */
4256 case IMAGE_FILE_MACHINE_I386
:
4257 CreateProcessMsg
->ProcessorArchitecture
= PROCESSOR_ARCHITECTURE_INTEL
;
4259 case IMAGE_FILE_MACHINE_IA64
:
4260 CreateProcessMsg
->ProcessorArchitecture
= PROCESSOR_ARCHITECTURE_IA64
;
4262 case IMAGE_FILE_MACHINE_AMD64
:
4263 CreateProcessMsg
->ProcessorArchitecture
= PROCESSOR_ARCHITECTURE_AMD64
;
4266 /* Anything else results in image unknown -- but no failure */
4268 DbgPrint("kernel32: No mapping for ImageInformation.Machine == %04x\n",
4269 ImageInformation
.Machine
);
4270 CreateProcessMsg
->ProcessorArchitecture
= PROCESSOR_ARCHITECTURE_UNKNOWN
;
4274 /* Write the input creation flags except any debugger-related flags */
4275 CreateProcessMsg
->CreationFlags
= dwCreationFlags
&
4276 ~(DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
);
4278 /* CSRSS needs to know if this is a GUI app or not */
4279 if ((ImageInformation
.SubSystemType
== IMAGE_SUBSYSTEM_WINDOWS_GUI
) ||
4283 * For GUI apps we turn on the 2nd bit. This allow CSRSS server dlls
4284 * (basesrv in particular) to know whether or not this is a GUI or a
4287 AddToHandle(CreateProcessMsg
->ProcessHandle
, 2);
4289 /* Also check if the parent is also a GUI process */
4290 NtHeaders
= RtlImageNtHeader(GetModuleHandle(NULL
));
4292 (NtHeaders
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
))
4294 /* Let it know that it should display the hourglass mouse cursor */
4295 AddToHandle(CreateProcessMsg
->ProcessHandle
, 1);
4299 /* For all apps, if this flag is on, the hourglass mouse cursor is shown */
4300 if (StartupInfo
.dwFlags
& STARTF_FORCEONFEEDBACK
)
4302 AddToHandle(CreateProcessMsg
->ProcessHandle
, 1);
4305 /* Likewise, the opposite holds as well */
4306 if (StartupInfo
.dwFlags
& STARTF_FORCEOFFFEEDBACK
)
4308 RemoveFromHandle(CreateProcessMsg
->ProcessHandle
, 1);
4311 /* Also store which kind of VDM app (if any) this is */
4312 CreateProcessMsg
->VdmBinaryType
= VdmBinaryType
;
4314 /* And if it really is a VDM app... */
4317 /* Store the task ID and VDM console handle */
4318 CreateProcessMsg
->hVDM
= VdmTask
? 0 : Peb
->ProcessParameters
->ConsoleHandle
;
4319 CreateProcessMsg
->VdmTask
= VdmTask
;
4321 else if (VdmReserve
)
4323 /* Extended VDM, set a flag */
4324 CreateProcessMsg
->VdmBinaryType
|= BINARY_TYPE_WOW_EX
;
4327 /* Check if there's side-by-side assembly data associated with the process */
4328 if (CreateProcessMsg
->Sxs
.Flags
)
4330 /* This should not happen in ReactOS yet */
4331 DPRINT1("This is an SxS Message -- should not happen yet\n");
4332 BaseSetLastNTError(STATUS_NOT_IMPLEMENTED
);
4333 NtTerminateProcess(ProcessHandle
, STATUS_NOT_IMPLEMENTED
);
4338 /* We are finally ready to call CSRSS to tell it about our new process! */
4339 CsrClientCallServer((PCSR_API_MESSAGE
)&CsrMsg
,
4341 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
,
4342 BasepCreateProcess
),
4343 sizeof(*CreateProcessMsg
));
4345 /* CSRSS has returned, free the capture buffer now if we had one */
4348 CsrFreeCaptureBuffer(CaptureBuffer
);
4349 CaptureBuffer
= NULL
;
4352 /* Check if CSRSS failed to accept ownership of the new Windows process */
4353 if (!NT_SUCCESS(CsrMsg
.Status
))
4355 /* Terminate the process and enter failure path with the CSRSS status */
4356 DPRINT1("Failed to tell csrss about new process\n");
4357 BaseSetLastNTError(CsrMsg
.Status
);
4358 NtTerminateProcess(ProcessHandle
, CsrMsg
.Status
);
4363 /* Check if we have a token due to Authz/Safer, not passed by the user */
4364 if ((TokenHandle
) && !(hUserToken
))
4366 /* Replace the process and/or thread token with the one from Safer */
4367 Status
= BasepReplaceProcessThreadTokens(TokenHandle
,
4370 if (!NT_SUCCESS(Status
))
4372 /* If this failed, kill the process and enter the failure path */
4373 DPRINT1("Failed to update process token: %lx\n", Status
);
4374 NtTerminateProcess(ProcessHandle
, Status
);
4375 BaseSetLastNTError(Status
);
4381 /* Check if a job was associated with this process */
4384 /* Bind the process and job together now */
4385 Status
= NtAssignProcessToJobObject(JobHandle
, ProcessHandle
);
4386 if (!NT_SUCCESS(Status
))
4388 /* Kill the process and enter the failure path if binding failed */
4389 DPRINT1("Failed to assign process to job: %lx\n", Status
);
4390 NtTerminateProcess(ProcessHandle
, STATUS_ACCESS_DENIED
);
4391 BaseSetLastNTError(Status
);
4397 /* Finally, resume the thread to actually get the process started */
4398 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
4400 NtResumeThread(ThreadHandle
, &ResumeCount
);
4404 /* We made it this far, meaning we have a fully created process and thread */
4407 /* Anyone doing a VDM undo should now undo everything, since we are done */
4408 if (VdmUndoLevel
) VdmUndoLevel
|= VDM_UNDO_COMPLETED
;
4410 /* Having a VDM wait object implies this must be a VDM process */
4413 /* Check if it's a 16-bit separate WOW process */
4414 if (VdmBinaryType
== BINARY_TYPE_SEPARATE_WOW
)
4416 /* OR-in the special flag to indicate this, and return to caller */
4417 AddToHandle(VdmWaitObject
, 2);
4418 lpProcessInformation
->hProcess
= VdmWaitObject
;
4420 /* Check if this was a re-used VDM */
4421 if (VdmUndoLevel
& VDM_UNDO_REUSE
)
4423 /* No Client ID should be returned in this case */
4424 ClientId
.UniqueProcess
= 0;
4425 ClientId
.UniqueThread
= 0;
4430 /* OR-in the special flag to indicate this is not a separate VDM */
4431 AddToHandle(VdmWaitObject
, 1);
4433 /* Return handle to the caller */
4434 lpProcessInformation
->hProcess
= VdmWaitObject
;
4437 /* Close the original process handle, since it's not needed for VDM */
4438 if (ProcessHandle
) NtClose(ProcessHandle
);
4442 /* This is a regular process, so return the real process handle */
4443 lpProcessInformation
->hProcess
= ProcessHandle
;
4446 /* Return the rest of the process information based on what we have so far */
4447 lpProcessInformation
->hThread
= ThreadHandle
;
4448 lpProcessInformation
->dwProcessId
= HandleToUlong(ClientId
.UniqueProcess
);
4449 lpProcessInformation
->dwThreadId
= HandleToUlong(ClientId
.UniqueThread
);
4451 /* NULL these out here so we know to treat this as a success scenario */
4452 ProcessHandle
= NULL
;
4453 ThreadHandle
= NULL
;
4456 /* Free the debugger command line if one was allocated */
4457 if (DebuggerCmdLine
) RtlFreeHeap(RtlGetProcessHeap(), 0, DebuggerCmdLine
);
4459 /* Check if an SxS full path as queried */
4462 /* Reinitialize the executable path */
4463 RtlInitEmptyUnicodeString(&SxsWin32ExePath
, NULL
, 0);
4464 SxsWin32ExePath
.Length
= 0;
4466 /* Free the path buffer */
4467 RtlFreeHeap(RtlGetProcessHeap(), 0, PathBuffer
);
4470 #if _SXS_SUPPORT_ENABLED_
4471 /* Check if this was a non-VDM process */
4474 /* Then it must've had SxS data, so close the handles used for it */
4475 BasepSxsCloseHandles(&Handles
);
4476 BasepSxsCloseHandles(&FileHandles
);
4478 /* Check if we built SxS byte buffers for this create process request */
4479 if (SxsConglomeratedBuffer
)
4481 /* Loop all of them */
4482 for (i
= 0; i
< 5; i
++)
4484 /* Check if this one was allocated */
4485 ThisBuffer
= SxsStaticBuffers
[i
];
4488 /* Get the underlying RTL_BUFFER structure */
4489 ByteBuffer
= &ThisBuffer
->ByteBuffer
;
4490 if ((ThisBuffer
!= (PVOID
)-8) && (ByteBuffer
->Buffer
))
4492 /* Check if it was dynamic */
4493 if (ByteBuffer
->Buffer
!= ByteBuffer
->StaticBuffer
)
4495 /* Free it from the heap */
4496 FreeString
.Buffer
= (PWCHAR
)ByteBuffer
->Buffer
;
4497 RtlFreeUnicodeString(&FreeString
);
4500 /* Reset the buffer to its static data */
4501 ByteBuffer
->Buffer
= ByteBuffer
->StaticBuffer
;
4502 ByteBuffer
->Size
= ByteBuffer
->StaticSize
;
4505 /* Reset the string to the static buffer */
4506 RtlInitEmptyUnicodeString(&ThisBuffer
->String
,
4507 (PWCHAR
)ByteBuffer
->StaticBuffer
,
4508 ByteBuffer
->StaticSize
);
4509 if (ThisBuffer
->String
.Buffer
)
4511 /* Also NULL-terminate it */
4512 *ThisBuffer
->String
.Buffer
= UNICODE_NULL
;
4519 /* Check if an environment was passed in */
4520 if ((lpEnvironment
) && !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
4523 RtlDestroyEnvironment(lpEnvironment
);
4525 /* If this was the VDM environment too, clear that as well */
4526 if (VdmUnicodeEnv
.Buffer
== lpEnvironment
) VdmUnicodeEnv
.Buffer
= NULL
;
4527 lpEnvironment
= NULL
;
4530 /* Unconditionally free all the name parsing buffers we always allocate */
4531 RtlFreeHeap(RtlGetProcessHeap(), 0, QuotedCmdLine
);
4532 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
4533 RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentDirectory
);
4534 RtlFreeHeap(RtlGetProcessHeap(), 0, FreeBuffer
);
4536 /* Close open file/section handles */
4537 if (FileHandle
) NtClose(FileHandle
);
4538 if (SectionHandle
) NtClose(SectionHandle
);
4540 /* If we have a thread handle, this was a failure path */
4543 /* So kill the process and close the thread handle */
4544 NtTerminateProcess(ProcessHandle
, 0);
4545 NtClose(ThreadHandle
);
4548 /* If we have a process handle, this was a failure path, so close it */
4549 if (ProcessHandle
) NtClose(ProcessHandle
);
4551 /* Thread/process handles, if any, are now processed. Now close this one. */
4552 if (JobHandle
) NtClose(JobHandle
);
4554 /* Check if we had created a token */
4557 /* And if the user asked for one */
4560 /* Then return it */
4561 *hNewToken
= TokenHandle
;
4565 /* User didn't want it, so we used it temporarily -- close it */
4566 NtClose(TokenHandle
);
4570 /* Free any temporary app compatibility data, it's no longer needed */
4571 BasepFreeAppCompatData(AppCompatData
, AppCompatSxsData
);
4573 /* Free a few strings. The API takes care of these possibly being NULL */
4574 RtlFreeUnicodeString(&VdmString
);
4575 RtlFreeUnicodeString(&DebuggerString
);
4577 /* Check if we had built any sort of VDM environment */
4578 if ((VdmAnsiEnv
.Buffer
) || (VdmUnicodeEnv
.Buffer
))
4581 BaseDestroyVDMEnvironment(&VdmAnsiEnv
, &VdmUnicodeEnv
);
4584 /* Check if this was any kind of VDM application that we ended up creating */
4585 if ((VdmUndoLevel
) && (!(VdmUndoLevel
& VDM_UNDO_COMPLETED
)))
4588 BaseUpdateVDMEntry(VdmEntryUndo
,
4593 /* And close whatever VDM handle we were using for notifications */
4594 if (VdmWaitObject
) NtClose(VdmWaitObject
);
4597 /* Check if we ended up here with an allocated search path, and free it */
4598 if (SearchPath
) RtlFreeHeap(RtlGetProcessHeap(), 0, SearchPath
);
4600 /* Finally, return the API's result */
4609 CreateProcessW(LPCWSTR lpApplicationName
,
4610 LPWSTR lpCommandLine
,
4611 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
4612 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
4613 BOOL bInheritHandles
,
4614 DWORD dwCreationFlags
,
4615 LPVOID lpEnvironment
,
4616 LPCWSTR lpCurrentDirectory
,
4617 LPSTARTUPINFOW lpStartupInfo
,
4618 LPPROCESS_INFORMATION lpProcessInformation
)
4620 /* Call the internal (but exported) version */
4621 return CreateProcessInternalW(NULL
,
4624 lpProcessAttributes
,
4631 lpProcessInformation
,
4640 CreateProcessInternalA(HANDLE hToken
,
4641 LPCSTR lpApplicationName
,
4642 LPSTR lpCommandLine
,
4643 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
4644 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
4645 BOOL bInheritHandles
,
4646 DWORD dwCreationFlags
,
4647 LPVOID lpEnvironment
,
4648 LPCSTR lpCurrentDirectory
,
4649 LPSTARTUPINFOA lpStartupInfo
,
4650 LPPROCESS_INFORMATION lpProcessInformation
,
4653 PUNICODE_STRING CommandLine
= NULL
;
4654 UNICODE_STRING DummyString
;
4655 UNICODE_STRING LiveCommandLine
;
4656 UNICODE_STRING ApplicationName
;
4657 UNICODE_STRING CurrentDirectory
;
4659 STARTUPINFOW StartupInfo
;
4661 DPRINT("dwCreationFlags %x, lpEnvironment %p, lpCurrentDirectory %p, "
4662 "lpStartupInfo %p, lpProcessInformation %p\n",
4663 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
4664 lpStartupInfo
, lpProcessInformation
);
4666 /* Copy Startup Info */
4667 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
4669 /* Initialize all strings to nothing */
4670 LiveCommandLine
.Buffer
= NULL
;
4671 DummyString
.Buffer
= NULL
;
4672 ApplicationName
.Buffer
= NULL
;
4673 CurrentDirectory
.Buffer
= NULL
;
4674 StartupInfo
.lpDesktop
= NULL
;
4675 StartupInfo
.lpReserved
= NULL
;
4676 StartupInfo
.lpTitle
= NULL
;
4678 /* Convert the Command line */
4681 /* If it's too long, then we'll have a problem */
4682 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
4683 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
4685 /* Cache it in the TEB */
4686 CommandLine
= Basep8BitStringToStaticUnicodeString(lpCommandLine
);
4690 /* Use a dynamic version */
4691 Basep8BitStringToDynamicUnicodeString(&LiveCommandLine
,
4697 /* The logic below will use CommandLine, so we must make it valid */
4698 CommandLine
= &DummyString
;
4701 /* Convert the Name and Directory */
4702 if (lpApplicationName
)
4704 Basep8BitStringToDynamicUnicodeString(&ApplicationName
,
4707 if (lpCurrentDirectory
)
4709 Basep8BitStringToDynamicUnicodeString(&CurrentDirectory
,
4710 lpCurrentDirectory
);
4713 /* Now convert Startup Strings */
4714 if (lpStartupInfo
->lpReserved
)
4716 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
4717 &StartupInfo
.lpReserved
);
4719 if (lpStartupInfo
->lpDesktop
)
4721 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
4722 &StartupInfo
.lpDesktop
);
4724 if (lpStartupInfo
->lpTitle
)
4726 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
4727 &StartupInfo
.lpTitle
);
4730 /* Call the Unicode function */
4731 bRetVal
= CreateProcessInternalW(hToken
,
4732 ApplicationName
.Buffer
,
4733 LiveCommandLine
.Buffer
?
4734 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
4735 lpProcessAttributes
,
4740 CurrentDirectory
.Buffer
,
4742 lpProcessInformation
,
4746 RtlFreeUnicodeString(&ApplicationName
);
4747 RtlFreeUnicodeString(&LiveCommandLine
);
4748 RtlFreeUnicodeString(&CurrentDirectory
);
4749 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpDesktop
);
4750 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpReserved
);
4751 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpTitle
);
4753 /* Return what Unicode did */
4758 * FUNCTION: The CreateProcess function creates a new process and its
4759 * primary thread. The new process executes the specified executable file
4762 * lpApplicationName = Pointer to name of executable module
4763 * lpCommandLine = Pointer to command line string
4764 * lpProcessAttributes = Process security attributes
4765 * lpThreadAttributes = Thread security attributes
4766 * bInheritHandles = Handle inheritance flag
4767 * dwCreationFlags = Creation flags
4768 * lpEnvironment = Pointer to new environment block
4769 * lpCurrentDirectory = Pointer to current directory name
4770 * lpStartupInfo = Pointer to startup info
4771 * lpProcessInformation = Pointer to process information
4777 CreateProcessA(LPCSTR lpApplicationName
,
4778 LPSTR lpCommandLine
,
4779 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
4780 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
4781 BOOL bInheritHandles
,
4782 DWORD dwCreationFlags
,
4783 LPVOID lpEnvironment
,
4784 LPCSTR lpCurrentDirectory
,
4785 LPSTARTUPINFOA lpStartupInfo
,
4786 LPPROCESS_INFORMATION lpProcessInformation
)
4788 /* Call the internal (but exported) version */
4789 return CreateProcessInternalA(NULL
,
4792 lpProcessAttributes
,
4799 lpProcessInformation
,
4808 WinExec(LPCSTR lpCmdLine
,
4811 STARTUPINFOA StartupInfo
;
4812 PROCESS_INFORMATION ProcessInformation
;
4815 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
4816 StartupInfo
.cb
= sizeof(STARTUPINFOA
);
4817 StartupInfo
.wShowWindow
= (WORD
)uCmdShow
;
4818 StartupInfo
.dwFlags
= 0;
4820 if (!CreateProcessA(NULL
,
4829 &ProcessInformation
))
4831 dosErr
= GetLastError();
4832 return dosErr
< 32 ? dosErr
: ERROR_BAD_FORMAT
;
4835 if (NULL
!= UserWaitForInputIdleRoutine
)
4837 UserWaitForInputIdleRoutine(ProcessInformation
.hProcess
,
4841 NtClose(ProcessInformation
.hProcess
);
4842 NtClose(ProcessInformation
.hThread
);
4844 return 33; /* Something bigger than 31 means success. */