3 * COPYRIGHT: See COPYING in the top level directory
4 * PROJECT: ReactOS system libraries
5 * FILE: lib/kernel32/proc/proc.c
6 * PURPOSE: Process functions
7 * PROGRAMMER: Ariadne ( ariadne@xs4all.nl)
12 /* INCLUDES ****************************************************************/
19 /* GLOBALS *******************************************************************/
21 WaitForInputIdleType UserWaitForInputIdleRoutine
;
22 UNICODE_STRING BaseUnicodeCommandLine
;
23 ANSI_STRING BaseAnsiCommandLine
;
24 UNICODE_STRING BasePathVariableName
= RTL_CONSTANT_STRING(L
"PATH");
25 LPSTARTUPINFOA BaseAnsiStartupInfo
= NULL
;
26 PLDR_DATA_TABLE_ENTRY BasepExeLdrEntry
;
27 BOOLEAN g_AppCertInitialized
;
28 BOOLEAN g_HaveAppCerts
;
29 LIST_ENTRY BasepAppCertDllsList
;
30 RTL_CRITICAL_SECTION gcsAppCert
;
31 PBASEP_APPCERT_EMBEDDED_FUNC fEmbeddedCertFunc
;
32 NTSTATUS g_AppCertStatus
;
33 RTL_QUERY_REGISTRY_TABLE BasepAppCertTable
[2] =
36 BasepConfigureAppCertDlls
,
39 &BasepAppCertDllsList
,
46 PSAFER_REPLACE_PROCESS_THREAD_TOKENS g_SaferReplaceProcessThreadTokens
;
47 HMODULE gSaferHandle
= (HMODULE
)-1;
50 RegisterWaitForInputIdle(WaitForInputIdleType lpfnRegisterWaitForInputIdle
);
52 #define CMD_STRING L"cmd /c "
54 /* FUNCTIONS ****************************************************************/
58 StuffStdHandle(IN HANDLE ProcessHandle
,
59 IN HANDLE StandardHandle
,
63 HANDLE DuplicatedHandle
;
66 /* Duplicate the handle */
67 Status
= NtDuplicateObject(NtCurrentProcess(),
71 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
,
74 if (NT_SUCCESS(Status
))
77 NtWriteVirtualMemory(ProcessHandle
,
87 BuildSubSysCommandLine(IN LPWSTR SubsystemName
,
88 IN LPWSTR ApplicationName
,
89 IN LPWSTR CommandLine
,
90 OUT PUNICODE_STRING SubsysCommandLine
)
92 UNICODE_STRING CommandLineString
, ApplicationNameString
;
96 /* Convert to unicode strings */
97 RtlInitUnicodeString(&CommandLineString
, ApplicationName
);
98 RtlInitUnicodeString(&ApplicationNameString
, CommandLine
);
100 /* Allocate buffer for the output string */
101 Length
= CommandLineString
.MaximumLength
+ ApplicationNameString
.MaximumLength
+ 32;
102 Buffer
= RtlAllocateHeap(RtlGetProcessHeap(), 0, Length
);
103 RtlInitEmptyUnicodeString(SubsysCommandLine
, Buffer
, Length
);
106 /* Fail, no memory */
107 BaseSetLastNTError(STATUS_NO_MEMORY
);
111 /* Build the final subsystem command line */
112 RtlAppendUnicodeToString(SubsysCommandLine
, SubsystemName
);
113 RtlAppendUnicodeStringToString(SubsysCommandLine
, &CommandLineString
);
114 RtlAppendUnicodeToString(SubsysCommandLine
, L
" /C ");
115 RtlAppendUnicodeStringToString(SubsysCommandLine
, &ApplicationNameString
);
121 BasepIsImageVersionOk(IN ULONG ImageMajorVersion
,
122 IN ULONG ImageMinorVersion
)
124 /* Accept images for NT 3.1 or higher, as long as they're not newer than us */
125 return ((ImageMajorVersion
>= 3) &&
126 ((ImageMajorVersion
!= 3) ||
127 (ImageMinorVersion
>= 10)) &&
128 (ImageMajorVersion
<= SharedUserData
->NtMajorVersion
) &&
129 ((ImageMajorVersion
!= SharedUserData
->NtMajorVersion
) ||
130 (ImageMinorVersion
<= SharedUserData
->NtMinorVersion
)));
135 BasepCheckWebBladeHashes(IN HANDLE FileHandle
)
140 /* Get all the MD5 hashes */
141 Status
= RtlComputeImportTableHash(FileHandle
, Hash
, 1);
142 if (!NT_SUCCESS(Status
)) return Status
;
144 /* Depending on which suite this is, run a bsearch and block the appropriate ones */
145 if (SharedUserData
->SuiteMask
& VER_SUITE_COMPUTE_SERVER
)
147 DPRINT1("Egad! This is a ReactOS Compute Server and we should prevent you from using certain APIs...but we won't.");
149 else if (SharedUserData
->SuiteMask
& VER_SUITE_STORAGE_SERVER
)
151 DPRINT1("Gasp! This is a ReactOS Storage Server and we should prevent you from using certain APIs...but we won't.");
153 else if (SharedUserData
->SuiteMask
& VER_SUITE_BLADE
)
155 DPRINT1("Golly! This is a ReactOS Web Blade Server and we should prevent you from using certain APIs...but we won't.");
158 /* Actually, fuck it, don't block anything, we're open source */
159 return STATUS_SUCCESS
;
164 BasepSaveAppCertRegistryValue(IN PLIST_ENTRY List
,
165 IN PWCHAR ComponentName
,
168 /* Pretty much the only thing this key is used for, is malware */
170 return STATUS_NOT_IMPLEMENTED
;
175 BasepConfigureAppCertDlls(IN PWSTR ValueName
,
178 IN ULONG ValueLength
,
180 IN PVOID EntryContext
)
182 /* Add this to the certification list */
183 return BasepSaveAppCertRegistryValue(Context
, ValueName
, ValueData
);
188 BasepIsProcessAllowed(IN PCHAR ApplicationName
)
193 HMODULE TrustLibrary
;
194 PBASEP_APPCERT_ENTRY Entry
;
196 PLIST_ENTRY NextEntry
;
198 UNICODE_STRING CertKey
= RTL_CONSTANT_STRING(L
"\\Registry\\MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\AppCertDlls");
199 OBJECT_ATTRIBUTES KeyAttributes
= RTL_CONSTANT_OBJECT_ATTRIBUTES(&CertKey
, OBJ_CASE_INSENSITIVE
);
201 /* Try to initialize the certification subsystem */
202 while (!g_AppCertInitialized
)
205 Status
= STATUS_SUCCESS
;
208 /* Acquire the lock while initializing and see if we lost a race */
209 RtlEnterCriticalSection(&gcsAppCert
);
210 if (g_AppCertInitialized
) break;
212 /* On embedded, there is a special DLL */
213 if (SharedUserData
->SuiteMask
& VER_SUITE_EMBEDDEDNT
)
215 /* Allocate a buffer for the name */
216 Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
218 MAX_PATH
* sizeof(WCHAR
) +
219 sizeof(UNICODE_NULL
));
222 /* Fail if no memory */
223 Status
= STATUS_NO_MEMORY
;
227 /* Now get the system32 directory in our buffer, make sure it fits */
228 Length
= GetSystemDirectoryW(Buffer
, MAX_PATH
- sizeof("EmbdTrst.DLL"));
229 if ((Length
) && (Length
<= MAX_PATH
- sizeof("EmbdTrst.DLL")))
231 /* Add a slash if needed, and add the embedded cert DLL name */
232 if (Buffer
[Length
- 1] != '\\') Buffer
[Length
++] = '\\';
233 RtlCopyMemory(&Buffer
[Length
],
235 sizeof(L
"EmbdTrst.DLL"));
238 TrustLibrary
= LoadLibraryW(Buffer
);
241 /* And extract the special function out of it */
242 fEmbeddedCertFunc
= (PVOID
)GetProcAddress(TrustLibrary
,
243 "ImageOkToRunOnEmbeddedNT");
247 /* If we didn't get this far, set a failure code */
248 if (!fEmbeddedCertFunc
) Status
= STATUS_UNSUCCESSFUL
;
253 /* Other systems have a registry entry for this */
254 Status
= NtOpenKey(&KeyHandle
, KEY_READ
, &KeyAttributes
);
255 if (NT_SUCCESS(Status
))
257 /* Close it, we'll query it through Rtl */
260 /* Do the query, which will call a special callback */
261 Status
= RtlQueryRegistryValues(2,
266 if (Status
== 0xC0000034) Status
= STATUS_SUCCESS
;
270 /* Free any buffer if we had one */
271 if (Buffer
) RtlFreeHeap(RtlGetProcessHeap(), 0, Buffer
);
273 /* Check for errors, or a missing embedded/custom certification DLL */
274 if (!NT_SUCCESS(Status
) ||
275 (!(fEmbeddedCertFunc
) && (IsListEmpty(&BasepAppCertDllsList
))))
277 /* The subsystem is not active on this machine, so give up */
278 g_HaveAppCerts
= FALSE
;
279 g_AppCertStatus
= Status
;
283 /* We have certification DLLs active, remember this */
284 g_HaveAppCerts
= TRUE
;
287 /* We are done the initialization phase, release the lock */
288 g_AppCertInitialized
= TRUE
;
289 RtlLeaveCriticalSection(&gcsAppCert
);
292 /* If there's no certification DLLs present, return the failure code */
293 if (!g_HaveAppCerts
) return g_AppCertStatus
;
295 /* Otherwise, assume success and make sure we have *something* */
296 ASSERT(fEmbeddedCertFunc
|| !IsListEmpty(&BasepAppCertDllsList
));
297 Status
= STATUS_SUCCESS
;
299 /* If the something is an embedded certification DLL, call it and return */
300 if (fEmbeddedCertFunc
) return fEmbeddedCertFunc(ApplicationName
);
302 /* Otherwise we have custom certification DLLs, parse them */
303 NextEntry
= BasepAppCertDllsList
.Flink
;
305 while (NextEntry
!= &BasepAppCertDllsList
)
307 /* Make sure the entry has a callback */
308 Entry
= CONTAINING_RECORD(NextEntry
, BASEP_APPCERT_ENTRY
, Entry
);
309 ASSERT(Entry
->fPluginCertFunc
!= NULL
);
311 /* Call it and check if it failed */
312 Status
= Entry
->fPluginCertFunc(ApplicationName
, 1);
313 if (!NT_SUCCESS(Status
)) CertFlag
= 3;
316 NextEntry
= NextEntry
->Flink
;
319 /* Now loop them again */
320 NextEntry
= BasepAppCertDllsList
.Flink
;
321 while (NextEntry
!= &BasepAppCertDllsList
)
323 /* Make sure the entry has a callback */
324 Entry
= CONTAINING_RECORD(NextEntry
, BASEP_APPCERT_ENTRY
, Entry
);
325 ASSERT(Entry
->fPluginCertFunc
!= NULL
);
327 /* Call it, this time with the flag from the loop above */
328 Status
= Entry
->fPluginCertFunc(ApplicationName
, CertFlag
);
331 /* All done, return the status */
337 BasepReplaceProcessThreadTokens(IN HANDLE TokenHandle
,
338 IN HANDLE ProcessHandle
,
339 IN HANDLE ThreadHandle
)
342 ANSI_STRING SaferiReplaceProcessThreadTokens
= RTL_CONSTANT_STRING("SaferiReplaceProcessThreadTokens");
344 /* Enter the application certification lock */
345 RtlEnterCriticalSection(&gcsAppCert
);
347 /* Check if we already know the function */
348 if (g_SaferReplaceProcessThreadTokens
)
351 Status
= g_SaferReplaceProcessThreadTokens(TokenHandle
,
359 /* Check if the app certification DLL isn't loaded */
360 if (!(gSaferHandle
) ||
361 (gSaferHandle
== (HMODULE
)-1) ||
362 (gSaferHandle
== (HMODULE
)-2))
364 /* Then we can't call the function */
365 Status
= STATUS_ENTRYPOINT_NOT_FOUND
;
369 /* We have the DLL, find the address of the Safer function */
370 Status
= LdrGetProcedureAddress(gSaferHandle
,
371 &SaferiReplaceProcessThreadTokens
,
373 (PVOID
*)&g_SaferReplaceProcessThreadTokens
);
374 if (NT_SUCCESS(Status
))
376 /* Found it, now call it */
377 Status
= g_SaferReplaceProcessThreadTokens(TokenHandle
,
385 /* We couldn't find it, so this must be an unsupported DLL */
386 LdrUnloadDll(gSaferHandle
);
388 Status
= STATUS_ENTRYPOINT_NOT_FOUND
;
393 /* Release the lock and return the result */
394 RtlLeaveCriticalSection(&gcsAppCert
);
400 BasepSxsCloseHandles(IN PBASE_MSG_SXS_HANDLES Handles
)
405 ASSERT(Handles
!= NULL
);
406 ASSERT(Handles
->Process
== NULL
|| Handles
->Process
== NtCurrentProcess());
408 /* Close the file handle */
411 Status
= NtClose(Handles
->File
);
412 ASSERT(NT_SUCCESS(Status
));
415 /* Close the section handle */
416 if (Handles
->Section
)
418 Status
= NtClose(Handles
->Section
);
419 ASSERT(NT_SUCCESS(Status
));
422 /* Unmap the section view */
423 if (Handles
->ViewBase
.QuadPart
)
425 Status
= NtUnmapViewOfSection(NtCurrentProcess(),
426 (PVOID
)Handles
->ViewBase
.LowPart
);
427 ASSERT(NT_SUCCESS(Status
));
432 LONG
BaseExceptionFilter(EXCEPTION_POINTERS
*ExceptionInfo
)
434 LONG ExceptionDisposition
= EXCEPTION_EXECUTE_HANDLER
;
435 LPTOP_LEVEL_EXCEPTION_FILTER RealFilter
;
436 RealFilter
= RtlDecodePointer(GlobalTopLevelExceptionFilter
);
438 if (RealFilter
!= NULL
)
442 ExceptionDisposition
= RealFilter(ExceptionInfo
);
444 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
449 if ((ExceptionDisposition
== EXCEPTION_CONTINUE_SEARCH
|| ExceptionDisposition
== EXCEPTION_EXECUTE_HANDLER
) &&
450 RealFilter
!= UnhandledExceptionFilter
)
452 ExceptionDisposition
= UnhandledExceptionFilter(ExceptionInfo
);
455 return ExceptionDisposition
;
460 BaseProcessStartup(PPROCESS_START_ROUTINE lpStartAddress
)
462 DPRINT("BaseProcessStartup(..) - setting up exception frame.\n");
466 /* Set our Start Address */
467 NtSetInformationThread(NtCurrentThread(),
468 ThreadQuerySetWin32StartAddress
,
470 sizeof(PPROCESS_START_ROUTINE
));
472 /* Call the Start Routine */
473 ExitThread(lpStartAddress());
475 _SEH2_EXCEPT(BaseExceptionFilter(_SEH2_GetExceptionInformation()))
477 /* Get the Exit code from the SEH Handler */
478 if (!BaseRunningInServerProcess
)
480 /* Kill the whole process, usually */
481 ExitProcess(_SEH2_GetExceptionCode());
485 /* If running inside CSRSS, kill just this thread */
486 ExitThread(_SEH2_GetExceptionCode());
494 BasepNotifyCsrOfThread(IN HANDLE ThreadHandle
,
495 IN PCLIENT_ID ClientId
)
497 ULONG Request
= CREATE_THREAD
;
498 CSR_API_MESSAGE CsrRequest
;
501 DPRINT("BasepNotifyCsrOfThread: Thread: %lx, Handle %lx\n",
502 ClientId
->UniqueThread
, ThreadHandle
);
504 /* Fill out the request */
505 CsrRequest
.Data
.CreateThreadRequest
.ClientId
= *ClientId
;
506 CsrRequest
.Data
.CreateThreadRequest
.ThreadHandle
= ThreadHandle
;
509 Status
= CsrClientCallServer(&CsrRequest
,
511 MAKE_CSR_API(Request
, CSR_NATIVE
),
512 sizeof(CSR_API_MESSAGE
));
513 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
515 DPRINT1("Failed to tell csrss about new thread: %lx %lx\n", Status
, CsrRequest
.Status
);
516 return CsrRequest
.Status
;
520 return STATUS_SUCCESS
;
524 * Creates the first Thread in a Proces
528 BasepCreateFirstThread(HANDLE ProcessHandle
,
529 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
530 PSECTION_IMAGE_INFORMATION SectionImageInfo
,
532 BOOLEAN InheritHandles
,
533 DWORD dwCreationFlags
)
535 OBJECT_ATTRIBUTES LocalObjectAttributes
;
536 POBJECT_ATTRIBUTES ObjectAttributes
;
538 INITIAL_TEB InitialTeb
;
541 ULONG Request
= CREATE_PROCESS
;
542 CSR_API_MESSAGE CsrRequest
;
543 DPRINT("BasepCreateFirstThread. hProcess: %lx\n", ProcessHandle
);
545 /* Create the Thread's Stack */
546 BaseCreateStack(ProcessHandle
,
547 SectionImageInfo
->MaximumStackSize
,
548 SectionImageInfo
->CommittedStackSize
,
551 /* Create the Thread's Context */
552 BaseInitializeContext(&Context
,
554 SectionImageInfo
->TransferAddress
,
555 InitialTeb
.StackBase
,
558 /* Convert the thread attributes */
559 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
563 /* Create the Kernel Thread Object */
564 Status
= NtCreateThread(&hThread
,
572 if (!NT_SUCCESS(Status
))
577 /* Fill out the request to notify CSRSS */
578 CsrRequest
.Data
.CreateProcessRequest
.ClientId
= *ClientId
;
579 CsrRequest
.Data
.CreateProcessRequest
.ProcessHandle
= ProcessHandle
;
580 CsrRequest
.Data
.CreateProcessRequest
.ThreadHandle
= hThread
;
581 CsrRequest
.Data
.CreateProcessRequest
.CreationFlags
= dwCreationFlags
;
582 CsrRequest
.Data
.CreateProcessRequest
.bInheritHandles
= InheritHandles
;
585 Status
= CsrClientCallServer(&CsrRequest
,
587 MAKE_CSR_API(Request
, CSR_NATIVE
),
588 sizeof(CSR_API_MESSAGE
));
589 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
591 DPRINT1("Failed to tell csrss about new process: %lx %lx\n", Status
, CsrRequest
.Status
);
600 * Converts ANSI to Unicode Environment
604 BasepConvertUnicodeEnvironment(OUT SIZE_T
* EnvSize
,
605 IN PVOID lpEnvironment
)
609 UNICODE_STRING UnicodeEnv
;
612 DPRINT("BasepConvertUnicodeEnvironment\n");
614 /* Scan the environment to calculate its Unicode size */
615 AnsiEnv
.Buffer
= pcScan
= (PCHAR
)lpEnvironment
;
618 pcScan
+= strlen(pcScan
) + 1;
621 /* Create our ANSI String */
622 if (pcScan
== (PCHAR
)lpEnvironment
)
624 AnsiEnv
.Length
= 2 * sizeof(CHAR
);
629 AnsiEnv
.Length
= (USHORT
)((ULONG_PTR
)pcScan
- (ULONG_PTR
)lpEnvironment
+ sizeof(CHAR
));
631 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ 1;
633 /* Allocate memory for the Unicode Environment */
634 UnicodeEnv
.Buffer
= NULL
;
635 *EnvSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
636 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
637 (PVOID
)&UnicodeEnv
.Buffer
,
643 if (!NT_SUCCESS(Status
))
645 SetLastError(Status
);
650 /* Use the allocated size */
651 UnicodeEnv
.MaximumLength
= (USHORT
)*EnvSize
;
654 RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
655 return UnicodeEnv
.Buffer
;
659 * Converts a Win32 Priority Class to NT
663 BasepConvertPriorityClass(IN ULONG dwCreationFlags
)
667 if(dwCreationFlags
& IDLE_PRIORITY_CLASS
)
669 ReturnClass
= PROCESS_PRIORITY_CLASS_IDLE
;
671 else if(dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
673 ReturnClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
675 else if(dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
677 ReturnClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
679 else if(dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
681 ReturnClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
683 else if(dwCreationFlags
& HIGH_PRIORITY_CLASS
)
685 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
687 else if(dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
689 /* Check for Privilege First */
690 if (BasepIsRealtimeAllowed(TRUE
))
692 ReturnClass
= PROCESS_PRIORITY_CLASS_REALTIME
;
696 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
701 ReturnClass
= PROCESS_PRIORITY_CLASS_INVALID
;
708 * Duplicates a standard handle and writes it where requested.
712 BasepDuplicateAndWriteHandle(IN HANDLE ProcessHandle
,
713 IN HANDLE StandardHandle
,
717 HANDLE DuplicatedHandle
;
720 DPRINT("BasepDuplicateAndWriteHandle. hProcess: %lx, Handle: %lx,"
721 "Address: %p\n", ProcessHandle
, StandardHandle
, Address
);
723 /* Don't touch Console Handles */
724 if (IsConsoleHandle(StandardHandle
)) return;
726 /* Duplicate the handle */
727 Status
= NtDuplicateObject(NtCurrentProcess(),
731 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
,
734 if (NT_SUCCESS(Status
))
737 NtWriteVirtualMemory(ProcessHandle
,
747 BasePushProcessParameters(IN ULONG ParameterFlags
,
748 IN HANDLE ProcessHandle
,
750 IN LPCWSTR ApplicationPathName
,
751 IN LPWSTR lpCurrentDirectory
,
752 IN LPWSTR lpCommandLine
,
753 IN LPVOID lpEnvironment
,
754 IN LPSTARTUPINFOW StartupInfo
,
755 IN DWORD CreationFlags
,
756 IN BOOL InheritHandles
,
757 IN ULONG ImageSubsystem
,
758 IN PVOID AppCompatData
,
759 IN ULONG AppCompatDataSize
)
761 WCHAR FullPath
[MAX_PATH
+ 5];
762 PWCHAR Remaining
, DllPathString
, ScanChar
;
763 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
, RemoteParameters
;
764 PVOID RemoteAppCompatData
;
765 UNICODE_STRING DllPath
, ImageName
, CommandLine
, CurrentDirectory
;
766 UNICODE_STRING Desktop
, Shell
, Runtime
, Title
;
770 BOOLEAN HavePebLock
= FALSE
, Result
;
771 PPEB Peb
= NtCurrentPeb();
773 /* Get the full path name */
774 Size
= GetFullPathNameW(ApplicationPathName
,
778 if ((Size
) && (Size
<= (MAX_PATH
+ 4)))
780 /* Get the DLL Path */
781 DllPathString
= BaseComputeProcessDllPath(FullPath
, lpEnvironment
);
785 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
789 /* Initialize Strings */
790 RtlInitUnicodeString(&DllPath
, DllPathString
);
791 RtlInitUnicodeString(&ImageName
, FullPath
);
795 /* Couldn't get the path name. Just take the original path */
796 DllPathString
= BaseComputeProcessDllPath((LPWSTR
)ApplicationPathName
,
801 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
805 /* Initialize Strings */
806 RtlInitUnicodeString(&DllPath
, DllPathString
);
807 RtlInitUnicodeString(&ImageName
, ApplicationPathName
);
810 /* Initialize Strings */
811 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
812 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
814 /* Initialize more Strings from the Startup Info */
815 if (StartupInfo
->lpDesktop
)
817 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
821 RtlInitUnicodeString(&Desktop
, L
"");
823 if (StartupInfo
->lpReserved
)
825 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
829 RtlInitUnicodeString(&Shell
, L
"");
831 if (StartupInfo
->lpTitle
)
833 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
837 RtlInitUnicodeString(&Title
, ApplicationPathName
);
840 /* This one is special because the length can differ */
841 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
842 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
844 /* Enforce no app compat data if the pointer was NULL */
845 if (!AppCompatData
) AppCompatDataSize
= 0;
847 /* Create the Parameter Block */
848 ProcessParameters
= NULL
;
849 Status
= RtlCreateProcessParameters(&ProcessParameters
,
853 &CurrentDirectory
: NULL
,
860 if (!NT_SUCCESS(Status
)) goto FailPath
;
862 /* Clear the current directory handle if not inheriting */
863 if (!InheritHandles
) ProcessParameters
->CurrentDirectory
.Handle
= NULL
;
865 /* Check if the user passed in an environment */
868 /* We should've made it part of the parameters block, enforce this */
869 ASSERT(ProcessParameters
->Environment
== lpEnvironment
);
870 lpEnvironment
= ProcessParameters
->Environment
;
874 /* The user did not, so use the one from the current PEB */
877 lpEnvironment
= Peb
->ProcessParameters
->Environment
;
880 /* Save pointer and start lookup */
881 ScanChar
= lpEnvironment
;
884 /* Find the environment size */
885 while ((ScanChar
[0]) || (ScanChar
[1])) ++ScanChar
;
886 ScanChar
+= (2 * sizeof(UNICODE_NULL
));
887 EnviroSize
= (ULONG_PTR
)ScanChar
- (ULONG_PTR
)lpEnvironment
;
889 /* Allocate and Initialize new Environment Block */
891 ProcessParameters
->Environment
= NULL
;
892 Status
= NtAllocateVirtualMemory(ProcessHandle
,
893 (PVOID
*)&ProcessParameters
->Environment
,
898 if (!NT_SUCCESS(Status
)) goto FailPath
;
900 /* Write the Environment Block */
901 Status
= NtWriteVirtualMemory(ProcessHandle
,
902 ProcessParameters
->Environment
,
907 /* No longer need the PEB lock anymore */
915 /* Check if the write failed */
916 if (!NT_SUCCESS(Status
)) goto FailPath
;
919 /* Write new parameters */
920 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
921 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
922 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
923 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
924 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
925 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
926 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
927 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
928 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
930 /* Write the handles only if we have to */
931 if (StartupInfo
->dwFlags
&
932 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
934 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
935 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
936 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
939 /* Use Special Flags for ConDllInitialize in Kernel32 */
940 if (CreationFlags
& DETACHED_PROCESS
)
942 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
944 else if (CreationFlags
& CREATE_NO_WINDOW
)
946 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
948 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
950 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
954 /* Inherit our Console Handle */
955 ProcessParameters
->ConsoleHandle
= Peb
->ProcessParameters
->ConsoleHandle
;
957 /* Make sure that the shell isn't trampling on our handles first */
958 if (!(StartupInfo
->dwFlags
&
959 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
961 /* Copy the handle if we are inheriting or if it's a console handle */
962 if ((InheritHandles
) ||
963 (IsConsoleHandle(Peb
->ProcessParameters
->StandardInput
)))
965 ProcessParameters
->StandardInput
= Peb
->ProcessParameters
->StandardInput
;
967 if ((InheritHandles
) ||
968 (IsConsoleHandle(Peb
->ProcessParameters
->StandardOutput
)))
970 ProcessParameters
->StandardOutput
= Peb
->ProcessParameters
->StandardOutput
;
972 if ((InheritHandles
) ||
973 (IsConsoleHandle(Peb
->ProcessParameters
->StandardError
)))
975 ProcessParameters
->StandardError
= Peb
->ProcessParameters
->StandardError
;
980 /* Also set the Console Flag */
981 if ((CreationFlags
& CREATE_NEW_PROCESS_GROUP
) &&
982 (!(CreationFlags
& CREATE_NEW_CONSOLE
)))
984 ProcessParameters
->ConsoleFlags
= 1;
987 /* See if the first 1MB should be reserved */
988 if (ParameterFlags
& 1)
990 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_RESERVE_1MB
;
993 /* See if the first 16MB should be reserved */
994 if (ParameterFlags
& 2)
996 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_RESERVE_16MB
;
999 /* Allocate memory for the parameter block */
1000 Size
= ProcessParameters
->Length
;
1001 RemoteParameters
= NULL
;
1002 Status
= NtAllocateVirtualMemory(ProcessHandle
,
1003 (PVOID
*)&RemoteParameters
,
1008 if (!NT_SUCCESS(Status
)) goto FailPath
;
1010 /* Set the allocated size */
1011 ProcessParameters
->MaximumLength
= Size
;
1013 /* Handle some Parameter Flags */
1014 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
1015 RTL_USER_PROCESS_PARAMETERS_PROFILE_USER
: 0;
1016 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
1017 RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL
: 0;
1018 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
1019 RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER
: 0;
1020 ProcessParameters
->Flags
|= (Peb
->ProcessParameters
->Flags
&
1021 RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_CHECKS
);
1023 /* Write the Parameter Block */
1024 Status
= NtWriteVirtualMemory(ProcessHandle
,
1027 ProcessParameters
->Length
,
1029 if (!NT_SUCCESS(Status
)) goto FailPath
;
1031 /* Write the PEB Pointer */
1032 Status
= NtWriteVirtualMemory(ProcessHandle
,
1033 &RemotePeb
->ProcessParameters
,
1037 if (!NT_SUCCESS(Status
)) goto FailPath
;
1039 /* Check if there's any app compat data to write */
1040 RemoteAppCompatData
= NULL
;
1043 /* Allocate some space for the application compatibility data */
1044 Size
= AppCompatDataSize
;
1045 Status
= NtAllocateVirtualMemory(ProcessHandle
,
1046 &RemoteAppCompatData
,
1051 if (!NT_SUCCESS(Status
)) goto FailPath
;
1053 /* Write the application compatibility data */
1054 Status
= NtWriteVirtualMemory(ProcessHandle
,
1055 RemoteAppCompatData
,
1059 if (!NT_SUCCESS(Status
)) goto FailPath
;
1062 /* Write the PEB Pointer to the app compat data (might be NULL) */
1063 Status
= NtWriteVirtualMemory(ProcessHandle
,
1064 &RemotePeb
->pShimData
,
1065 &RemoteAppCompatData
,
1068 if (!NT_SUCCESS(Status
)) goto FailPath
;
1070 /* Now write Peb->ImageSubSystem */
1073 NtWriteVirtualMemory(ProcessHandle
,
1074 &RemotePeb
->ImageSubsystem
,
1076 sizeof(ImageSubsystem
),
1085 if (HavePebLock
) RtlReleasePebLock();
1086 RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath
.Buffer
);
1087 if (ProcessParameters
) RtlDestroyProcessParameters(ProcessParameters
);
1090 DPRINT1("Failure to create proecss parameters: %lx\n", Status
);
1091 BaseSetLastNTError(Status
);
1098 InitCommandLines(VOID
)
1102 /* Read the UNICODE_STRING from the PEB */
1103 BaseUnicodeCommandLine
= NtCurrentPeb()->ProcessParameters
->CommandLine
;
1105 /* Convert to ANSI_STRING for the *A callers */
1106 Status
= RtlUnicodeStringToAnsiString(&BaseAnsiCommandLine
,
1107 &BaseUnicodeCommandLine
,
1109 if (!NT_SUCCESS(Status
)) RtlInitEmptyAnsiString(&BaseAnsiCommandLine
, 0, 0);
1112 /* PUBLIC FUNCTIONS ***********************************************************/
1119 GetProcessAffinityMask(IN HANDLE hProcess
,
1120 OUT PDWORD_PTR lpProcessAffinityMask
,
1121 OUT PDWORD_PTR lpSystemAffinityMask
)
1123 PROCESS_BASIC_INFORMATION ProcessInfo
;
1126 /* Query information on the process from the kernel */
1127 Status
= NtQueryInformationProcess(hProcess
,
1128 ProcessBasicInformation
,
1129 (PVOID
)&ProcessInfo
,
1130 sizeof(PROCESS_BASIC_INFORMATION
),
1132 if (!NT_SUCCESS(Status
))
1135 BaseSetLastNTError(Status
);
1139 /* Copy the affinity mask, and get the system one from our shared data */
1140 *lpProcessAffinityMask
= (DWORD
)ProcessInfo
.AffinityMask
;
1141 *lpSystemAffinityMask
= (DWORD
)BaseStaticServerData
->SysInfo
.ActiveProcessorsAffinityMask
;
1150 SetProcessAffinityMask(IN HANDLE hProcess
,
1151 IN DWORD_PTR dwProcessAffinityMask
)
1155 /* Directly set the affinity mask */
1156 Status
= NtSetInformationProcess(hProcess
,
1157 ProcessAffinityMask
,
1158 (PVOID
)&dwProcessAffinityMask
,
1160 if (!NT_SUCCESS(Status
))
1162 /* Handle failure */
1163 BaseSetLastNTError(Status
);
1167 /* Everything was ok */
1176 GetProcessShutdownParameters(OUT LPDWORD lpdwLevel
,
1177 OUT LPDWORD lpdwFlags
)
1179 CSR_API_MESSAGE CsrRequest
;
1182 /* Ask CSRSS for shutdown information */
1183 Status
= CsrClientCallServer(&CsrRequest
,
1185 MAKE_CSR_API(GET_SHUTDOWN_PARAMETERS
, CSR_NATIVE
),
1186 sizeof(CSR_API_MESSAGE
));
1187 if (!(NT_SUCCESS(Status
)) || !(NT_SUCCESS(CsrRequest
.Status
)))
1189 /* Return the failure from CSRSS */
1190 BaseSetLastNTError(CsrRequest
.Status
);
1194 /* Get the data out of the LCP reply */
1195 *lpdwLevel
= CsrRequest
.Data
.GetShutdownParametersRequest
.Level
;
1196 *lpdwFlags
= CsrRequest
.Data
.GetShutdownParametersRequest
.Flags
;
1205 SetProcessShutdownParameters(IN DWORD dwLevel
,
1208 CSR_API_MESSAGE CsrRequest
;
1211 /* Write the data into the CSRSS request and send it */
1212 CsrRequest
.Data
.SetShutdownParametersRequest
.Level
= dwLevel
;
1213 CsrRequest
.Data
.SetShutdownParametersRequest
.Flags
= dwFlags
;
1214 Status
= CsrClientCallServer(&CsrRequest
,
1216 MAKE_CSR_API(SET_SHUTDOWN_PARAMETERS
, CSR_NATIVE
),
1217 sizeof(CSR_API_MESSAGE
));
1218 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
1220 /* Return the failure from CSRSS */
1221 BaseSetLastNTError(CsrRequest
.Status
);
1234 GetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1235 OUT PSIZE_T lpMinimumWorkingSetSize
,
1236 OUT PSIZE_T lpMaximumWorkingSetSize
,
1239 QUOTA_LIMITS_EX QuotaLimits
;
1242 /* Query the kernel about this */
1243 Status
= NtQueryInformationProcess(hProcess
,
1246 sizeof(QUOTA_LIMITS_EX
),
1248 if (!NT_SUCCESS(Status
))
1251 BaseSetLastNTError(Status
);
1255 /* Copy the quota information out */
1256 *lpMinimumWorkingSetSize
= QuotaLimits
.MinimumWorkingSetSize
;
1257 *lpMaximumWorkingSetSize
= QuotaLimits
.MaximumWorkingSetSize
;
1258 *Flags
= QuotaLimits
.Flags
;
1267 GetProcessWorkingSetSize(IN HANDLE hProcess
,
1268 OUT PSIZE_T lpMinimumWorkingSetSize
,
1269 OUT PSIZE_T lpMaximumWorkingSetSize
)
1272 return GetProcessWorkingSetSizeEx(hProcess
,
1273 lpMinimumWorkingSetSize
,
1274 lpMaximumWorkingSetSize
,
1283 SetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1284 IN SIZE_T dwMinimumWorkingSetSize
,
1285 IN SIZE_T dwMaximumWorkingSetSize
,
1288 QUOTA_LIMITS_EX QuotaLimits
;
1289 NTSTATUS Status
, ReturnStatus
;
1292 ULONG Privilege
= SE_INC_BASE_PRIORITY_PRIVILEGE
;
1294 /* Zero out the input structure */
1295 RtlZeroMemory(&QuotaLimits
, sizeof(QuotaLimits
));
1297 /* Check if the caller sent any limits */
1298 if ((dwMinimumWorkingSetSize
) && (dwMaximumWorkingSetSize
))
1300 /* Write the quota information */
1301 QuotaLimits
.MinimumWorkingSetSize
= dwMinimumWorkingSetSize
;
1302 QuotaLimits
.MaximumWorkingSetSize
= dwMaximumWorkingSetSize
;
1303 QuotaLimits
.Flags
= Flags
;
1305 /* Acquire the required privilege */
1306 Status
= RtlAcquirePrivilege(&Privilege
, 1, 0, &State
);
1308 /* Request the new quotas */
1309 ReturnStatus
= NtSetInformationProcess(hProcess
,
1312 sizeof(QuotaLimits
));
1313 Result
= NT_SUCCESS(ReturnStatus
);
1314 if (NT_SUCCESS(Status
))
1316 /* Release the privilege and set succes code */
1317 ASSERT(State
!= NULL
);
1318 RtlReleasePrivilege(State
);
1324 /* No limits, fail the call */
1325 ReturnStatus
= STATUS_INVALID_PARAMETER
;
1329 /* Return result code, set error code if this was a failure */
1330 if (!Result
) BaseSetLastNTError(ReturnStatus
);
1339 SetProcessWorkingSetSize(IN HANDLE hProcess
,
1340 IN SIZE_T dwMinimumWorkingSetSize
,
1341 IN SIZE_T dwMaximumWorkingSetSize
)
1343 /* Call the newer API */
1344 return SetProcessWorkingSetSizeEx(hProcess
,
1345 dwMinimumWorkingSetSize
,
1346 dwMaximumWorkingSetSize
,
1355 GetProcessTimes(IN HANDLE hProcess
,
1356 IN LPFILETIME lpCreationTime
,
1357 IN LPFILETIME lpExitTime
,
1358 IN LPFILETIME lpKernelTime
,
1359 IN LPFILETIME lpUserTime
)
1361 KERNEL_USER_TIMES Kut
;
1364 /* Query the times */
1365 Status
= NtQueryInformationProcess(hProcess
,
1370 if (!NT_SUCCESS(Status
))
1372 /* Handle failure */
1373 BaseSetLastNTError(Status
);
1377 /* Copy all the times and return success */
1378 lpCreationTime
->dwLowDateTime
= Kut
.CreateTime
.u
.LowPart
;
1379 lpCreationTime
->dwHighDateTime
= Kut
.CreateTime
.u
.HighPart
;
1380 lpExitTime
->dwLowDateTime
= Kut
.ExitTime
.u
.LowPart
;
1381 lpExitTime
->dwHighDateTime
= Kut
.ExitTime
.u
.HighPart
;
1382 lpKernelTime
->dwLowDateTime
= Kut
.KernelTime
.u
.LowPart
;
1383 lpKernelTime
->dwHighDateTime
= Kut
.KernelTime
.u
.HighPart
;
1384 lpUserTime
->dwLowDateTime
= Kut
.UserTime
.u
.LowPart
;
1385 lpUserTime
->dwHighDateTime
= Kut
.UserTime
.u
.HighPart
;
1394 GetCurrentProcess(VOID
)
1396 return (HANDLE
)NtCurrentProcess();
1404 GetCurrentThread(VOID
)
1406 return (HANDLE
)NtCurrentThread();
1414 GetCurrentProcessId(VOID
)
1416 return HandleToUlong(NtCurrentTeb()->ClientId
.UniqueProcess
);
1424 GetExitCodeProcess(IN HANDLE hProcess
,
1425 IN LPDWORD lpExitCode
)
1427 PROCESS_BASIC_INFORMATION ProcessBasic
;
1430 /* Ask the kernel */
1431 Status
= NtQueryInformationProcess(hProcess
,
1432 ProcessBasicInformation
,
1434 sizeof(PROCESS_BASIC_INFORMATION
),
1436 if (!NT_SUCCESS(Status
))
1438 /* We failed, was this because this is a VDM process? */
1439 if (BaseCheckForVDM(hProcess
, lpExitCode
) == TRUE
) return TRUE
;
1441 /* Not a VDM process, fail the call */
1442 BaseSetLastNTError(Status
);
1446 /* Succes case, return the exit code */
1447 *lpExitCode
= (DWORD
)ProcessBasic
.ExitStatus
;
1456 GetProcessId(IN HANDLE Process
)
1458 PROCESS_BASIC_INFORMATION ProcessBasic
;
1461 /* Query the kernel */
1462 Status
= NtQueryInformationProcess(Process
,
1463 ProcessBasicInformation
,
1465 sizeof(PROCESS_BASIC_INFORMATION
),
1467 if (!NT_SUCCESS(Status
))
1469 /* Handle failure */
1470 BaseSetLastNTError(Status
);
1474 /* Return the PID */
1475 return (DWORD
)ProcessBasic
.UniqueProcessId
;
1483 OpenProcess(IN DWORD dwDesiredAccess
,
1484 IN BOOL bInheritHandle
,
1485 IN DWORD dwProcessId
)
1488 HANDLE ProcessHandle
;
1489 OBJECT_ATTRIBUTES ObjectAttributes
;
1492 /* Setup the input client ID structure */
1493 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
1494 ClientId
.UniqueThread
= 0;
1496 /* This is needed just to define the inheritance flags */
1497 InitializeObjectAttributes(&ObjectAttributes
,
1499 (bInheritHandle
? OBJ_INHERIT
: 0),
1503 /* Now try to open the process */
1504 Status
= NtOpenProcess(&ProcessHandle
,
1508 if (!NT_SUCCESS(Status
))
1510 /* Handle failure */
1511 BaseSetLastNTError(Status
);
1515 /* Otherwise return a handle to the process */
1516 return ProcessHandle
;
1524 RegisterWaitForInputIdle(IN WaitForInputIdleType lpfnRegisterWaitForInputIdle
)
1526 /* Write the global function pointer */
1527 UserWaitForInputIdleRoutine
= lpfnRegisterWaitForInputIdle
;
1535 GetStartupInfoW(IN LPSTARTUPINFOW lpStartupInfo
)
1537 PRTL_USER_PROCESS_PARAMETERS Params
;
1539 /* Get the process parameters */
1540 Params
= NtCurrentPeb()->ProcessParameters
;
1542 /* Copy the data out of there */
1543 lpStartupInfo
->cb
= sizeof(STARTUPINFOW
);
1544 lpStartupInfo
->lpReserved
= Params
->ShellInfo
.Buffer
;
1545 lpStartupInfo
->lpDesktop
= Params
->DesktopInfo
.Buffer
;
1546 lpStartupInfo
->lpTitle
= Params
->WindowTitle
.Buffer
;
1547 lpStartupInfo
->dwX
= Params
->StartingX
;
1548 lpStartupInfo
->dwY
= Params
->StartingY
;
1549 lpStartupInfo
->dwXSize
= Params
->CountX
;
1550 lpStartupInfo
->dwYSize
= Params
->CountY
;
1551 lpStartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1552 lpStartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1553 lpStartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1554 lpStartupInfo
->dwFlags
= Params
->WindowFlags
;
1555 lpStartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1556 lpStartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1557 lpStartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1559 /* Check if the standard handles are being used for other features */
1560 if (lpStartupInfo
->dwFlags
& (STARTF_USESTDHANDLES
|
1562 STARTF_SHELLPRIVATE
))
1564 /* These are, so copy the standard handles too */
1565 lpStartupInfo
->hStdInput
= Params
->StandardInput
;
1566 lpStartupInfo
->hStdOutput
= Params
->StandardOutput
;
1567 lpStartupInfo
->hStdError
= Params
->StandardError
;
1576 GetStartupInfoA(IN LPSTARTUPINFOA lpStartupInfo
)
1578 PRTL_USER_PROCESS_PARAMETERS Params
;
1579 ANSI_STRING TitleString
, ShellString
, DesktopString
;
1580 LPSTARTUPINFOA StartupInfo
;
1583 /* Get the cached information as well as the PEB parameters */
1584 StartupInfo
= BaseAnsiStartupInfo
;
1585 Params
= NtCurrentPeb()->ProcessParameters
;
1587 /* Check if this is the first time we have to get the cached version */
1588 while (!StartupInfo
)
1590 /* Create new ANSI startup info */
1591 StartupInfo
= RtlAllocateHeap(RtlGetProcessHeap(),
1593 sizeof(*StartupInfo
));
1596 /* Zero out string pointers in case we fail to create them */
1597 StartupInfo
->lpReserved
= 0;
1598 StartupInfo
->lpDesktop
= 0;
1599 StartupInfo
->lpTitle
= 0;
1602 StartupInfo
->cb
= sizeof(*StartupInfo
);
1604 /* Copy what's already stored in the PEB */
1605 StartupInfo
->dwX
= Params
->StartingX
;
1606 StartupInfo
->dwY
= Params
->StartingY
;
1607 StartupInfo
->dwXSize
= Params
->CountX
;
1608 StartupInfo
->dwYSize
= Params
->CountY
;
1609 StartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1610 StartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1611 StartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1612 StartupInfo
->dwFlags
= Params
->WindowFlags
;
1613 StartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1614 StartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1615 StartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1616 StartupInfo
->hStdInput
= Params
->StandardInput
;
1617 StartupInfo
->hStdOutput
= Params
->StandardOutput
;
1618 StartupInfo
->hStdError
= Params
->StandardError
;
1620 /* Copy shell info string */
1621 Status
= RtlUnicodeStringToAnsiString(&ShellString
,
1624 if (NT_SUCCESS(Status
))
1627 StartupInfo
->lpReserved
= ShellString
.Buffer
;
1629 /* Copy desktop info string */
1630 Status
= RtlUnicodeStringToAnsiString(&DesktopString
,
1631 &Params
->DesktopInfo
,
1633 if (NT_SUCCESS(Status
))
1636 StartupInfo
->lpDesktop
= DesktopString
.Buffer
;
1638 /* Copy window title string */
1639 Status
= RtlUnicodeStringToAnsiString(&TitleString
,
1640 &Params
->WindowTitle
,
1642 if (NT_SUCCESS(Status
))
1645 StartupInfo
->lpTitle
= TitleString
.Buffer
;
1647 /* We finished with the ANSI version, try to cache it */
1648 if (!InterlockedCompareExchangePointer(&BaseAnsiStartupInfo
,
1652 /* We were the first thread through, use the data */
1656 /* Someone beat us to it, use their data instead */
1657 StartupInfo
= BaseAnsiStartupInfo
;
1658 Status
= STATUS_SUCCESS
;
1660 /* We're going to free our own stuff, but not raise */
1661 RtlFreeAnsiString(&TitleString
);
1663 RtlFreeAnsiString(&DesktopString
);
1665 RtlFreeAnsiString(&ShellString
);
1667 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
);
1671 /* No memory, fail */
1672 Status
= STATUS_NO_MEMORY
;
1675 /* Raise an error unless we got here due to the race condition */
1676 if (!NT_SUCCESS(Status
)) RtlRaiseStatus(Status
);
1679 /* Now copy from the cached ANSI version */
1680 lpStartupInfo
->cb
= StartupInfo
->cb
;
1681 lpStartupInfo
->lpReserved
= StartupInfo
->lpReserved
;
1682 lpStartupInfo
->lpDesktop
= StartupInfo
->lpDesktop
;
1683 lpStartupInfo
->lpTitle
= StartupInfo
->lpTitle
;
1684 lpStartupInfo
->dwX
= StartupInfo
->dwX
;
1685 lpStartupInfo
->dwY
= StartupInfo
->dwY
;
1686 lpStartupInfo
->dwXSize
= StartupInfo
->dwXSize
;
1687 lpStartupInfo
->dwYSize
= StartupInfo
->dwYSize
;
1688 lpStartupInfo
->dwXCountChars
= StartupInfo
->dwXCountChars
;
1689 lpStartupInfo
->dwYCountChars
= StartupInfo
->dwYCountChars
;
1690 lpStartupInfo
->dwFillAttribute
= StartupInfo
->dwFillAttribute
;
1691 lpStartupInfo
->dwFlags
= StartupInfo
->dwFlags
;
1692 lpStartupInfo
->wShowWindow
= StartupInfo
->wShowWindow
;
1693 lpStartupInfo
->cbReserved2
= StartupInfo
->cbReserved2
;
1694 lpStartupInfo
->lpReserved2
= StartupInfo
->lpReserved2
;
1696 /* Check if the shell is hijacking the handles for other features */
1697 if (lpStartupInfo
->dwFlags
&
1698 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
1700 /* It isn't, so we can return the raw values */
1701 lpStartupInfo
->hStdInput
= StartupInfo
->hStdInput
;
1702 lpStartupInfo
->hStdOutput
= StartupInfo
->hStdOutput
;
1703 lpStartupInfo
->hStdError
= StartupInfo
->hStdError
;
1707 /* It is, so make sure nobody uses these as console handles */
1708 lpStartupInfo
->hStdInput
= INVALID_HANDLE_VALUE
;
1709 lpStartupInfo
->hStdOutput
= INVALID_HANDLE_VALUE
;
1710 lpStartupInfo
->hStdError
= INVALID_HANDLE_VALUE
;
1719 FlushInstructionCache(IN HANDLE hProcess
,
1720 IN LPCVOID lpBaseAddress
,
1725 /* Call the native function */
1726 Status
= NtFlushInstructionCache(hProcess
, (PVOID
)lpBaseAddress
, dwSize
);
1727 if (!NT_SUCCESS(Status
))
1729 /* Handle failure case */
1730 BaseSetLastNTError(Status
);
1743 ExitProcess(IN UINT uExitCode
)
1745 CSR_API_MESSAGE CsrRequest
;
1746 ASSERT(!BaseRunningInServerProcess
);
1750 /* Acquire the PEB lock */
1751 RtlAcquirePebLock();
1753 /* Kill all the threads */
1754 NtTerminateProcess(NULL
, 0);
1756 /* Unload all DLLs */
1757 LdrShutdownProcess();
1759 /* Notify Base Server of process termination */
1760 CsrRequest
.Data
.TerminateProcessRequest
.uExitCode
= uExitCode
;
1761 CsrClientCallServer(&CsrRequest
,
1763 MAKE_CSR_API(TERMINATE_PROCESS
, CSR_NATIVE
),
1764 sizeof(CSR_API_MESSAGE
));
1766 /* Now do it again */
1767 NtTerminateProcess(NtCurrentProcess(), uExitCode
);
1771 /* Release the PEB lock */
1772 RtlReleasePebLock();
1776 /* should never get here */
1786 TerminateProcess(IN HANDLE hProcess
,
1791 /* Check if no handle was passed in */
1794 /* Set error code */
1795 SetLastError(ERROR_INVALID_HANDLE
);
1799 /* Otherwise, try to terminate the process */
1800 Status
= NtTerminateProcess(hProcess
, uExitCode
);
1801 if (NT_SUCCESS(Status
)) return TRUE
;
1803 /* It failed, convert error code */
1804 BaseSetLastNTError(Status
);
1807 /* This is the failure path */
1816 FatalAppExitA(UINT uAction
,
1817 LPCSTR lpMessageText
)
1819 PUNICODE_STRING MessageTextU
;
1820 ANSI_STRING MessageText
;
1823 /* Initialize the string using the static TEB pointer */
1824 MessageTextU
= &NtCurrentTeb()->StaticUnicodeString
;
1825 RtlInitAnsiString(&MessageText
, (LPSTR
)lpMessageText
);
1827 /* Convert to unicode and just exit normally if this failed */
1828 Status
= RtlAnsiStringToUnicodeString(MessageTextU
, &MessageText
, FALSE
);
1829 if (!NT_SUCCESS(Status
)) ExitProcess(0);
1831 /* Call the Wide function */
1832 FatalAppExitW(uAction
, MessageTextU
->Buffer
);
1840 FatalAppExitW(IN UINT uAction
,
1841 IN LPCWSTR lpMessageText
)
1843 UNICODE_STRING UnicodeString
;
1847 /* Setup the stirng to print out */
1848 RtlInitUnicodeString(&UnicodeString
, lpMessageText
);
1850 /* Display the hard error no matter what */
1851 Status
= NtRaiseHardError(STATUS_FATAL_APP_EXIT
| HARDERROR_OVERRIDE_ERRORMODE
,
1854 (PULONG_PTR
)&UnicodeString
,
1858 /* Give the user a chance to abort */
1859 if ((NT_SUCCESS(Status
)) && (Response
== ResponseCancel
)) return;
1861 /* Otherwise kill the process */
1870 FatalExit(IN
int ExitCode
)
1873 /* On Checked builds, Windows gives you a nice little debugger UI */
1875 DbgPrint("FatalExit...\n");
1880 DbgPrompt( "A (Abort), B (Break), I (Ignore)? ", ch
, sizeof(ch
));
1888 ExitProcess(ExitCode
);
1895 /* On other builds, just kill the process */
1896 ExitProcess(ExitCode
);
1904 GetPriorityClass(IN HANDLE hProcess
)
1907 PROCESS_PRIORITY_CLASS PriorityClass
;
1909 /* Query the kernel */
1910 Status
= NtQueryInformationProcess(hProcess
,
1911 ProcessPriorityClass
,
1913 sizeof(PROCESS_PRIORITY_CLASS
),
1915 if (NT_SUCCESS(Status
))
1917 /* Handle the conversion from NT to Win32 classes */
1918 switch (PriorityClass
.PriorityClass
)
1920 case PROCESS_PRIORITY_CLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
1921 case PROCESS_PRIORITY_CLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
1922 case PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
1923 case PROCESS_PRIORITY_CLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
1924 case PROCESS_PRIORITY_CLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
1925 case PROCESS_PRIORITY_CLASS_NORMAL
: default: return NORMAL_PRIORITY_CLASS
;
1930 BaseSetLastNTError(Status
);
1939 SetPriorityClass(IN HANDLE hProcess
,
1940 IN DWORD dwPriorityClass
)
1944 PROCESS_PRIORITY_CLASS PriorityClass
;
1946 /* Handle conversion from Win32 to NT priority classes */
1947 switch (dwPriorityClass
)
1949 case IDLE_PRIORITY_CLASS
:
1950 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_IDLE
;
1953 case BELOW_NORMAL_PRIORITY_CLASS
:
1954 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
1957 case NORMAL_PRIORITY_CLASS
:
1958 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
1961 case ABOVE_NORMAL_PRIORITY_CLASS
:
1962 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
1965 case HIGH_PRIORITY_CLASS
:
1966 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1969 case REALTIME_PRIORITY_CLASS
:
1970 /* Try to acquire the privilege. If it fails, just use HIGH */
1971 State
= BasepIsRealtimeAllowed(TRUE
);
1972 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1973 PriorityClass
.PriorityClass
+= (State
!= NULL
);
1977 /* Unrecognized priority classes don't make it to the kernel */
1978 SetLastError(ERROR_INVALID_PARAMETER
);
1982 /* Send the request to the kernel, and don't touch the foreground flag */
1983 PriorityClass
.Foreground
= FALSE
;
1984 Status
= NtSetInformationProcess(hProcess
,
1985 ProcessPriorityClass
,
1987 sizeof(PROCESS_PRIORITY_CLASS
));
1989 /* Release the privilege if we had it */
1990 if (State
) RtlReleasePrivilege(State
);
1991 if (!NT_SUCCESS(Status
))
1993 /* Handle error path */
1994 BaseSetLastNTError(Status
);
2007 GetProcessVersion(IN DWORD ProcessId
)
2010 PIMAGE_NT_HEADERS NtHeader
;
2011 PIMAGE_DOS_HEADER DosHeader
;
2013 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
2016 HANDLE ProcessHandle
= NULL
;
2018 USHORT VersionData
[2];
2021 /* We'll be accessing stuff that can fault, so protect everything with SEH */
2024 /* It this an in-process or out-of-process request? */
2025 if (!(ProcessId
) || (GetCurrentProcessId() == ProcessId
))
2027 /* It's in-process, so just read our own header */
2028 NtHeader
= RtlImageNtHeader(NtCurrentPeb()->ImageBaseAddress
);
2031 /* Unable to read the NT header, something is wrong here... */
2032 Status
= STATUS_INVALID_IMAGE_FORMAT
;
2036 /* Get the version straight out of the NT header */
2037 Version
= MAKELONG(NtHeader
->OptionalHeader
.MinorSubsystemVersion
,
2038 NtHeader
->OptionalHeader
.MajorSubsystemVersion
);
2042 /* Out-of-process, so open it */
2043 ProcessHandle
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
,
2046 if (!ProcessHandle
) return 0;
2048 /* Try to find out where its PEB lives */
2049 Status
= NtQueryInformationProcess(ProcessHandle
,
2050 ProcessBasicInformation
,
2052 sizeof(ProcessBasicInfo
),
2055 if (!NT_SUCCESS(Status
)) goto Error
;
2056 Peb
= ProcessBasicInfo
.PebBaseAddress
;
2058 /* Now that we have the PEB, read the image base address out of it */
2059 Result
= ReadProcessMemory(ProcessHandle
,
2060 &Peb
->ImageBaseAddress
,
2062 sizeof(BaseAddress
),
2064 if (!Result
) goto Error
;
2066 /* Now read the e_lfanew (offset to NT header) from the base */
2067 DosHeader
= BaseAddress
;
2068 Result
= ReadProcessMemory(ProcessHandle
,
2069 &DosHeader
->e_lfanew
,
2073 if (!Result
) goto Error
;
2075 /* And finally, read the NT header itself by adding the offset */
2076 NtHeader
= (PVOID
)((ULONG_PTR
)BaseAddress
+ e_lfanew
);
2077 Result
= ReadProcessMemory(ProcessHandle
,
2078 &NtHeader
->OptionalHeader
.MajorSubsystemVersion
,
2080 sizeof(VersionData
),
2082 if (!Result
) goto Error
;
2084 /* Get the version straight out of the NT header */
2085 Version
= MAKELONG(VersionData
[0], VersionData
[1]);
2088 /* If there was an error anywhere, set the last error */
2089 if (!NT_SUCCESS(Status
)) BaseSetLastNTError(Status
);
2094 /* Close the process handle */
2095 if (ProcessHandle
) CloseHandle(ProcessHandle
);
2099 /* And return the version data */
2108 GetProcessIoCounters(IN HANDLE hProcess
,
2109 OUT PIO_COUNTERS lpIoCounters
)
2113 /* Query the kernel. Structures are identical, so let it do the copy too. */
2114 Status
= NtQueryInformationProcess(hProcess
,
2117 sizeof(IO_COUNTERS
),
2119 if (!NT_SUCCESS(Status
))
2121 /* Handle error path */
2122 BaseSetLastNTError(Status
);
2135 GetProcessPriorityBoost(IN HANDLE hProcess
,
2136 OUT PBOOL pDisablePriorityBoost
)
2139 ULONG PriorityBoost
;
2141 /* Query the kernel */
2142 Status
= NtQueryInformationProcess(hProcess
,
2143 ProcessPriorityBoost
,
2147 if (NT_SUCCESS(Status
))
2149 /* Convert from ULONG to a BOOL */
2150 *pDisablePriorityBoost
= PriorityBoost
? TRUE
: FALSE
;
2154 /* Handle error path */
2155 BaseSetLastNTError(Status
);
2164 SetProcessPriorityBoost(IN HANDLE hProcess
,
2165 IN BOOL bDisablePriorityBoost
)
2168 ULONG PriorityBoost
;
2170 /* Enforce that this is a BOOL, and send it to the kernel as a ULONG */
2171 PriorityBoost
= (bDisablePriorityBoost
? TRUE
: FALSE
);
2172 Status
= NtSetInformationProcess(hProcess
,
2173 ProcessPriorityBoost
,
2176 if (!NT_SUCCESS(Status
))
2178 /* Handle error path */
2179 BaseSetLastNTError(Status
);
2192 GetProcessHandleCount(IN HANDLE hProcess
,
2193 OUT PDWORD pdwHandleCount
)
2198 /* Query the kernel */
2199 Status
= NtQueryInformationProcess(hProcess
,
2204 if (NT_SUCCESS(Status
))
2206 /* Copy the count and return sucecss */
2207 *pdwHandleCount
= phc
;
2211 /* Handle error path */
2212 BaseSetLastNTError(Status
);
2221 IsWow64Process(IN HANDLE hProcess
,
2222 OUT PBOOL Wow64Process
)
2227 /* Query the kernel */
2228 Status
= NtQueryInformationProcess(hProcess
,
2229 ProcessWow64Information
,
2233 if (!NT_SUCCESS(Status
))
2235 /* Handle error path */
2236 BaseSetLastNTError(Status
);
2240 /* Enforce this is a BOOL, and return success */
2241 *Wow64Process
= (pbi
!= 0);
2250 GetCommandLineA(VOID
)
2252 return BaseAnsiCommandLine
.Buffer
;
2260 GetCommandLineW(VOID
)
2262 return BaseUnicodeCommandLine
.Buffer
;
2270 ReadProcessMemory(IN HANDLE hProcess
,
2271 IN LPCVOID lpBaseAddress
,
2274 OUT SIZE_T
* lpNumberOfBytesRead
)
2279 Status
= NtReadVirtualMemory(hProcess
,
2280 (PVOID
)lpBaseAddress
,
2285 /* In user-mode, this parameter is optional */
2286 if (lpNumberOfBytesRead
) *lpNumberOfBytesRead
= nSize
;
2287 if (!NT_SUCCESS(Status
))
2290 BaseSetLastNTError(Status
);
2294 /* Return success */
2303 WriteProcessMemory(IN HANDLE hProcess
,
2304 IN LPVOID lpBaseAddress
,
2305 IN LPCVOID lpBuffer
,
2307 OUT SIZE_T
*lpNumberOfBytesWritten
)
2315 /* Set parameters for protect call */
2317 Base
= lpBaseAddress
;
2319 /* Check the current status */
2320 Status
= NtProtectVirtualMemory(hProcess
,
2323 PAGE_EXECUTE_READWRITE
,
2325 if (NT_SUCCESS(Status
))
2327 /* Check if we are unprotecting */
2328 UnProtect
= OldValue
& (PAGE_READWRITE
|
2330 PAGE_EXECUTE_READWRITE
|
2331 PAGE_EXECUTE_WRITECOPY
) ? FALSE
: TRUE
;
2334 /* Set the new protection */
2335 Status
= NtProtectVirtualMemory(hProcess
,
2341 /* Write the memory */
2342 Status
= NtWriteVirtualMemory(hProcess
,
2348 /* In Win32, the parameter is optional, so handle this case */
2349 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2351 if (!NT_SUCCESS(Status
))
2354 BaseSetLastNTError(Status
);
2358 /* Flush the ITLB */
2359 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2364 /* Check if we were read only */
2365 if (OldValue
& (PAGE_NOACCESS
| PAGE_READONLY
))
2367 /* Restore protection and fail */
2368 NtProtectVirtualMemory(hProcess
,
2373 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2375 /* Note: This is what Windows returns and code depends on it */
2376 return STATUS_ACCESS_VIOLATION
;
2379 /* Otherwise, do the write */
2380 Status
= NtWriteVirtualMemory(hProcess
,
2386 /* In Win32, the parameter is optional, so handle this case */
2387 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2389 /* And restore the protection */
2390 NtProtectVirtualMemory(hProcess
,
2395 if (!NT_SUCCESS(Status
))
2398 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2400 /* Note: This is what Windows returns and code depends on it */
2401 return STATUS_ACCESS_VIOLATION
;
2404 /* Flush the ITLB */
2405 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2412 BaseSetLastNTError(Status
);
2422 ProcessIdToSessionId(IN DWORD dwProcessId
,
2423 OUT PDWORD pSessionId
)
2425 PROCESS_SESSION_INFORMATION SessionInformation
;
2426 OBJECT_ATTRIBUTES ObjectAttributes
;
2428 HANDLE ProcessHandle
;
2431 /* Do a quick check if the pointer is not writable */
2432 if (IsBadWritePtr(pSessionId
, sizeof(DWORD
)))
2435 SetLastError(ERROR_INVALID_PARAMETER
);
2439 /* Open the process passed in by ID */
2440 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
2441 ClientId
.UniqueThread
= 0;
2442 InitializeObjectAttributes(&ObjectAttributes
, NULL
, 0, NULL
, NULL
);
2443 Status
= NtOpenProcess(&ProcessHandle
,
2444 PROCESS_QUERY_INFORMATION
,
2447 if (NT_SUCCESS(Status
))
2449 /* Query the session ID from the kernel */
2450 Status
= NtQueryInformationProcess(ProcessHandle
,
2451 ProcessSessionInformation
,
2452 &SessionInformation
,
2453 sizeof(SessionInformation
),
2456 /* Close the handle and check if we suceeded */
2457 NtClose(ProcessHandle
);
2458 if (NT_SUCCESS(Status
))
2460 /* Return the session ID */
2461 *pSessionId
= SessionInformation
.SessionId
;
2466 /* Set error code and fail */
2467 BaseSetLastNTError(Status
);
2476 CreateProcessInternalW(HANDLE hToken
,
2477 LPCWSTR lpApplicationName
,
2478 LPWSTR lpCommandLine
,
2479 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
2480 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
2481 BOOL bInheritHandles
,
2482 DWORD dwCreationFlags
,
2483 LPVOID lpEnvironment
,
2484 LPCWSTR lpCurrentDirectory
,
2485 LPSTARTUPINFOW lpStartupInfo
,
2486 LPPROCESS_INFORMATION lpProcessInformation
,
2490 PROCESS_PRIORITY_CLASS PriorityClass
;
2491 BOOLEAN FoundQuotes
= FALSE
;
2492 BOOLEAN QuotesNeeded
= FALSE
;
2493 BOOLEAN CmdLineIsAppName
= FALSE
;
2494 UNICODE_STRING ApplicationName
= { 0, 0, NULL
};
2495 OBJECT_ATTRIBUTES LocalObjectAttributes
;
2496 POBJECT_ATTRIBUTES ObjectAttributes
;
2497 HANDLE hSection
= NULL
, hProcess
= NULL
, hThread
= NULL
, hDebug
= NULL
;
2498 SECTION_IMAGE_INFORMATION SectionImageInfo
;
2499 LPWSTR CurrentDirectory
= NULL
;
2500 LPWSTR CurrentDirectoryPart
;
2501 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
2502 STARTUPINFOW StartupInfo
;
2504 LPWSTR BatchCommandLine
;
2505 ULONG CmdLineLength
;
2506 UNICODE_STRING CommandLineString
;
2508 LPWSTR QuotedCmdLine
= NULL
;
2510 LPWSTR NullBuffer
= NULL
;
2511 LPWSTR NameBuffer
= NULL
;
2515 BOOLEAN SearchDone
= FALSE
;
2516 BOOLEAN Escape
= FALSE
;
2518 PPEB OurPeb
= NtCurrentPeb();
2523 /* FIXME should process
2524 * HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
2525 * key (see http://blogs.msdn.com/oldnewthing/archive/2005/12/19/505449.aspx)
2528 DPRINT("CreateProcessW: lpApplicationName: %S lpCommandLine: %S"
2529 " lpEnvironment: %p lpCurrentDirectory: %S dwCreationFlags: %lx\n",
2530 lpApplicationName
, lpCommandLine
, lpEnvironment
, lpCurrentDirectory
,
2533 /* Flags we don't handle yet */
2534 if (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
)
2536 DPRINT1("CREATE_SEPARATE_WOW_VDM not handled\n");
2538 if (dwCreationFlags
& CREATE_SHARED_WOW_VDM
)
2540 DPRINT1("CREATE_SHARED_WOW_VDM not handled\n");
2542 if (dwCreationFlags
& CREATE_FORCEDOS
)
2544 DPRINT1("CREATE_FORCEDOS not handled\n");
2547 /* Fail on this flag, it's only valid with the WithLogonW function */
2548 if (dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
)
2550 DPRINT1("Invalid flag used\n");
2551 SetLastError(ERROR_INVALID_PARAMETER
);
2555 /* This combination is illegal (see MSDN) */
2556 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
2557 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
2559 DPRINT1("Invalid flag combo used\n");
2560 SetLastError(ERROR_INVALID_PARAMETER
);
2564 /* Another illegal combo */
2565 if ((dwCreationFlags
& (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
)) ==
2566 (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
))
2568 DPRINT1("Invalid flag combo used\n");
2569 SetLastError(ERROR_INVALID_PARAMETER
);
2573 if (lpCurrentDirectory
)
2575 if ((GetFileAttributesW(lpCurrentDirectory
) == INVALID_FILE_ATTRIBUTES
) ||
2576 !(GetFileAttributesW(lpCurrentDirectory
) & FILE_ATTRIBUTE_DIRECTORY
))
2578 SetLastError(ERROR_DIRECTORY
);
2584 * We're going to modify and mask out flags and stuff in lpStartupInfo,
2585 * so we'll use our own local copy for that.
2587 StartupInfo
= *lpStartupInfo
;
2589 /* FIXME: Use default Separate/Shared VDM Flag */
2591 /* If we are inside a Job, use Separate VDM so it won't escape the Job */
2592 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
2594 if (NtIsProcessInJob(NtCurrentProcess(), NULL
))
2596 /* Remove the shared flag and add the separate flag. */
2597 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
2598 CREATE_SEPARATE_WOW_VDM
;
2603 * According to some sites, ShellExecuteEx uses an undocumented flag to
2604 * send private handle data (such as HMONITOR or HICON). See:
2605 * www.catch22.net/tuts/undoc01.asp. This implies that we can't use the
2606 * standard handles anymore since we'd be overwriting this private data
2608 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
2609 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
2611 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
2614 /* Start by zeroing out the fields */
2615 RtlZeroMemory(lpProcessInformation
, sizeof(PROCESS_INFORMATION
));
2617 /* Easy stuff first, convert the process priority class */
2618 PriorityClass
.Foreground
= FALSE
;
2619 PriorityClass
.PriorityClass
= (UCHAR
)BasepConvertPriorityClass(dwCreationFlags
);
2623 /* Search for escape sequences */
2624 ScanString
= lpCommandLine
;
2625 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
2628 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\"')
2636 /* Get the application name and do all the proper formating necessary */
2638 /* See if we have an application name (oh please let us have one!) */
2639 if (!lpApplicationName
)
2641 /* The fun begins */
2642 NameBuffer
= RtlAllocateHeap(RtlGetProcessHeap(),
2644 MAX_PATH
* sizeof(WCHAR
));
2645 if (NameBuffer
== NULL
)
2647 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2651 /* This is all we have to work with :( */
2652 lpApplicationName
= lpCommandLine
;
2654 /* Initialize our friends at the beginning */
2655 NullBuffer
= (LPWSTR
)lpApplicationName
;
2656 ScanString
= (LPWSTR
)lpApplicationName
;
2658 /* We will start by looking for a quote */
2659 if (*ScanString
== L
'\"')
2661 /* That was quick */
2664 /* Advance past quote */
2666 lpApplicationName
= ScanString
;
2668 /* Find the closing quote */
2671 if (*ScanString
== L
'\"' && *(ScanString
- 1) != L
'^')
2674 NullBuffer
= ScanString
;
2681 NullBuffer
= ScanString
;
2686 /* No quotes, so we'll be looking for white space */
2688 /* Reset the pointer */
2689 lpApplicationName
= lpCommandLine
;
2691 /* Find whitespace of Tab */
2694 if (*ScanString
== ' ' || *ScanString
== '\t')
2697 NullBuffer
= ScanString
;
2703 NullBuffer
= ScanString
;
2707 /* Set the Null Buffer */
2708 SaveChar
= *NullBuffer
;
2709 *NullBuffer
= UNICODE_NULL
;
2711 /* Do a search for the file */
2712 DPRINT("Ready for SearchPathW: %S\n", lpApplicationName
);
2713 RetVal
= SearchPathW(NULL
,
2718 NULL
) * sizeof(WCHAR
);
2720 /* Did it find something? */
2723 /* Get file attributes */
2724 ULONG Attributes
= GetFileAttributesW(NameBuffer
);
2725 if (Attributes
& FILE_ATTRIBUTE_DIRECTORY
)
2727 /* Give it a length of 0 to fail, this was a directory. */
2733 RetVal
+= sizeof(WCHAR
);
2737 /* Now check if we have a file, and if the path size is OK */
2738 if (!RetVal
|| RetVal
>= (MAX_PATH
* sizeof(WCHAR
)))
2743 /* We failed, try to get the Path Type */
2744 DPRINT("SearchPathW failed. Retval: %ld\n", RetVal
);
2745 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
2747 /* If it's not relative, try to get the error */
2748 if (PathType
!= RtlPathTypeRelative
)
2750 /* This should fail, and give us a detailed LastError */
2751 hFile
= CreateFileW(lpApplicationName
,
2753 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
2756 FILE_ATTRIBUTE_NORMAL
,
2759 /* Did it actually NOT fail? */
2760 if (hFile
!= INVALID_HANDLE_VALUE
)
2762 /* Fake the error */
2764 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2769 /* Immediately set the error */
2770 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2773 /* Did we already fail once? */
2776 SetLastError(Error
);
2780 /* Not yet, cache it */
2781 Error
= GetLastError();
2784 /* Put back the command line */
2785 *NullBuffer
= SaveChar
;
2786 lpApplicationName
= NameBuffer
;
2789 * If the search isn't done and we still have cmdline
2790 * then start over. Ex: c:\ha ha ha\haha.exe
2792 if (*ScanString
&& !SearchDone
)
2794 /* Move in the buffer */
2796 NullBuffer
= ScanString
;
2798 /* We will have to add a quote, since there is a space*/
2799 QuotesNeeded
= TRUE
;
2801 /* And we will also fake the fact we found one */
2808 /* We totally failed */
2812 /* Put back the command line */
2813 *NullBuffer
= SaveChar
;
2814 lpApplicationName
= NameBuffer
;
2815 DPRINT("SearchPathW suceeded (%ld): %S\n", RetVal
, NameBuffer
);
2817 else if (!lpCommandLine
|| *lpCommandLine
== UNICODE_NULL
)
2819 /* We have an app name (good!) but no command line */
2820 CmdLineIsAppName
= TRUE
;
2821 lpCommandLine
= (LPWSTR
)lpApplicationName
;
2824 /* At this point the name has been toyed with enough to be openable */
2825 Status
= BasepMapFile(lpApplicationName
, &hSection
, &ApplicationName
);
2827 /* Check for failure */
2828 if (!NT_SUCCESS(Status
))
2830 /* Could be a non-PE File */
2833 /* Check if the Kernel tells us it's not even valid MZ */
2834 case STATUS_INVALID_IMAGE_NE_FORMAT
:
2835 case STATUS_INVALID_IMAGE_PROTECT
:
2836 case STATUS_INVALID_IMAGE_NOT_MZ
:
2839 /* If it's a DOS app, use VDM */
2840 if ((BasepCheckDosApp(&ApplicationName
)))
2842 DPRINT1("Launching VDM...\n");
2843 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2844 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2845 return CreateProcessW(L
"ntvdm.exe",
2846 (LPWSTR
)((ULONG_PTR
)lpApplicationName
), /* FIXME: Buffer must be writable!!! */
2847 lpProcessAttributes
,
2854 lpProcessInformation
);
2857 /* It's a batch file */
2858 Extension
= &ApplicationName
.Buffer
[ApplicationName
.Length
/
2861 /* Make sure the extensions are correct */
2862 if (_wcsnicmp(Extension
, L
".bat", 4) && _wcsnicmp(Extension
, L
".cmd", 4))
2864 SetLastError(ERROR_BAD_EXE_FORMAT
);
2868 /* Calculate the length of the command line */
2869 CmdLineLength
= wcslen(CMD_STRING
) + wcslen(lpCommandLine
) + 1;
2871 /* If we found quotes, then add them into the length size */
2872 if (CmdLineIsAppName
|| FoundQuotes
) CmdLineLength
+= 2;
2873 CmdLineLength
*= sizeof(WCHAR
);
2875 /* Allocate space for the new command line */
2876 BatchCommandLine
= RtlAllocateHeap(RtlGetProcessHeap(),
2879 if (BatchCommandLine
== NULL
)
2881 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2886 wcscpy(BatchCommandLine
, CMD_STRING
);
2887 if (CmdLineIsAppName
|| FoundQuotes
)
2889 wcscat(BatchCommandLine
, L
"\"");
2891 wcscat(BatchCommandLine
, lpCommandLine
);
2892 if (CmdLineIsAppName
|| FoundQuotes
)
2894 wcscat(BatchCommandLine
, L
"\"");
2897 /* Create it as a Unicode String */
2898 RtlInitUnicodeString(&CommandLineString
, BatchCommandLine
);
2900 /* Set the command line to this */
2901 lpCommandLine
= CommandLineString
.Buffer
;
2902 lpApplicationName
= NULL
;
2905 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2906 ApplicationName
.Buffer
= NULL
;
2910 case STATUS_INVALID_IMAGE_WIN_16
:
2912 /* It's a Win16 Image, use VDM */
2913 DPRINT1("Launching VDM...\n");
2914 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2915 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2916 return CreateProcessW(L
"ntvdm.exe",
2917 (LPWSTR
)((ULONG_PTR
)lpApplicationName
), /* FIXME: Buffer must be writable!!! */
2918 lpProcessAttributes
,
2925 lpProcessInformation
);
2927 case STATUS_OBJECT_NAME_NOT_FOUND
:
2928 case STATUS_OBJECT_PATH_NOT_FOUND
:
2929 BaseSetLastNTError(Status
);
2933 /* Invalid Image Type */
2934 SetLastError(ERROR_BAD_EXE_FORMAT
);
2939 /* Use our desktop if we didn't get any */
2940 if (!StartupInfo
.lpDesktop
)
2942 StartupInfo
.lpDesktop
= OurPeb
->ProcessParameters
->DesktopInfo
.Buffer
;
2945 /* FIXME: Check if Application is allowed to run */
2947 /* FIXME: Allow CREATE_SEPARATE only for WOW Apps, once we have that. */
2949 /* Get some information about the executable */
2950 Status
= NtQuerySection(hSection
,
2951 SectionImageInformation
,
2953 sizeof(SectionImageInfo
),
2955 if(!NT_SUCCESS(Status
))
2957 DPRINT1("Unable to get SectionImageInformation, status 0x%x\n", Status
);
2958 BaseSetLastNTError(Status
);
2962 /* Don't execute DLLs */
2963 if (SectionImageInfo
.ImageCharacteristics
& IMAGE_FILE_DLL
)
2965 DPRINT1("Can't execute a DLL\n");
2966 SetLastError(ERROR_BAD_EXE_FORMAT
);
2970 /* FIXME: Check for Debugger */
2972 /* FIXME: Check if Machine Type and SubSys Version Match */
2974 /* We don't support POSIX or anything else for now */
2975 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
!= SectionImageInfo
.SubSystemType
&&
2976 IMAGE_SUBSYSTEM_WINDOWS_CUI
!= SectionImageInfo
.SubSystemType
)
2978 DPRINT1("Invalid subsystem %d\n", SectionImageInfo
.SubSystemType
);
2980 * Despite the name of the error code suggests, it corresponds to the
2981 * well-known "The %1 application cannot be run in Win32 mode" message.
2983 SetLastError(ERROR_CHILD_NOT_COMPLETE
);
2987 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
== SectionImageInfo
.SubSystemType
)
2989 /* Do not create a console for GUI applications */
2990 dwCreationFlags
&= ~CREATE_NEW_CONSOLE
;
2991 dwCreationFlags
|= DETACHED_PROCESS
;
2994 /* Initialize the process object attributes */
2995 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
2996 lpProcessAttributes
,
2999 /* Check if we're going to be debugged */
3000 if (dwCreationFlags
& DEBUG_PROCESS
)
3002 /* FIXME: Set process flag */
3005 /* Check if we're going to be debugged */
3006 if (dwCreationFlags
& (DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
))
3008 /* Connect to DbgUi */
3009 Status
= DbgUiConnectToDbg();
3010 if (!NT_SUCCESS(Status
))
3012 DPRINT1("Failed to connect to DbgUI!\n");
3013 BaseSetLastNTError(Status
);
3017 /* Get the debug object */
3018 hDebug
= DbgUiGetThreadDebugObject();
3020 /* Check if only this process will be debugged */
3021 if (dwCreationFlags
& DEBUG_ONLY_THIS_PROCESS
)
3023 /* Set process flag */
3024 hDebug
= (HANDLE
)((ULONG_PTR
)hDebug
| 0x1);
3028 /* Create the Process */
3029 Status
= NtCreateProcess(&hProcess
,
3033 (BOOLEAN
)bInheritHandles
,
3037 if (!NT_SUCCESS(Status
))
3039 DPRINT1("Unable to create process, status 0x%x\n", Status
);
3040 BaseSetLastNTError(Status
);
3044 if (PriorityClass
.PriorityClass
!= PROCESS_PRIORITY_CLASS_INVALID
)
3047 Status
= NtSetInformationProcess(hProcess
,
3048 ProcessPriorityClass
,
3050 sizeof(PROCESS_PRIORITY_CLASS
));
3051 if(!NT_SUCCESS(Status
))
3053 DPRINT1("Unable to set new process priority, status 0x%x\n", Status
);
3054 BaseSetLastNTError(Status
);
3059 /* Set Error Mode */
3060 if (dwCreationFlags
& CREATE_DEFAULT_ERROR_MODE
)
3062 ULONG ErrorMode
= SEM_FAILCRITICALERRORS
;
3063 NtSetInformationProcess(hProcess
,
3064 ProcessDefaultHardErrorMode
,
3069 /* Convert the directory to a full path */
3070 if (lpCurrentDirectory
)
3072 /* Allocate a buffer */
3073 CurrentDirectory
= RtlAllocateHeap(RtlGetProcessHeap(),
3075 (MAX_PATH
+ 1) * sizeof(WCHAR
));
3076 if (CurrentDirectory
== NULL
)
3078 DPRINT1("Cannot allocate memory for directory name\n");
3079 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3083 /* Get the length */
3084 if (GetFullPathNameW(lpCurrentDirectory
,
3087 &CurrentDirectoryPart
) > MAX_PATH
)
3089 DPRINT1("Directory name too long\n");
3090 SetLastError(ERROR_DIRECTORY
);
3095 /* Insert quotes if needed */
3096 if (QuotesNeeded
|| CmdLineIsAppName
)
3098 /* Allocate a buffer */
3099 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3101 (wcslen(lpCommandLine
) + 2 + 1) *
3103 if (QuotedCmdLine
== NULL
)
3105 DPRINT1("Cannot allocate memory for quoted command line\n");
3106 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3110 /* Copy the first quote */
3111 wcscpy(QuotedCmdLine
, L
"\"");
3113 /* Save a null char */
3116 SaveChar
= *NullBuffer
;
3117 *NullBuffer
= UNICODE_NULL
;
3120 /* Add the command line and the finishing quote */
3121 wcscat(QuotedCmdLine
, lpCommandLine
);
3122 wcscat(QuotedCmdLine
, L
"\"");
3124 /* Add the null char */
3127 *NullBuffer
= SaveChar
;
3128 wcscat(QuotedCmdLine
, NullBuffer
);
3131 DPRINT("Quoted CmdLine: %S\n", QuotedCmdLine
);
3136 if (QuotedCmdLine
== NULL
)
3138 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3140 (wcslen(lpCommandLine
) + 1) * sizeof(WCHAR
));
3141 if (QuotedCmdLine
== NULL
)
3143 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3146 wcscpy(QuotedCmdLine
, lpCommandLine
);
3149 ScanString
= QuotedCmdLine
;
3150 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
3153 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\\')
3155 memmove(ScanString
-1, ScanString
, wcslen(ScanString
) * sizeof(WCHAR
) + sizeof(WCHAR
));
3160 /* Get the Process Information */
3161 Status
= NtQueryInformationProcess(hProcess
,
3162 ProcessBasicInformation
,
3164 sizeof(ProcessBasicInfo
),
3167 /* Convert the environment */
3168 if(lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3170 lpEnvironment
= BasepConvertUnicodeEnvironment(&EnvSize
, lpEnvironment
);
3171 if (!lpEnvironment
) goto Cleanup
;
3174 /* Create Process Environment */
3175 RemotePeb
= ProcessBasicInfo
.PebBaseAddress
;
3176 Ret
= BasePushProcessParameters(0,
3179 (LPWSTR
)lpApplicationName
,
3181 (QuotesNeeded
|| CmdLineIsAppName
|| Escape
) ?
3182 QuotedCmdLine
: lpCommandLine
,
3190 if (!Ret
) goto Cleanup
;
3192 /* Cleanup Environment */
3193 if (lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3195 RtlDestroyEnvironment(lpEnvironment
);
3198 /* Close the section */
3202 /* Duplicate the handles if needed */
3203 if (!bInheritHandles
&& !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
3204 SectionImageInfo
.SubSystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
3206 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
;
3208 /* Get the remote parameters */
3209 Status
= NtReadVirtualMemory(hProcess
,
3210 &RemotePeb
->ProcessParameters
,
3214 if (!NT_SUCCESS(Status
))
3216 DPRINT1("Failed to read memory\n");
3220 /* Duplicate and write the handles */
3221 BasepDuplicateAndWriteHandle(hProcess
,
3222 OurPeb
->ProcessParameters
->StandardInput
,
3223 &RemoteParameters
->StandardInput
);
3224 BasepDuplicateAndWriteHandle(hProcess
,
3225 OurPeb
->ProcessParameters
->StandardOutput
,
3226 &RemoteParameters
->StandardOutput
);
3227 BasepDuplicateAndWriteHandle(hProcess
,
3228 OurPeb
->ProcessParameters
->StandardError
,
3229 &RemoteParameters
->StandardError
);
3232 /* Create the first thread */
3233 DPRINT("Creating thread for process (EntryPoint = 0x%p)\n",
3234 SectionImageInfo
.TransferAddress
);
3235 hThread
= BasepCreateFirstThread(hProcess
,
3242 if (hThread
== NULL
)
3244 DPRINT1("Could not create Initial Thread\n");
3245 /* FIXME - set last error code */
3249 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
3251 NtResumeThread(hThread
, &Dummy
);
3255 lpProcessInformation
->dwProcessId
= (DWORD
)ClientId
.UniqueProcess
;
3256 lpProcessInformation
->dwThreadId
= (DWORD
)ClientId
.UniqueThread
;
3257 lpProcessInformation
->hProcess
= hProcess
;
3258 lpProcessInformation
->hThread
= hThread
;
3259 DPRINT("hThread[%p]: %p inside hProcess[%p]: %p\n", hThread
,
3260 ClientId
.UniqueThread
, ClientId
.UniqueProcess
, hProcess
);
3261 hProcess
= hThread
= NULL
;
3265 /* De-allocate heap strings */
3266 if (NameBuffer
) RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
3267 if (ApplicationName
.Buffer
)
3268 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
3269 if (CurrentDirectory
) RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentDirectory
);
3270 if (QuotedCmdLine
) RtlFreeHeap(RtlGetProcessHeap(), 0, QuotedCmdLine
);
3272 /* Kill any handles still alive */
3273 if (hSection
) NtClose(hSection
);
3276 /* We don't know any more details than this */
3277 NtTerminateProcess(hProcess
, STATUS_UNSUCCESSFUL
);
3280 if (hProcess
) NtClose(hProcess
);
3282 /* Return Success */
3291 CreateProcessW(LPCWSTR lpApplicationName
,
3292 LPWSTR lpCommandLine
,
3293 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3294 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3295 BOOL bInheritHandles
,
3296 DWORD dwCreationFlags
,
3297 LPVOID lpEnvironment
,
3298 LPCWSTR lpCurrentDirectory
,
3299 LPSTARTUPINFOW lpStartupInfo
,
3300 LPPROCESS_INFORMATION lpProcessInformation
)
3302 /* Call the internal (but exported) version */
3303 return CreateProcessInternalW(0,
3306 lpProcessAttributes
,
3313 lpProcessInformation
,
3322 CreateProcessInternalA(HANDLE hToken
,
3323 LPCSTR lpApplicationName
,
3324 LPSTR lpCommandLine
,
3325 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3326 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3327 BOOL bInheritHandles
,
3328 DWORD dwCreationFlags
,
3329 LPVOID lpEnvironment
,
3330 LPCSTR lpCurrentDirectory
,
3331 LPSTARTUPINFOA lpStartupInfo
,
3332 LPPROCESS_INFORMATION lpProcessInformation
,
3335 PUNICODE_STRING CommandLine
= NULL
;
3336 UNICODE_STRING DummyString
;
3337 UNICODE_STRING LiveCommandLine
;
3338 UNICODE_STRING ApplicationName
;
3339 UNICODE_STRING CurrentDirectory
;
3341 STARTUPINFOW StartupInfo
;
3343 DPRINT("dwCreationFlags %x, lpEnvironment %x, lpCurrentDirectory %x, "
3344 "lpStartupInfo %x, lpProcessInformation %x\n",
3345 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
3346 lpStartupInfo
, lpProcessInformation
);
3348 /* Copy Startup Info */
3349 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
3351 /* Initialize all strings to nothing */
3352 LiveCommandLine
.Buffer
= NULL
;
3353 DummyString
.Buffer
= NULL
;
3354 ApplicationName
.Buffer
= NULL
;
3355 CurrentDirectory
.Buffer
= NULL
;
3356 StartupInfo
.lpDesktop
= NULL
;
3357 StartupInfo
.lpReserved
= NULL
;
3358 StartupInfo
.lpTitle
= NULL
;
3360 /* Convert the Command line */
3363 /* If it's too long, then we'll have a problem */
3364 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
3365 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
3367 /* Cache it in the TEB */
3368 CommandLine
= Basep8BitStringToStaticUnicodeString(lpCommandLine
);
3372 /* Use a dynamic version */
3373 Basep8BitStringToDynamicUnicodeString(&LiveCommandLine
,
3379 /* The logic below will use CommandLine, so we must make it valid */
3380 CommandLine
= &DummyString
;
3383 /* Convert the Name and Directory */
3384 if (lpApplicationName
)
3386 Basep8BitStringToDynamicUnicodeString(&ApplicationName
,
3389 if (lpCurrentDirectory
)
3391 Basep8BitStringToDynamicUnicodeString(&CurrentDirectory
,
3392 lpCurrentDirectory
);
3395 /* Now convert Startup Strings */
3396 if (lpStartupInfo
->lpReserved
)
3398 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
3399 &StartupInfo
.lpReserved
);
3401 if (lpStartupInfo
->lpDesktop
)
3403 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
3404 &StartupInfo
.lpDesktop
);
3406 if (lpStartupInfo
->lpTitle
)
3408 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
3409 &StartupInfo
.lpTitle
);
3412 /* Call the Unicode function */
3413 bRetVal
= CreateProcessInternalW(hToken
,
3414 ApplicationName
.Buffer
,
3415 LiveCommandLine
.Buffer
?
3416 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
3417 lpProcessAttributes
,
3422 CurrentDirectory
.Buffer
,
3424 lpProcessInformation
,
3428 RtlFreeUnicodeString(&ApplicationName
);
3429 RtlFreeUnicodeString(&LiveCommandLine
);
3430 RtlFreeUnicodeString(&CurrentDirectory
);
3431 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpDesktop
);
3432 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpReserved
);
3433 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpTitle
);
3435 /* Return what Unicode did */
3440 * FUNCTION: The CreateProcess function creates a new process and its
3441 * primary thread. The new process executes the specified executable file
3444 * lpApplicationName = Pointer to name of executable module
3445 * lpCommandLine = Pointer to command line string
3446 * lpProcessAttributes = Process security attributes
3447 * lpThreadAttributes = Thread security attributes
3448 * bInheritHandles = Handle inheritance flag
3449 * dwCreationFlags = Creation flags
3450 * lpEnvironment = Pointer to new environment block
3451 * lpCurrentDirectory = Pointer to current directory name
3452 * lpStartupInfo = Pointer to startup info
3453 * lpProcessInformation = Pointer to process information
3459 CreateProcessA(LPCSTR lpApplicationName
,
3460 LPSTR lpCommandLine
,
3461 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3462 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3463 BOOL bInheritHandles
,
3464 DWORD dwCreationFlags
,
3465 LPVOID lpEnvironment
,
3466 LPCSTR lpCurrentDirectory
,
3467 LPSTARTUPINFOA lpStartupInfo
,
3468 LPPROCESS_INFORMATION lpProcessInformation
)
3470 /* Call the internal (but exported) version */
3471 return CreateProcessInternalA(0,
3474 lpProcessAttributes
,
3481 lpProcessInformation
,
3490 WinExec(LPCSTR lpCmdLine
,
3493 STARTUPINFOA StartupInfo
;
3494 PROCESS_INFORMATION ProcessInformation
;
3497 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
3498 StartupInfo
.cb
= sizeof(STARTUPINFOA
);
3499 StartupInfo
.wShowWindow
= (WORD
)uCmdShow
;
3500 StartupInfo
.dwFlags
= 0;
3502 if (!CreateProcessA(NULL
,
3511 &ProcessInformation
))
3513 dosErr
= GetLastError();
3514 return dosErr
< 32 ? dosErr
: ERROR_BAD_FORMAT
;
3517 if (NULL
!= UserWaitForInputIdleRoutine
)
3519 UserWaitForInputIdleRoutine(ProcessInformation
.hProcess
,
3523 NtClose(ProcessInformation
.hProcess
);
3524 NtClose(ProcessInformation
.hThread
);
3526 return 33; /* Something bigger than 31 means success. */