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
)
464 DPRINT("BaseProcessStartup(..) - setting up exception frame.\n");
468 /* Set our Start Address */
469 NtSetInformationThread(NtCurrentThread(),
470 ThreadQuerySetWin32StartAddress
,
472 sizeof(PPROCESS_START_ROUTINE
));
474 /* Call the Start Routine */
475 uExitCode
= (lpStartAddress
)();
477 _SEH2_EXCEPT(BaseExceptionFilter(_SEH2_GetExceptionInformation()))
479 /* Get the SEH Error */
480 uExitCode
= _SEH2_GetExceptionCode();
484 /* Exit the Process with our error */
485 ExitProcess(uExitCode
);
489 * Tells CSR that a new process was created
493 BasepNotifyCsrOfCreation(ULONG dwCreationFlags
,
495 IN BOOL InheritHandles
)
497 ULONG Request
= CREATE_PROCESS
;
498 CSR_API_MESSAGE CsrRequest
;
501 DPRINT("BasepNotifyCsrOfCreation: Process: %lx, Flags %lx\n",
502 ProcessId
, dwCreationFlags
);
504 /* Fill out the request */
505 CsrRequest
.Data
.CreateProcessRequest
.NewProcessId
= ProcessId
;
506 CsrRequest
.Data
.CreateProcessRequest
.Flags
= dwCreationFlags
;
507 CsrRequest
.Data
.CreateProcessRequest
.bInheritHandles
= InheritHandles
;
510 Status
= CsrClientCallServer(&CsrRequest
,
512 MAKE_CSR_API(Request
, CSR_NATIVE
),
513 sizeof(CSR_API_MESSAGE
));
514 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
516 DPRINT1("Failed to tell csrss about new process\n");
517 return CsrRequest
.Status
;
521 return STATUS_SUCCESS
;
526 BasepNotifyCsrOfThread(IN HANDLE ThreadHandle
,
527 IN PCLIENT_ID ClientId
)
529 ULONG Request
= CREATE_THREAD
;
530 CSR_API_MESSAGE CsrRequest
;
533 DPRINT("BasepNotifyCsrOfThread: Thread: %lx, Handle %lx\n",
534 ClientId
->UniqueThread
, ThreadHandle
);
536 /* Fill out the request */
537 CsrRequest
.Data
.CreateThreadRequest
.ClientId
= *ClientId
;
538 CsrRequest
.Data
.CreateThreadRequest
.ThreadHandle
= ThreadHandle
;
541 Status
= CsrClientCallServer(&CsrRequest
,
543 MAKE_CSR_API(Request
, CSR_NATIVE
),
544 sizeof(CSR_API_MESSAGE
));
545 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
547 DPRINT1("Failed to tell csrss about new thread\n");
548 return CsrRequest
.Status
;
552 return STATUS_SUCCESS
;
556 * Creates the first Thread in a Proces
560 BasepCreateFirstThread(HANDLE ProcessHandle
,
561 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
562 PSECTION_IMAGE_INFORMATION SectionImageInfo
,
565 OBJECT_ATTRIBUTES LocalObjectAttributes
;
566 POBJECT_ATTRIBUTES ObjectAttributes
;
568 INITIAL_TEB InitialTeb
;
572 DPRINT("BasepCreateFirstThread. hProcess: %lx\n", ProcessHandle
);
574 /* Create the Thread's Stack */
575 BaseCreateStack(ProcessHandle
,
576 SectionImageInfo
->MaximumStackSize
,
577 SectionImageInfo
->CommittedStackSize
,
580 /* Create the Thread's Context */
581 BaseInitializeContext(&Context
,
583 SectionImageInfo
->TransferAddress
,
584 InitialTeb
.StackBase
,
587 /* Convert the thread attributes */
588 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
592 /* Create the Kernel Thread Object */
593 Status
= NtCreateThread(&hThread
,
601 if (!NT_SUCCESS(Status
))
606 Status
= BasepNotifyCsrOfThread(hThread
, ClientId
);
607 if (!NT_SUCCESS(Status
))
617 * Converts ANSI to Unicode Environment
621 BasepConvertUnicodeEnvironment(OUT SIZE_T
* EnvSize
,
622 IN PVOID lpEnvironment
)
626 UNICODE_STRING UnicodeEnv
;
629 DPRINT("BasepConvertUnicodeEnvironment\n");
631 /* Scan the environment to calculate its Unicode size */
632 AnsiEnv
.Buffer
= pcScan
= (PCHAR
)lpEnvironment
;
635 pcScan
+= strlen(pcScan
) + 1;
638 /* Create our ANSI String */
639 if (pcScan
== (PCHAR
)lpEnvironment
)
641 AnsiEnv
.Length
= 2 * sizeof(CHAR
);
646 AnsiEnv
.Length
= (USHORT
)((ULONG_PTR
)pcScan
- (ULONG_PTR
)lpEnvironment
+ sizeof(CHAR
));
648 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ 1;
650 /* Allocate memory for the Unicode Environment */
651 UnicodeEnv
.Buffer
= NULL
;
652 *EnvSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
653 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
654 (PVOID
)&UnicodeEnv
.Buffer
,
660 if (!NT_SUCCESS(Status
))
662 SetLastError(Status
);
667 /* Use the allocated size */
668 UnicodeEnv
.MaximumLength
= (USHORT
)*EnvSize
;
671 RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
672 return UnicodeEnv
.Buffer
;
676 * Converts a Win32 Priority Class to NT
680 BasepConvertPriorityClass(IN ULONG dwCreationFlags
)
684 if(dwCreationFlags
& IDLE_PRIORITY_CLASS
)
686 ReturnClass
= PROCESS_PRIORITY_CLASS_IDLE
;
688 else if(dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
690 ReturnClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
692 else if(dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
694 ReturnClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
696 else if(dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
698 ReturnClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
700 else if(dwCreationFlags
& HIGH_PRIORITY_CLASS
)
702 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
704 else if(dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
706 /* Check for Privilege First */
707 if (BasepIsRealtimeAllowed(TRUE
))
709 ReturnClass
= PROCESS_PRIORITY_CLASS_REALTIME
;
713 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
718 ReturnClass
= PROCESS_PRIORITY_CLASS_INVALID
;
725 * Duplicates a standard handle and writes it where requested.
729 BasepDuplicateAndWriteHandle(IN HANDLE ProcessHandle
,
730 IN HANDLE StandardHandle
,
734 HANDLE DuplicatedHandle
;
737 DPRINT("BasepDuplicateAndWriteHandle. hProcess: %lx, Handle: %lx,"
738 "Address: %p\n", ProcessHandle
, StandardHandle
, Address
);
740 /* Don't touch Console Handles */
741 if (IsConsoleHandle(StandardHandle
)) return;
743 /* Duplicate the handle */
744 Status
= NtDuplicateObject(NtCurrentProcess(),
748 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
,
751 if (NT_SUCCESS(Status
))
754 NtWriteVirtualMemory(ProcessHandle
,
764 BasePushProcessParameters(IN ULONG ParameterFlags
,
765 IN HANDLE ProcessHandle
,
767 IN LPCWSTR ApplicationPathName
,
768 IN LPWSTR lpCurrentDirectory
,
769 IN LPWSTR lpCommandLine
,
770 IN LPVOID lpEnvironment
,
771 IN LPSTARTUPINFOW StartupInfo
,
772 IN DWORD CreationFlags
,
773 IN BOOL InheritHandles
,
774 IN ULONG ImageSubsystem
,
775 IN PVOID AppCompatData
,
776 IN ULONG AppCompatDataSize
)
778 WCHAR FullPath
[MAX_PATH
+ 5];
779 PWCHAR Remaining
, DllPathString
, ScanChar
;
780 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
, RemoteParameters
;
781 PVOID RemoteAppCompatData
;
782 UNICODE_STRING DllPath
, ImageName
, CommandLine
, CurrentDirectory
;
783 UNICODE_STRING Desktop
, Shell
, Runtime
, Title
;
787 BOOLEAN HavePebLock
= FALSE
, Result
;
788 PPEB Peb
= NtCurrentPeb();
790 /* Get the full path name */
791 Size
= GetFullPathNameW(ApplicationPathName
,
795 if ((Size
) && (Size
<= (MAX_PATH
+ 4)))
797 /* Get the DLL Path */
798 DllPathString
= BaseComputeProcessDllPath((LPWSTR
)ApplicationPathName
,
803 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
807 /* Initialize Strings */
808 RtlInitUnicodeString(&DllPath
, DllPathString
);
809 RtlInitUnicodeString(&ImageName
, ApplicationPathName
);
813 /* Get the DLL Path */
814 DllPathString
= BaseComputeProcessDllPath(FullPath
, lpEnvironment
);
818 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
822 /* Initialize Strings */
823 RtlInitUnicodeString(&DllPath
, DllPathString
);
824 RtlInitUnicodeString(&ImageName
, FullPath
);
827 /* Initialize Strings */
828 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
829 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
831 /* Initialize more Strings from the Startup Info */
832 if (StartupInfo
->lpDesktop
)
834 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
838 RtlInitUnicodeString(&Desktop
, L
"");
840 if (StartupInfo
->lpReserved
)
842 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
846 RtlInitUnicodeString(&Shell
, L
"");
848 if (StartupInfo
->lpTitle
)
850 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
854 RtlInitUnicodeString(&Title
, ApplicationPathName
);
857 /* This one is special because the length can differ */
858 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
859 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
861 /* Enforce no app compat data if the pointer was NULL */
862 if (!AppCompatData
) AppCompatDataSize
= 0;
864 /* Create the Parameter Block */
865 ProcessParameters
= NULL
;
866 Status
= RtlCreateProcessParameters(&ProcessParameters
,
870 &CurrentDirectory
: NULL
,
877 if (!NT_SUCCESS(Status
)) goto FailPath
;
879 /* Clear the current directory handle if not inheriting */
880 if (!InheritHandles
) ProcessParameters
->CurrentDirectory
.Handle
= NULL
;
882 /* Check if the user passed in an environment */
885 /* We should've made it part of the parameters block, enforce this */
886 ASSERT(ProcessParameters
->Environment
== lpEnvironment
);
887 lpEnvironment
= ProcessParameters
->Environment
;
891 /* The user did not, so use the one from the current PEB */
894 lpEnvironment
= Peb
->ProcessParameters
->Environment
;
897 /* Save pointer and start lookup */
898 ScanChar
= lpEnvironment
;
901 /* Find the environment size */
902 while ((ScanChar
[0]) || (ScanChar
[1])) ++ScanChar
;
903 ScanChar
+= (2 * sizeof(UNICODE_NULL
));
904 EnviroSize
= (ULONG_PTR
)ScanChar
- (ULONG_PTR
)lpEnvironment
;
906 /* Allocate and Initialize new Environment Block */
908 ProcessParameters
->Environment
= NULL
;
909 Status
= ZwAllocateVirtualMemory(ProcessHandle
,
910 (PVOID
*)&ProcessParameters
->Environment
,
915 if (!NT_SUCCESS(Status
)) goto FailPath
;
917 /* Write the Environment Block */
918 Status
= ZwWriteVirtualMemory(ProcessHandle
,
919 ProcessParameters
->Environment
,
924 /* No longer need the PEB lock anymore */
932 /* Check if the write failed */
933 if (!NT_SUCCESS(Status
)) goto FailPath
;
936 /* Write new parameters */
937 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
938 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
939 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
940 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
941 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
942 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
943 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
944 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
945 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
947 /* Write the handles only if we have to */
948 if (StartupInfo
->dwFlags
&
949 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
951 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
952 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
953 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
956 /* Use Special Flags for ConDllInitialize in Kernel32 */
957 if (CreationFlags
& DETACHED_PROCESS
)
959 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
961 else if (CreationFlags
& CREATE_NO_WINDOW
)
963 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
965 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
967 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
971 /* Inherit our Console Handle */
972 ProcessParameters
->ConsoleHandle
= Peb
->ProcessParameters
->ConsoleHandle
;
974 /* Make sure that the shell isn't trampling on our handles first */
975 if (!(StartupInfo
->dwFlags
&
976 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
978 /* Copy the handle if we are inheriting or if it's a console handle */
979 if ((InheritHandles
) ||
980 (IsConsoleHandle(Peb
->ProcessParameters
->StandardInput
)))
982 ProcessParameters
->StandardInput
= Peb
->ProcessParameters
->StandardInput
;
984 if ((InheritHandles
) ||
985 (IsConsoleHandle(Peb
->ProcessParameters
->StandardOutput
)))
987 ProcessParameters
->StandardOutput
= Peb
->ProcessParameters
->StandardOutput
;
989 if ((InheritHandles
) ||
990 (IsConsoleHandle(Peb
->ProcessParameters
->StandardError
)))
992 ProcessParameters
->StandardError
= Peb
->ProcessParameters
->StandardError
;
997 /* Also set the Console Flag */
998 if ((CreationFlags
& CREATE_NEW_PROCESS_GROUP
) &&
999 (!(CreationFlags
& CREATE_NEW_CONSOLE
)))
1001 ProcessParameters
->ConsoleFlags
= 1;
1004 /* See if the first 1MB should be reserved */
1005 if (ParameterFlags
& 1)
1007 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_RESERVE_1MB
;
1010 /* See if the first 16MB should be reserved */
1011 if (ParameterFlags
& 2)
1013 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_RESERVE_16MB
;
1016 /* Allocate memory for the parameter block */
1017 Size
= ProcessParameters
->Length
;
1018 RemoteParameters
= NULL
;
1019 Status
= NtAllocateVirtualMemory(ProcessHandle
,
1020 (PVOID
*)&RemoteParameters
,
1025 if (!NT_SUCCESS(Status
)) goto FailPath
;
1027 /* Set the allocated size */
1028 ProcessParameters
->MaximumLength
= Size
;
1030 /* Handle some Parameter Flags */
1031 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
1032 RTL_USER_PROCESS_PARAMETERS_PROFILE_USER
: 0;
1033 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
1034 RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL
: 0;
1035 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
1036 RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER
: 0;
1037 ProcessParameters
->Flags
|= (Peb
->ProcessParameters
->Flags
&
1038 RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_CHECKS
);
1040 /* Write the Parameter Block */
1041 Status
= NtWriteVirtualMemory(ProcessHandle
,
1044 ProcessParameters
->Length
,
1046 if (!NT_SUCCESS(Status
)) goto FailPath
;
1048 /* Write the PEB Pointer */
1049 Status
= NtWriteVirtualMemory(ProcessHandle
,
1050 &RemotePeb
->ProcessParameters
,
1054 if (!NT_SUCCESS(Status
)) goto FailPath
;
1056 /* Check if there's any app compat data to write */
1057 RemoteAppCompatData
= NULL
;
1060 /* Allocate some space for the application compatibility data */
1061 Size
= AppCompatDataSize
;
1062 Status
= NtAllocateVirtualMemory(ProcessHandle
,
1063 &RemoteAppCompatData
,
1068 if (!NT_SUCCESS(Status
)) goto FailPath
;
1070 /* Write the application compatibility data */
1071 Status
= NtWriteVirtualMemory(ProcessHandle
,
1072 RemoteAppCompatData
,
1076 if (!NT_SUCCESS(Status
)) goto FailPath
;
1079 /* Write the PEB Pointer to the app compat data (might be NULL) */
1080 Status
= NtWriteVirtualMemory(ProcessHandle
,
1081 &RemotePeb
->pShimData
,
1082 &RemoteAppCompatData
,
1085 if (!NT_SUCCESS(Status
)) goto FailPath
;
1087 /* Now write Peb->ImageSubSystem */
1090 NtWriteVirtualMemory(ProcessHandle
,
1091 &RemotePeb
->ImageSubsystem
,
1093 sizeof(ImageSubsystem
),
1102 if (HavePebLock
) RtlReleasePebLock();
1103 RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath
.Buffer
);
1104 if (ProcessParameters
) RtlDestroyProcessParameters(ProcessParameters
);
1107 DPRINT1("Failure to create proecss parameters: %lx\n", Status
);
1108 BaseSetLastNTError(Status
);
1115 InitCommandLines(VOID
)
1119 /* Read the UNICODE_STRING from the PEB */
1120 BaseUnicodeCommandLine
= NtCurrentPeb()->ProcessParameters
->CommandLine
;
1122 /* Convert to ANSI_STRING for the *A callers */
1123 Status
= RtlUnicodeStringToAnsiString(&BaseAnsiCommandLine
,
1124 &BaseUnicodeCommandLine
,
1126 if (!NT_SUCCESS(Status
)) RtlInitEmptyAnsiString(&BaseAnsiCommandLine
, 0, 0);
1129 /* PUBLIC FUNCTIONS ***********************************************************/
1136 GetProcessAffinityMask(IN HANDLE hProcess
,
1137 OUT PDWORD_PTR lpProcessAffinityMask
,
1138 OUT PDWORD_PTR lpSystemAffinityMask
)
1140 PROCESS_BASIC_INFORMATION ProcessInfo
;
1143 /* Query information on the process from the kernel */
1144 Status
= NtQueryInformationProcess(hProcess
,
1145 ProcessBasicInformation
,
1146 (PVOID
)&ProcessInfo
,
1147 sizeof(PROCESS_BASIC_INFORMATION
),
1149 if (!NT_SUCCESS(Status
))
1152 BaseSetLastNTError(Status
);
1156 /* Copy the affinity mask, and get the system one from our shared data */
1157 *lpProcessAffinityMask
= (DWORD
)ProcessInfo
.AffinityMask
;
1158 *lpSystemAffinityMask
= (DWORD
)BaseStaticServerData
->SysInfo
.ActiveProcessorsAffinityMask
;
1167 SetProcessAffinityMask(IN HANDLE hProcess
,
1168 IN DWORD_PTR dwProcessAffinityMask
)
1172 /* Directly set the affinity mask */
1173 Status
= NtSetInformationProcess(hProcess
,
1174 ProcessAffinityMask
,
1175 (PVOID
)&dwProcessAffinityMask
,
1177 if (!NT_SUCCESS(Status
))
1179 /* Handle failure */
1180 BaseSetLastNTError(Status
);
1184 /* Everything was ok */
1193 GetProcessShutdownParameters(OUT LPDWORD lpdwLevel
,
1194 OUT LPDWORD lpdwFlags
)
1196 CSR_API_MESSAGE CsrRequest
;
1199 /* Ask CSRSS for shutdown information */
1200 Status
= CsrClientCallServer(&CsrRequest
,
1202 MAKE_CSR_API(GET_SHUTDOWN_PARAMETERS
, CSR_NATIVE
),
1203 sizeof(CSR_API_MESSAGE
));
1204 if (!(NT_SUCCESS(Status
)) || !(NT_SUCCESS(CsrRequest
.Status
)))
1206 /* Return the failure from CSRSS */
1207 BaseSetLastNTError(CsrRequest
.Status
);
1211 /* Get the data out of the LCP reply */
1212 *lpdwLevel
= CsrRequest
.Data
.GetShutdownParametersRequest
.Level
;
1213 *lpdwFlags
= CsrRequest
.Data
.GetShutdownParametersRequest
.Flags
;
1222 SetProcessShutdownParameters(IN DWORD dwLevel
,
1225 CSR_API_MESSAGE CsrRequest
;
1228 /* Write the data into the CSRSS request and send it */
1229 CsrRequest
.Data
.SetShutdownParametersRequest
.Level
= dwLevel
;
1230 CsrRequest
.Data
.SetShutdownParametersRequest
.Flags
= dwFlags
;
1231 Status
= CsrClientCallServer(&CsrRequest
,
1233 MAKE_CSR_API(SET_SHUTDOWN_PARAMETERS
, CSR_NATIVE
),
1234 sizeof(CSR_API_MESSAGE
));
1235 if (!NT_SUCCESS(Status
) || !NT_SUCCESS(CsrRequest
.Status
))
1237 /* Return the failure from CSRSS */
1238 BaseSetLastNTError(CsrRequest
.Status
);
1251 GetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1252 OUT PSIZE_T lpMinimumWorkingSetSize
,
1253 OUT PSIZE_T lpMaximumWorkingSetSize
,
1256 QUOTA_LIMITS_EX QuotaLimits
;
1259 /* Query the kernel about this */
1260 Status
= NtQueryInformationProcess(hProcess
,
1263 sizeof(QUOTA_LIMITS_EX
),
1265 if (!NT_SUCCESS(Status
))
1268 BaseSetLastNTError(Status
);
1272 /* Copy the quota information out */
1273 *lpMinimumWorkingSetSize
= QuotaLimits
.MinimumWorkingSetSize
;
1274 *lpMaximumWorkingSetSize
= QuotaLimits
.MaximumWorkingSetSize
;
1275 *Flags
= QuotaLimits
.Flags
;
1284 GetProcessWorkingSetSize(IN HANDLE hProcess
,
1285 OUT PSIZE_T lpMinimumWorkingSetSize
,
1286 OUT PSIZE_T lpMaximumWorkingSetSize
)
1289 return GetProcessWorkingSetSizeEx(hProcess
,
1290 lpMinimumWorkingSetSize
,
1291 lpMaximumWorkingSetSize
,
1300 SetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1301 IN SIZE_T dwMinimumWorkingSetSize
,
1302 IN SIZE_T dwMaximumWorkingSetSize
,
1305 QUOTA_LIMITS_EX QuotaLimits
;
1306 NTSTATUS Status
, ReturnStatus
;
1309 ULONG Privilege
= SE_INC_BASE_PRIORITY_PRIVILEGE
;
1311 /* Zero out the input structure */
1312 RtlZeroMemory(&QuotaLimits
, sizeof(QuotaLimits
));
1314 /* Check if the caller sent any limits */
1315 if ((dwMinimumWorkingSetSize
) && (dwMaximumWorkingSetSize
))
1317 /* Write the quota information */
1318 QuotaLimits
.MinimumWorkingSetSize
= dwMinimumWorkingSetSize
;
1319 QuotaLimits
.MaximumWorkingSetSize
= dwMaximumWorkingSetSize
;
1320 QuotaLimits
.Flags
= Flags
;
1322 /* Acquire the required privilege */
1323 Status
= RtlAcquirePrivilege(&Privilege
, 1, 0, &State
);
1325 /* Request the new quotas */
1326 ReturnStatus
= NtSetInformationProcess(hProcess
,
1329 sizeof(QuotaLimits
));
1330 Result
= NT_SUCCESS(ReturnStatus
);
1331 if (NT_SUCCESS(Status
))
1333 /* Release the privilege and set succes code */
1334 ASSERT(State
!= NULL
);
1335 RtlReleasePrivilege(State
);
1341 /* No limits, fail the call */
1342 ReturnStatus
= STATUS_INVALID_PARAMETER
;
1346 /* Return result code, set error code if this was a failure */
1347 if (!Result
) BaseSetLastNTError(ReturnStatus
);
1356 SetProcessWorkingSetSize(IN HANDLE hProcess
,
1357 IN SIZE_T dwMinimumWorkingSetSize
,
1358 IN SIZE_T dwMaximumWorkingSetSize
)
1360 /* Call the newer API */
1361 return SetProcessWorkingSetSizeEx(hProcess
,
1362 dwMinimumWorkingSetSize
,
1363 dwMaximumWorkingSetSize
,
1372 GetProcessTimes(IN HANDLE hProcess
,
1373 IN LPFILETIME lpCreationTime
,
1374 IN LPFILETIME lpExitTime
,
1375 IN LPFILETIME lpKernelTime
,
1376 IN LPFILETIME lpUserTime
)
1378 KERNEL_USER_TIMES Kut
;
1381 /* Query the times */
1382 Status
= NtQueryInformationProcess(hProcess
,
1387 if (!NT_SUCCESS(Status
))
1389 /* Handle failure */
1390 BaseSetLastNTError(Status
);
1394 /* Copy all the times and return success */
1395 lpCreationTime
->dwLowDateTime
= Kut
.CreateTime
.u
.LowPart
;
1396 lpCreationTime
->dwHighDateTime
= Kut
.CreateTime
.u
.HighPart
;
1397 lpExitTime
->dwLowDateTime
= Kut
.ExitTime
.u
.LowPart
;
1398 lpExitTime
->dwHighDateTime
= Kut
.ExitTime
.u
.HighPart
;
1399 lpKernelTime
->dwLowDateTime
= Kut
.KernelTime
.u
.LowPart
;
1400 lpKernelTime
->dwHighDateTime
= Kut
.KernelTime
.u
.HighPart
;
1401 lpUserTime
->dwLowDateTime
= Kut
.UserTime
.u
.LowPart
;
1402 lpUserTime
->dwHighDateTime
= Kut
.UserTime
.u
.HighPart
;
1411 GetCurrentProcess(VOID
)
1413 return (HANDLE
)NtCurrentProcess();
1421 GetCurrentThread(VOID
)
1423 return (HANDLE
)NtCurrentThread();
1431 GetCurrentProcessId(VOID
)
1433 return HandleToUlong(NtCurrentTeb()->ClientId
.UniqueProcess
);
1441 GetExitCodeProcess(IN HANDLE hProcess
,
1442 IN LPDWORD lpExitCode
)
1444 PROCESS_BASIC_INFORMATION ProcessBasic
;
1447 /* Ask the kernel */
1448 Status
= NtQueryInformationProcess(hProcess
,
1449 ProcessBasicInformation
,
1451 sizeof(PROCESS_BASIC_INFORMATION
),
1453 if (!NT_SUCCESS(Status
))
1455 /* We failed, was this because this is a VDM process? */
1456 if (BaseCheckForVDM(hProcess
, lpExitCode
) == TRUE
) return TRUE
;
1458 /* Not a VDM process, fail the call */
1459 BaseSetLastNTError(Status
);
1463 /* Succes case, return the exit code */
1464 *lpExitCode
= (DWORD
)ProcessBasic
.ExitStatus
;
1473 GetProcessId(IN HANDLE Process
)
1475 PROCESS_BASIC_INFORMATION ProcessBasic
;
1478 /* Query the kernel */
1479 Status
= NtQueryInformationProcess(Process
,
1480 ProcessBasicInformation
,
1482 sizeof(PROCESS_BASIC_INFORMATION
),
1484 if (!NT_SUCCESS(Status
))
1486 /* Handle failure */
1487 BaseSetLastNTError(Status
);
1491 /* Return the PID */
1492 return (DWORD
)ProcessBasic
.UniqueProcessId
;
1500 OpenProcess(IN DWORD dwDesiredAccess
,
1501 IN BOOL bInheritHandle
,
1502 IN DWORD dwProcessId
)
1505 HANDLE ProcessHandle
;
1506 OBJECT_ATTRIBUTES ObjectAttributes
;
1509 /* Setup the input client ID structure */
1510 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
1511 ClientId
.UniqueThread
= 0;
1513 /* This is needed just to define the inheritance flags */
1514 InitializeObjectAttributes(&ObjectAttributes
,
1516 (bInheritHandle
? OBJ_INHERIT
: 0),
1520 /* Now try to open the process */
1521 Status
= NtOpenProcess(&ProcessHandle
,
1525 if (!NT_SUCCESS(Status
))
1527 /* Handle failure */
1528 BaseSetLastNTError(Status
);
1532 /* Otherwise return a handle to the process */
1533 return ProcessHandle
;
1541 RegisterWaitForInputIdle(IN WaitForInputIdleType lpfnRegisterWaitForInputIdle
)
1543 /* Write the global function pointer */
1544 UserWaitForInputIdleRoutine
= lpfnRegisterWaitForInputIdle
;
1552 GetStartupInfoW(IN LPSTARTUPINFOW lpStartupInfo
)
1554 PRTL_USER_PROCESS_PARAMETERS Params
;
1556 /* Get the process parameters */
1557 Params
= NtCurrentPeb()->ProcessParameters
;
1559 /* Copy the data out of there */
1560 lpStartupInfo
->cb
= sizeof(STARTUPINFOW
);
1561 lpStartupInfo
->lpReserved
= Params
->ShellInfo
.Buffer
;
1562 lpStartupInfo
->lpDesktop
= Params
->DesktopInfo
.Buffer
;
1563 lpStartupInfo
->lpTitle
= Params
->WindowTitle
.Buffer
;
1564 lpStartupInfo
->dwX
= Params
->StartingX
;
1565 lpStartupInfo
->dwY
= Params
->StartingY
;
1566 lpStartupInfo
->dwXSize
= Params
->CountX
;
1567 lpStartupInfo
->dwYSize
= Params
->CountY
;
1568 lpStartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1569 lpStartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1570 lpStartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1571 lpStartupInfo
->dwFlags
= Params
->WindowFlags
;
1572 lpStartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1573 lpStartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1574 lpStartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1576 /* Check if the standard handles are being used for other features */
1577 if (lpStartupInfo
->dwFlags
& (STARTF_USESTDHANDLES
|
1579 STARTF_SHELLPRIVATE
))
1581 /* These are, so copy the standard handles too */
1582 lpStartupInfo
->hStdInput
= Params
->StandardInput
;
1583 lpStartupInfo
->hStdOutput
= Params
->StandardOutput
;
1584 lpStartupInfo
->hStdError
= Params
->StandardError
;
1593 GetStartupInfoA(IN LPSTARTUPINFOA lpStartupInfo
)
1595 PRTL_USER_PROCESS_PARAMETERS Params
;
1596 ANSI_STRING TitleString
, ShellString
, DesktopString
;
1597 LPSTARTUPINFOA StartupInfo
;
1600 /* Get the cached information as well as the PEB parameters */
1601 StartupInfo
= BaseAnsiStartupInfo
;
1602 Params
= NtCurrentPeb()->ProcessParameters
;
1604 /* Check if this is the first time we have to get the cached version */
1605 while (!StartupInfo
)
1607 /* Create new ANSI startup info */
1608 StartupInfo
= RtlAllocateHeap(RtlGetProcessHeap(),
1610 sizeof(*StartupInfo
));
1613 /* Zero out string pointers in case we fail to create them */
1614 StartupInfo
->lpReserved
= 0;
1615 StartupInfo
->lpDesktop
= 0;
1616 StartupInfo
->lpTitle
= 0;
1619 StartupInfo
->cb
= sizeof(*StartupInfo
);
1621 /* Copy what's already stored in the PEB */
1622 StartupInfo
->dwX
= Params
->StartingX
;
1623 StartupInfo
->dwY
= Params
->StartingY
;
1624 StartupInfo
->dwXSize
= Params
->CountX
;
1625 StartupInfo
->dwYSize
= Params
->CountY
;
1626 StartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1627 StartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1628 StartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1629 StartupInfo
->dwFlags
= Params
->WindowFlags
;
1630 StartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1631 StartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1632 StartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1633 StartupInfo
->hStdInput
= Params
->StandardInput
;
1634 StartupInfo
->hStdOutput
= Params
->StandardOutput
;
1635 StartupInfo
->hStdError
= Params
->StandardError
;
1637 /* Copy shell info string */
1638 Status
= RtlUnicodeStringToAnsiString(&ShellString
,
1641 if (NT_SUCCESS(Status
))
1644 StartupInfo
->lpReserved
= ShellString
.Buffer
;
1646 /* Copy desktop info string */
1647 Status
= RtlUnicodeStringToAnsiString(&DesktopString
,
1648 &Params
->DesktopInfo
,
1650 if (NT_SUCCESS(Status
))
1653 StartupInfo
->lpDesktop
= DesktopString
.Buffer
;
1655 /* Copy window title string */
1656 Status
= RtlUnicodeStringToAnsiString(&TitleString
,
1657 &Params
->WindowTitle
,
1659 if (NT_SUCCESS(Status
))
1662 StartupInfo
->lpTitle
= TitleString
.Buffer
;
1664 /* We finished with the ANSI version, try to cache it */
1665 if (!InterlockedCompareExchangePointer(&BaseAnsiStartupInfo
,
1669 /* We were the first thread through, use the data */
1673 /* Someone beat us to it, use their data instead */
1674 StartupInfo
= BaseAnsiStartupInfo
;
1675 Status
= STATUS_SUCCESS
;
1677 /* We're going to free our own stuff, but not raise */
1678 RtlFreeAnsiString(&TitleString
);
1680 RtlFreeAnsiString(&DesktopString
);
1682 RtlFreeAnsiString(&ShellString
);
1684 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
);
1688 /* No memory, fail */
1689 Status
= STATUS_NO_MEMORY
;
1692 /* Raise an error unless we got here due to the race condition */
1693 if (!NT_SUCCESS(Status
)) RtlRaiseStatus(Status
);
1696 /* Now copy from the cached ANSI version */
1697 lpStartupInfo
->cb
= StartupInfo
->cb
;
1698 lpStartupInfo
->lpReserved
= StartupInfo
->lpReserved
;
1699 lpStartupInfo
->lpDesktop
= StartupInfo
->lpDesktop
;
1700 lpStartupInfo
->lpTitle
= StartupInfo
->lpTitle
;
1701 lpStartupInfo
->dwX
= StartupInfo
->dwX
;
1702 lpStartupInfo
->dwY
= StartupInfo
->dwY
;
1703 lpStartupInfo
->dwXSize
= StartupInfo
->dwXSize
;
1704 lpStartupInfo
->dwYSize
= StartupInfo
->dwYSize
;
1705 lpStartupInfo
->dwXCountChars
= StartupInfo
->dwXCountChars
;
1706 lpStartupInfo
->dwYCountChars
= StartupInfo
->dwYCountChars
;
1707 lpStartupInfo
->dwFillAttribute
= StartupInfo
->dwFillAttribute
;
1708 lpStartupInfo
->dwFlags
= StartupInfo
->dwFlags
;
1709 lpStartupInfo
->wShowWindow
= StartupInfo
->wShowWindow
;
1710 lpStartupInfo
->cbReserved2
= StartupInfo
->cbReserved2
;
1711 lpStartupInfo
->lpReserved2
= StartupInfo
->lpReserved2
;
1713 /* Check if the shell is hijacking the handles for other features */
1714 if (lpStartupInfo
->dwFlags
&
1715 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
1717 /* It isn't, so we can return the raw values */
1718 lpStartupInfo
->hStdInput
= StartupInfo
->hStdInput
;
1719 lpStartupInfo
->hStdOutput
= StartupInfo
->hStdOutput
;
1720 lpStartupInfo
->hStdError
= StartupInfo
->hStdError
;
1724 /* It is, so make sure nobody uses these as console handles */
1725 lpStartupInfo
->hStdInput
= INVALID_HANDLE_VALUE
;
1726 lpStartupInfo
->hStdOutput
= INVALID_HANDLE_VALUE
;
1727 lpStartupInfo
->hStdError
= INVALID_HANDLE_VALUE
;
1736 FlushInstructionCache(IN HANDLE hProcess
,
1737 IN LPCVOID lpBaseAddress
,
1742 /* Call the native function */
1743 Status
= NtFlushInstructionCache(hProcess
, (PVOID
)lpBaseAddress
, dwSize
);
1744 if (!NT_SUCCESS(Status
))
1746 /* Handle failure case */
1747 BaseSetLastNTError(Status
);
1760 ExitProcess(IN UINT uExitCode
)
1762 CSR_API_MESSAGE CsrRequest
;
1763 ASSERT(!BaseRunningInServerProcess
);
1767 /* Acquire the PEB lock */
1768 RtlAcquirePebLock();
1770 /* Kill all the threads */
1771 NtTerminateProcess(NULL
, 0);
1773 /* Unload all DLLs */
1774 LdrShutdownProcess();
1776 /* Notify Base Server of process termination */
1777 CsrClientCallServer(&CsrRequest
,
1779 MAKE_CSR_API(TERMINATE_PROCESS
, CSR_NATIVE
),
1780 sizeof(CSR_API_MESSAGE
));
1782 /* Now do it again */
1783 NtTerminateProcess(NtCurrentProcess(), uExitCode
);
1787 /* Release the PEB lock */
1788 RtlReleasePebLock();
1792 /* should never get here */
1802 TerminateProcess(IN HANDLE hProcess
,
1807 /* Check if no handle was passed in */
1810 /* Set error code */
1811 SetLastError(ERROR_INVALID_HANDLE
);
1815 /* Otherwise, try to terminate the process */
1816 Status
= NtTerminateProcess(hProcess
, uExitCode
);
1817 if (NT_SUCCESS(Status
)) return TRUE
;
1819 /* It failed, convert error code */
1820 BaseSetLastNTError(Status
);
1823 /* This is the failure path */
1832 FatalAppExitA(UINT uAction
,
1833 LPCSTR lpMessageText
)
1835 PUNICODE_STRING MessageTextU
;
1836 ANSI_STRING MessageText
;
1839 /* Initialize the string using the static TEB pointer */
1840 MessageTextU
= &NtCurrentTeb()->StaticUnicodeString
;
1841 RtlInitAnsiString(&MessageText
, (LPSTR
)lpMessageText
);
1843 /* Convert to unicode and just exit normally if this failed */
1844 Status
= RtlAnsiStringToUnicodeString(MessageTextU
, &MessageText
, FALSE
);
1845 if (!NT_SUCCESS(Status
)) ExitProcess(0);
1847 /* Call the Wide function */
1848 FatalAppExitW(uAction
, MessageTextU
->Buffer
);
1856 FatalAppExitW(IN UINT uAction
,
1857 IN LPCWSTR lpMessageText
)
1859 UNICODE_STRING UnicodeString
;
1863 /* Setup the stirng to print out */
1864 RtlInitUnicodeString(&UnicodeString
, lpMessageText
);
1866 /* Display the hard error no matter what */
1867 Status
= NtRaiseHardError(STATUS_FATAL_APP_EXIT
| HARDERROR_OVERRIDE_ERRORMODE
,
1870 (PULONG_PTR
)&UnicodeString
,
1874 /* Give the user a chance to abort */
1875 if ((NT_SUCCESS(Status
)) && (Response
== ResponseCancel
)) return;
1877 /* Otherwise kill the process */
1886 FatalExit(IN
int ExitCode
)
1889 /* On Checked builds, Windows gives you a nice little debugger UI */
1891 DbgPrint("FatalExit...\n");
1896 DbgPrompt( "A (Abort), B (Break), I (Ignore)? ", ch
, sizeof(ch
));
1904 ExitProcess(ExitCode
);
1911 /* On other builds, just kill the process */
1912 ExitProcess(ExitCode
);
1920 GetPriorityClass(IN HANDLE hProcess
)
1923 PROCESS_PRIORITY_CLASS PriorityClass
;
1925 /* Query the kernel */
1926 Status
= NtQueryInformationProcess(hProcess
,
1927 ProcessPriorityClass
,
1929 sizeof(PROCESS_PRIORITY_CLASS
),
1931 if (NT_SUCCESS(Status
))
1933 /* Handle the conversion from NT to Win32 classes */
1934 switch (PriorityClass
.PriorityClass
)
1936 case PROCESS_PRIORITY_CLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
1937 case PROCESS_PRIORITY_CLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
1938 case PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
1939 case PROCESS_PRIORITY_CLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
1940 case PROCESS_PRIORITY_CLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
1941 case PROCESS_PRIORITY_CLASS_NORMAL
: default: return NORMAL_PRIORITY_CLASS
;
1946 BaseSetLastNTError(Status
);
1955 SetPriorityClass(IN HANDLE hProcess
,
1956 IN DWORD dwPriorityClass
)
1960 PROCESS_PRIORITY_CLASS PriorityClass
;
1962 /* Handle conversion from Win32 to NT priority classes */
1963 switch (dwPriorityClass
)
1965 case IDLE_PRIORITY_CLASS
:
1966 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_IDLE
;
1969 case BELOW_NORMAL_PRIORITY_CLASS
:
1970 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
1973 case NORMAL_PRIORITY_CLASS
:
1974 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
1977 case ABOVE_NORMAL_PRIORITY_CLASS
:
1978 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
1981 case HIGH_PRIORITY_CLASS
:
1982 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1985 case REALTIME_PRIORITY_CLASS
:
1986 /* Try to acquire the privilege. If it fails, just use HIGH */
1987 State
= BasepIsRealtimeAllowed(TRUE
);
1988 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1989 PriorityClass
.PriorityClass
+= (State
!= NULL
);
1993 /* Unrecognized priority classes don't make it to the kernel */
1994 SetLastError(ERROR_INVALID_PARAMETER
);
1998 /* Send the request to the kernel, and don't touch the foreground flag */
1999 PriorityClass
.Foreground
= FALSE
;
2000 Status
= NtSetInformationProcess(hProcess
,
2001 ProcessPriorityClass
,
2003 sizeof(PROCESS_PRIORITY_CLASS
));
2005 /* Release the privilege if we had it */
2006 if (State
) RtlReleasePrivilege(State
);
2007 if (!NT_SUCCESS(Status
))
2009 /* Handle error path */
2010 BaseSetLastNTError(Status
);
2023 GetProcessVersion(IN DWORD ProcessId
)
2026 PIMAGE_NT_HEADERS NtHeader
;
2027 PIMAGE_DOS_HEADER DosHeader
;
2029 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
2032 HANDLE ProcessHandle
= NULL
;
2034 USHORT VersionData
[2];
2037 /* We'll be accessing stuff that can fault, so protect everything with SEH */
2040 /* It this an in-process or out-of-process request? */
2041 if (!(ProcessId
) || (GetCurrentProcessId() == ProcessId
))
2043 /* It's in-process, so just read our own header */
2044 NtHeader
= RtlImageNtHeader(NtCurrentPeb()->ImageBaseAddress
);
2047 /* Unable to read the NT header, something is wrong here... */
2048 Status
= STATUS_INVALID_IMAGE_FORMAT
;
2052 /* Get the version straight out of the NT header */
2053 Version
= MAKELONG(NtHeader
->OptionalHeader
.MinorSubsystemVersion
,
2054 NtHeader
->OptionalHeader
.MajorSubsystemVersion
);
2058 /* Out-of-process, so open it */
2059 ProcessHandle
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
,
2062 if (!ProcessHandle
) return 0;
2064 /* Try to find out where its PEB lives */
2065 Status
= NtQueryInformationProcess(ProcessHandle
,
2066 ProcessBasicInformation
,
2068 sizeof(ProcessBasicInfo
),
2071 if (!NT_SUCCESS(Status
)) goto Error
;
2072 Peb
= ProcessBasicInfo
.PebBaseAddress
;
2074 /* Now that we have the PEB, read the image base address out of it */
2075 Result
= ReadProcessMemory(ProcessHandle
,
2076 &Peb
->ImageBaseAddress
,
2078 sizeof(BaseAddress
),
2080 if (!Result
) goto Error
;
2082 /* Now read the e_lfanew (offset to NT header) from the base */
2083 DosHeader
= BaseAddress
;
2084 Result
= ReadProcessMemory(ProcessHandle
,
2085 &DosHeader
->e_lfanew
,
2089 if (!Result
) goto Error
;
2091 /* And finally, read the NT header itself by adding the offset */
2092 NtHeader
= (PVOID
)((ULONG_PTR
)BaseAddress
+ e_lfanew
);
2093 Result
= ReadProcessMemory(ProcessHandle
,
2094 &NtHeader
->OptionalHeader
.MajorSubsystemVersion
,
2096 sizeof(VersionData
),
2098 if (!Result
) goto Error
;
2100 /* Get the version straight out of the NT header */
2101 Version
= MAKELONG(VersionData
[0], VersionData
[1]);
2104 /* If there was an error anywhere, set the last error */
2105 if (!NT_SUCCESS(Status
)) BaseSetLastNTError(Status
);
2110 /* Close the process handle */
2111 if (ProcessHandle
) CloseHandle(ProcessHandle
);
2115 /* And return the version data */
2124 GetProcessIoCounters(IN HANDLE hProcess
,
2125 OUT PIO_COUNTERS lpIoCounters
)
2129 /* Query the kernel. Structures are identical, so let it do the copy too. */
2130 Status
= NtQueryInformationProcess(hProcess
,
2133 sizeof(IO_COUNTERS
),
2135 if (!NT_SUCCESS(Status
))
2137 /* Handle error path */
2138 BaseSetLastNTError(Status
);
2151 GetProcessPriorityBoost(IN HANDLE hProcess
,
2152 OUT PBOOL pDisablePriorityBoost
)
2155 ULONG PriorityBoost
;
2157 /* Query the kernel */
2158 Status
= NtQueryInformationProcess(hProcess
,
2159 ProcessPriorityBoost
,
2163 if (NT_SUCCESS(Status
))
2165 /* Convert from ULONG to a BOOL */
2166 *pDisablePriorityBoost
= PriorityBoost
? TRUE
: FALSE
;
2170 /* Handle error path */
2171 BaseSetLastNTError(Status
);
2180 SetProcessPriorityBoost(IN HANDLE hProcess
,
2181 IN BOOL bDisablePriorityBoost
)
2184 ULONG PriorityBoost
;
2186 /* Enforce that this is a BOOL, and send it to the kernel as a ULONG */
2187 PriorityBoost
= (bDisablePriorityBoost
? TRUE
: FALSE
);
2188 Status
= NtSetInformationProcess(hProcess
,
2189 ProcessPriorityBoost
,
2192 if (!NT_SUCCESS(Status
))
2194 /* Handle error path */
2195 BaseSetLastNTError(Status
);
2208 GetProcessHandleCount(IN HANDLE hProcess
,
2209 OUT PDWORD pdwHandleCount
)
2214 /* Query the kernel */
2215 Status
= NtQueryInformationProcess(hProcess
,
2220 if (NT_SUCCESS(Status
))
2222 /* Copy the count and return sucecss */
2223 *pdwHandleCount
= phc
;
2227 /* Handle error path */
2228 BaseSetLastNTError(Status
);
2237 IsWow64Process(IN HANDLE hProcess
,
2238 OUT PBOOL Wow64Process
)
2243 /* Query the kernel */
2244 Status
= NtQueryInformationProcess(hProcess
,
2245 ProcessWow64Information
,
2249 if (!NT_SUCCESS(Status
))
2251 /* Handle error path */
2252 BaseSetLastNTError(Status
);
2256 /* Enforce this is a BOOL, and return success */
2257 *Wow64Process
= (pbi
!= 0);
2266 GetCommandLineA(VOID
)
2268 return BaseAnsiCommandLine
.Buffer
;
2276 GetCommandLineW(VOID
)
2278 return BaseUnicodeCommandLine
.Buffer
;
2286 ReadProcessMemory(IN HANDLE hProcess
,
2287 IN LPCVOID lpBaseAddress
,
2290 OUT SIZE_T
* lpNumberOfBytesRead
)
2295 Status
= NtReadVirtualMemory(hProcess
,
2296 (PVOID
)lpBaseAddress
,
2301 /* In user-mode, this parameter is optional */
2302 if (lpNumberOfBytesRead
) *lpNumberOfBytesRead
= nSize
;
2303 if (!NT_SUCCESS(Status
))
2306 BaseSetLastNTError(Status
);
2310 /* Return success */
2319 WriteProcessMemory(IN HANDLE hProcess
,
2320 IN LPVOID lpBaseAddress
,
2321 IN LPCVOID lpBuffer
,
2323 OUT SIZE_T
*lpNumberOfBytesWritten
)
2331 /* Set parameters for protect call */
2333 Base
= lpBaseAddress
;
2335 /* Check the current status */
2336 Status
= NtProtectVirtualMemory(hProcess
,
2339 PAGE_EXECUTE_READWRITE
,
2341 if (NT_SUCCESS(Status
))
2343 /* Check if we are unprotecting */
2344 UnProtect
= OldValue
& (PAGE_READWRITE
|
2346 PAGE_EXECUTE_READWRITE
|
2347 PAGE_EXECUTE_WRITECOPY
) ? FALSE
: TRUE
;
2350 /* Set the new protection */
2351 Status
= NtProtectVirtualMemory(hProcess
,
2357 /* Write the memory */
2358 Status
= NtWriteVirtualMemory(hProcess
,
2364 /* In Win32, the parameter is optional, so handle this case */
2365 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2367 if (!NT_SUCCESS(Status
))
2370 BaseSetLastNTError(Status
);
2374 /* Flush the ITLB */
2375 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2380 /* Check if we were read only */
2381 if (OldValue
& (PAGE_NOACCESS
| PAGE_READONLY
))
2383 /* Restore protection and fail */
2384 NtProtectVirtualMemory(hProcess
,
2389 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2391 /* Note: This is what Windows returns and code depends on it */
2392 return STATUS_ACCESS_VIOLATION
;
2395 /* Otherwise, do the write */
2396 Status
= NtWriteVirtualMemory(hProcess
,
2402 /* In Win32, the parameter is optional, so handle this case */
2403 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2405 /* And restore the protection */
2406 NtProtectVirtualMemory(hProcess
,
2411 if (!NT_SUCCESS(Status
))
2414 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2416 /* Note: This is what Windows returns and code depends on it */
2417 return STATUS_ACCESS_VIOLATION
;
2420 /* Flush the ITLB */
2421 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2428 BaseSetLastNTError(Status
);
2438 ProcessIdToSessionId(IN DWORD dwProcessId
,
2439 OUT PDWORD pSessionId
)
2441 PROCESS_SESSION_INFORMATION SessionInformation
;
2442 OBJECT_ATTRIBUTES ObjectAttributes
;
2444 HANDLE ProcessHandle
;
2447 /* Do a quick check if the pointer is not writable */
2448 if (IsBadWritePtr(pSessionId
, sizeof(DWORD
)))
2451 SetLastError(ERROR_INVALID_PARAMETER
);
2455 /* Open the process passed in by ID */
2456 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
2457 ClientId
.UniqueThread
= 0;
2458 InitializeObjectAttributes(&ObjectAttributes
, NULL
, 0, NULL
, NULL
);
2459 Status
= NtOpenProcess(&ProcessHandle
,
2460 PROCESS_QUERY_INFORMATION
,
2463 if (NT_SUCCESS(Status
))
2465 /* Query the session ID from the kernel */
2466 Status
= NtQueryInformationProcess(ProcessHandle
,
2467 ProcessSessionInformation
,
2468 &SessionInformation
,
2469 sizeof(SessionInformation
),
2472 /* Close the handle and check if we suceeded */
2473 NtClose(ProcessHandle
);
2474 if (NT_SUCCESS(Status
))
2476 /* Return the session ID */
2477 *pSessionId
= SessionInformation
.SessionId
;
2482 /* Set error code and fail */
2483 BaseSetLastNTError(Status
);
2492 CreateProcessInternalW(HANDLE hToken
,
2493 LPCWSTR lpApplicationName
,
2494 LPWSTR lpCommandLine
,
2495 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
2496 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
2497 BOOL bInheritHandles
,
2498 DWORD dwCreationFlags
,
2499 LPVOID lpEnvironment
,
2500 LPCWSTR lpCurrentDirectory
,
2501 LPSTARTUPINFOW lpStartupInfo
,
2502 LPPROCESS_INFORMATION lpProcessInformation
,
2506 PROCESS_PRIORITY_CLASS PriorityClass
;
2507 BOOLEAN FoundQuotes
= FALSE
;
2508 BOOLEAN QuotesNeeded
= FALSE
;
2509 BOOLEAN CmdLineIsAppName
= FALSE
;
2510 UNICODE_STRING ApplicationName
= { 0, 0, NULL
};
2511 OBJECT_ATTRIBUTES LocalObjectAttributes
;
2512 POBJECT_ATTRIBUTES ObjectAttributes
;
2513 HANDLE hSection
= NULL
, hProcess
= NULL
, hThread
= NULL
, hDebug
= NULL
;
2514 SECTION_IMAGE_INFORMATION SectionImageInfo
;
2515 LPWSTR CurrentDirectory
= NULL
;
2516 LPWSTR CurrentDirectoryPart
;
2517 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
2518 STARTUPINFOW StartupInfo
;
2520 LPWSTR BatchCommandLine
;
2521 ULONG CmdLineLength
;
2522 UNICODE_STRING CommandLineString
;
2524 LPWSTR QuotedCmdLine
= NULL
;
2526 LPWSTR NullBuffer
= NULL
;
2527 LPWSTR NameBuffer
= NULL
;
2531 BOOLEAN SearchDone
= FALSE
;
2532 BOOLEAN Escape
= FALSE
;
2534 PPEB OurPeb
= NtCurrentPeb();
2539 /* FIXME should process
2540 * HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
2541 * key (see http://blogs.msdn.com/oldnewthing/archive/2005/12/19/505449.aspx)
2544 DPRINT("CreateProcessW: lpApplicationName: %S lpCommandLine: %S"
2545 " lpEnvironment: %p lpCurrentDirectory: %S dwCreationFlags: %lx\n",
2546 lpApplicationName
, lpCommandLine
, lpEnvironment
, lpCurrentDirectory
,
2549 /* Flags we don't handle yet */
2550 if (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
)
2552 DPRINT1("CREATE_SEPARATE_WOW_VDM not handled\n");
2554 if (dwCreationFlags
& CREATE_SHARED_WOW_VDM
)
2556 DPRINT1("CREATE_SHARED_WOW_VDM not handled\n");
2558 if (dwCreationFlags
& CREATE_FORCEDOS
)
2560 DPRINT1("CREATE_FORCEDOS not handled\n");
2563 /* Fail on this flag, it's only valid with the WithLogonW function */
2564 if (dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
)
2566 DPRINT1("Invalid flag used\n");
2567 SetLastError(ERROR_INVALID_PARAMETER
);
2571 /* This combination is illegal (see MSDN) */
2572 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
2573 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
2575 DPRINT1("Invalid flag combo used\n");
2576 SetLastError(ERROR_INVALID_PARAMETER
);
2580 /* Another illegal combo */
2581 if ((dwCreationFlags
& (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
)) ==
2582 (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
))
2584 DPRINT1("Invalid flag combo used\n");
2585 SetLastError(ERROR_INVALID_PARAMETER
);
2589 if (lpCurrentDirectory
)
2591 if ((GetFileAttributesW(lpCurrentDirectory
) == INVALID_FILE_ATTRIBUTES
) ||
2592 !(GetFileAttributesW(lpCurrentDirectory
) & FILE_ATTRIBUTE_DIRECTORY
))
2594 SetLastError(ERROR_DIRECTORY
);
2600 * We're going to modify and mask out flags and stuff in lpStartupInfo,
2601 * so we'll use our own local copy for that.
2603 StartupInfo
= *lpStartupInfo
;
2605 /* FIXME: Use default Separate/Shared VDM Flag */
2607 /* If we are inside a Job, use Separate VDM so it won't escape the Job */
2608 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
2610 if (NtIsProcessInJob(NtCurrentProcess(), NULL
))
2612 /* Remove the shared flag and add the separate flag. */
2613 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
2614 CREATE_SEPARATE_WOW_VDM
;
2619 * According to some sites, ShellExecuteEx uses an undocumented flag to
2620 * send private handle data (such as HMONITOR or HICON). See:
2621 * www.catch22.net/tuts/undoc01.asp. This implies that we can't use the
2622 * standard handles anymore since we'd be overwriting this private data
2624 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
2625 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
2627 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
2630 /* Start by zeroing out the fields */
2631 RtlZeroMemory(lpProcessInformation
, sizeof(PROCESS_INFORMATION
));
2633 /* Easy stuff first, convert the process priority class */
2634 PriorityClass
.Foreground
= FALSE
;
2635 PriorityClass
.PriorityClass
= (UCHAR
)BasepConvertPriorityClass(dwCreationFlags
);
2639 /* Search for escape sequences */
2640 ScanString
= lpCommandLine
;
2641 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
2644 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\"')
2652 /* Get the application name and do all the proper formating necessary */
2654 /* See if we have an application name (oh please let us have one!) */
2655 if (!lpApplicationName
)
2657 /* The fun begins */
2658 NameBuffer
= RtlAllocateHeap(RtlGetProcessHeap(),
2660 MAX_PATH
* sizeof(WCHAR
));
2661 if (NameBuffer
== NULL
)
2663 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2667 /* This is all we have to work with :( */
2668 lpApplicationName
= lpCommandLine
;
2670 /* Initialize our friends at the beginning */
2671 NullBuffer
= (LPWSTR
)lpApplicationName
;
2672 ScanString
= (LPWSTR
)lpApplicationName
;
2674 /* We will start by looking for a quote */
2675 if (*ScanString
== L
'\"')
2677 /* That was quick */
2680 /* Advance past quote */
2682 lpApplicationName
= ScanString
;
2684 /* Find the closing quote */
2687 if (*ScanString
== L
'\"' && *(ScanString
- 1) != L
'^')
2690 NullBuffer
= ScanString
;
2697 NullBuffer
= ScanString
;
2702 /* No quotes, so we'll be looking for white space */
2704 /* Reset the pointer */
2705 lpApplicationName
= lpCommandLine
;
2707 /* Find whitespace of Tab */
2710 if (*ScanString
== ' ' || *ScanString
== '\t')
2713 NullBuffer
= ScanString
;
2719 NullBuffer
= ScanString
;
2723 /* Set the Null Buffer */
2724 SaveChar
= *NullBuffer
;
2725 *NullBuffer
= UNICODE_NULL
;
2727 /* Do a search for the file */
2728 DPRINT("Ready for SearchPathW: %S\n", lpApplicationName
);
2729 RetVal
= SearchPathW(NULL
,
2734 NULL
) * sizeof(WCHAR
);
2736 /* Did it find something? */
2739 /* Get file attributes */
2740 ULONG Attributes
= GetFileAttributesW(NameBuffer
);
2741 if (Attributes
& FILE_ATTRIBUTE_DIRECTORY
)
2743 /* Give it a length of 0 to fail, this was a directory. */
2749 RetVal
+= sizeof(WCHAR
);
2753 /* Now check if we have a file, and if the path size is OK */
2754 if (!RetVal
|| RetVal
>= (MAX_PATH
* sizeof(WCHAR
)))
2759 /* We failed, try to get the Path Type */
2760 DPRINT("SearchPathW failed. Retval: %ld\n", RetVal
);
2761 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
2763 /* If it's not relative, try to get the error */
2764 if (PathType
!= RtlPathTypeRelative
)
2766 /* This should fail, and give us a detailed LastError */
2767 hFile
= CreateFileW(lpApplicationName
,
2769 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
2772 FILE_ATTRIBUTE_NORMAL
,
2775 /* Did it actually NOT fail? */
2776 if (hFile
!= INVALID_HANDLE_VALUE
)
2778 /* Fake the error */
2780 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2785 /* Immediately set the error */
2786 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2789 /* Did we already fail once? */
2792 SetLastError(Error
);
2796 /* Not yet, cache it */
2797 Error
= GetLastError();
2800 /* Put back the command line */
2801 *NullBuffer
= SaveChar
;
2802 lpApplicationName
= NameBuffer
;
2805 * If the search isn't done and we still have cmdline
2806 * then start over. Ex: c:\ha ha ha\haha.exe
2808 if (*ScanString
&& !SearchDone
)
2810 /* Move in the buffer */
2812 NullBuffer
= ScanString
;
2814 /* We will have to add a quote, since there is a space*/
2815 QuotesNeeded
= TRUE
;
2817 /* And we will also fake the fact we found one */
2824 /* We totally failed */
2828 /* Put back the command line */
2829 *NullBuffer
= SaveChar
;
2830 lpApplicationName
= NameBuffer
;
2831 DPRINT("SearchPathW suceeded (%ld): %S\n", RetVal
, NameBuffer
);
2833 else if (!lpCommandLine
|| *lpCommandLine
== UNICODE_NULL
)
2835 /* We have an app name (good!) but no command line */
2836 CmdLineIsAppName
= TRUE
;
2837 lpCommandLine
= (LPWSTR
)lpApplicationName
;
2840 /* At this point the name has been toyed with enough to be openable */
2841 Status
= BasepMapFile(lpApplicationName
, &hSection
, &ApplicationName
);
2843 /* Check for failure */
2844 if (!NT_SUCCESS(Status
))
2846 /* Could be a non-PE File */
2849 /* Check if the Kernel tells us it's not even valid MZ */
2850 case STATUS_INVALID_IMAGE_NE_FORMAT
:
2851 case STATUS_INVALID_IMAGE_PROTECT
:
2852 case STATUS_INVALID_IMAGE_NOT_MZ
:
2855 /* If it's a DOS app, use VDM */
2856 if ((BasepCheckDosApp(&ApplicationName
)))
2858 DPRINT1("Launching VDM...\n");
2859 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2860 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2861 return CreateProcessW(L
"ntvdm.exe",
2862 (LPWSTR
)((ULONG_PTR
)lpApplicationName
), /* FIXME: Buffer must be writable!!! */
2863 lpProcessAttributes
,
2870 lpProcessInformation
);
2873 /* It's a batch file */
2874 Extension
= &ApplicationName
.Buffer
[ApplicationName
.Length
/
2877 /* Make sure the extensions are correct */
2878 if (_wcsnicmp(Extension
, L
".bat", 4) && _wcsnicmp(Extension
, L
".cmd", 4))
2880 SetLastError(ERROR_BAD_EXE_FORMAT
);
2884 /* Calculate the length of the command line */
2885 CmdLineLength
= wcslen(CMD_STRING
) + wcslen(lpCommandLine
) + 1;
2887 /* If we found quotes, then add them into the length size */
2888 if (CmdLineIsAppName
|| FoundQuotes
) CmdLineLength
+= 2;
2889 CmdLineLength
*= sizeof(WCHAR
);
2891 /* Allocate space for the new command line */
2892 BatchCommandLine
= RtlAllocateHeap(RtlGetProcessHeap(),
2895 if (BatchCommandLine
== NULL
)
2897 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2902 wcscpy(BatchCommandLine
, CMD_STRING
);
2903 if (CmdLineIsAppName
|| FoundQuotes
)
2905 wcscat(BatchCommandLine
, L
"\"");
2907 wcscat(BatchCommandLine
, lpCommandLine
);
2908 if (CmdLineIsAppName
|| FoundQuotes
)
2910 wcscat(BatchCommandLine
, L
"\"");
2913 /* Create it as a Unicode String */
2914 RtlInitUnicodeString(&CommandLineString
, BatchCommandLine
);
2916 /* Set the command line to this */
2917 lpCommandLine
= CommandLineString
.Buffer
;
2918 lpApplicationName
= NULL
;
2921 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2922 ApplicationName
.Buffer
= NULL
;
2926 case STATUS_INVALID_IMAGE_WIN_16
:
2928 /* It's a Win16 Image, use VDM */
2929 DPRINT1("Launching VDM...\n");
2930 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2931 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2932 return CreateProcessW(L
"ntvdm.exe",
2933 (LPWSTR
)((ULONG_PTR
)lpApplicationName
), /* FIXME: Buffer must be writable!!! */
2934 lpProcessAttributes
,
2941 lpProcessInformation
);
2943 case STATUS_OBJECT_NAME_NOT_FOUND
:
2944 case STATUS_OBJECT_PATH_NOT_FOUND
:
2945 BaseSetLastNTError(Status
);
2949 /* Invalid Image Type */
2950 SetLastError(ERROR_BAD_EXE_FORMAT
);
2955 /* Use our desktop if we didn't get any */
2956 if (!StartupInfo
.lpDesktop
)
2958 StartupInfo
.lpDesktop
= OurPeb
->ProcessParameters
->DesktopInfo
.Buffer
;
2961 /* FIXME: Check if Application is allowed to run */
2963 /* FIXME: Allow CREATE_SEPARATE only for WOW Apps, once we have that. */
2965 /* Get some information about the executable */
2966 Status
= ZwQuerySection(hSection
,
2967 SectionImageInformation
,
2969 sizeof(SectionImageInfo
),
2971 if(!NT_SUCCESS(Status
))
2973 DPRINT1("Unable to get SectionImageInformation, status 0x%x\n", Status
);
2974 BaseSetLastNTError(Status
);
2978 /* Don't execute DLLs */
2979 if (SectionImageInfo
.ImageCharacteristics
& IMAGE_FILE_DLL
)
2981 DPRINT1("Can't execute a DLL\n");
2982 SetLastError(ERROR_BAD_EXE_FORMAT
);
2986 /* FIXME: Check for Debugger */
2988 /* FIXME: Check if Machine Type and SubSys Version Match */
2990 /* We don't support POSIX or anything else for now */
2991 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
!= SectionImageInfo
.SubSystemType
&&
2992 IMAGE_SUBSYSTEM_WINDOWS_CUI
!= SectionImageInfo
.SubSystemType
)
2994 DPRINT1("Invalid subsystem %d\n", SectionImageInfo
.SubSystemType
);
2995 SetLastError(ERROR_BAD_EXE_FORMAT
);
2999 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
== SectionImageInfo
.SubSystemType
)
3001 /* Do not create a console for GUI applications */
3002 dwCreationFlags
&= ~CREATE_NEW_CONSOLE
;
3003 dwCreationFlags
|= DETACHED_PROCESS
;
3006 /* Initialize the process object attributes */
3007 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
3008 lpProcessAttributes
,
3011 /* Check if we're going to be debugged */
3012 if (dwCreationFlags
& DEBUG_PROCESS
)
3014 /* FIXME: Set process flag */
3017 /* Check if we're going to be debugged */
3018 if (dwCreationFlags
& (DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
))
3020 /* Connect to DbgUi */
3021 Status
= DbgUiConnectToDbg();
3022 if (!NT_SUCCESS(Status
))
3024 DPRINT1("Failed to connect to DbgUI!\n");
3025 BaseSetLastNTError(Status
);
3029 /* Get the debug object */
3030 hDebug
= DbgUiGetThreadDebugObject();
3032 /* Check if only this process will be debugged */
3033 if (dwCreationFlags
& DEBUG_ONLY_THIS_PROCESS
)
3035 /* FIXME: Set process flag */
3039 /* Create the Process */
3040 Status
= NtCreateProcess(&hProcess
,
3044 (BOOLEAN
)bInheritHandles
,
3048 if (!NT_SUCCESS(Status
))
3050 DPRINT1("Unable to create process, status 0x%x\n", Status
);
3051 BaseSetLastNTError(Status
);
3055 if (PriorityClass
.PriorityClass
!= PROCESS_PRIORITY_CLASS_INVALID
)
3058 Status
= NtSetInformationProcess(hProcess
,
3059 ProcessPriorityClass
,
3061 sizeof(PROCESS_PRIORITY_CLASS
));
3062 if(!NT_SUCCESS(Status
))
3064 DPRINT1("Unable to set new process priority, status 0x%x\n", Status
);
3065 BaseSetLastNTError(Status
);
3070 /* Set Error Mode */
3071 if (dwCreationFlags
& CREATE_DEFAULT_ERROR_MODE
)
3073 ULONG ErrorMode
= SEM_FAILCRITICALERRORS
;
3074 NtSetInformationProcess(hProcess
,
3075 ProcessDefaultHardErrorMode
,
3080 /* Convert the directory to a full path */
3081 if (lpCurrentDirectory
)
3083 /* Allocate a buffer */
3084 CurrentDirectory
= RtlAllocateHeap(RtlGetProcessHeap(),
3086 (MAX_PATH
+ 1) * sizeof(WCHAR
));
3087 if (CurrentDirectory
== NULL
)
3089 DPRINT1("Cannot allocate memory for directory name\n");
3090 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3094 /* Get the length */
3095 if (GetFullPathNameW(lpCurrentDirectory
,
3098 &CurrentDirectoryPart
) > MAX_PATH
)
3100 DPRINT1("Directory name too long\n");
3101 SetLastError(ERROR_DIRECTORY
);
3106 /* Insert quotes if needed */
3107 if (QuotesNeeded
|| CmdLineIsAppName
)
3109 /* Allocate a buffer */
3110 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3112 (wcslen(lpCommandLine
) + 2 + 1) *
3114 if (QuotedCmdLine
== NULL
)
3116 DPRINT1("Cannot allocate memory for quoted command line\n");
3117 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3121 /* Copy the first quote */
3122 wcscpy(QuotedCmdLine
, L
"\"");
3124 /* Save a null char */
3127 SaveChar
= *NullBuffer
;
3128 *NullBuffer
= UNICODE_NULL
;
3131 /* Add the command line and the finishing quote */
3132 wcscat(QuotedCmdLine
, lpCommandLine
);
3133 wcscat(QuotedCmdLine
, L
"\"");
3135 /* Add the null char */
3138 *NullBuffer
= SaveChar
;
3139 wcscat(QuotedCmdLine
, NullBuffer
);
3142 DPRINT("Quoted CmdLine: %S\n", QuotedCmdLine
);
3147 if (QuotedCmdLine
== NULL
)
3149 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3151 (wcslen(lpCommandLine
) + 1) * sizeof(WCHAR
));
3152 if (QuotedCmdLine
== NULL
)
3154 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3157 wcscpy(QuotedCmdLine
, lpCommandLine
);
3160 ScanString
= QuotedCmdLine
;
3161 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
3164 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\\')
3166 memmove(ScanString
-1, ScanString
, wcslen(ScanString
) * sizeof(WCHAR
) + sizeof(WCHAR
));
3171 /* Get the Process Information */
3172 Status
= NtQueryInformationProcess(hProcess
,
3173 ProcessBasicInformation
,
3175 sizeof(ProcessBasicInfo
),
3178 /* Convert the environment */
3179 if(lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3181 lpEnvironment
= BasepConvertUnicodeEnvironment(&EnvSize
, lpEnvironment
);
3182 if (!lpEnvironment
) goto Cleanup
;
3185 /* Create Process Environment */
3186 RemotePeb
= ProcessBasicInfo
.PebBaseAddress
;
3187 Ret
= BasePushProcessParameters(0,
3190 (LPWSTR
)lpApplicationName
,
3192 (QuotesNeeded
|| CmdLineIsAppName
|| Escape
) ?
3193 QuotedCmdLine
: lpCommandLine
,
3201 if (!Ret
) goto Cleanup
;
3203 /* Cleanup Environment */
3204 if (lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3206 RtlDestroyEnvironment(lpEnvironment
);
3209 /* Close the section */
3213 /* Duplicate the handles if needed */
3214 if (!bInheritHandles
&& !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
3215 SectionImageInfo
.SubSystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
3217 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
;
3219 /* Get the remote parameters */
3220 Status
= NtReadVirtualMemory(hProcess
,
3221 &RemotePeb
->ProcessParameters
,
3225 if (!NT_SUCCESS(Status
))
3227 DPRINT1("Failed to read memory\n");
3231 /* Duplicate and write the handles */
3232 BasepDuplicateAndWriteHandle(hProcess
,
3233 OurPeb
->ProcessParameters
->StandardInput
,
3234 &RemoteParameters
->StandardInput
);
3235 BasepDuplicateAndWriteHandle(hProcess
,
3236 OurPeb
->ProcessParameters
->StandardOutput
,
3237 &RemoteParameters
->StandardOutput
);
3238 BasepDuplicateAndWriteHandle(hProcess
,
3239 OurPeb
->ProcessParameters
->StandardError
,
3240 &RemoteParameters
->StandardError
);
3244 Status
= BasepNotifyCsrOfCreation(dwCreationFlags
,
3245 (HANDLE
)ProcessBasicInfo
.UniqueProcessId
,
3248 if (!NT_SUCCESS(Status
))
3250 DPRINT1("CSR Notification Failed\n");
3251 BaseSetLastNTError(Status
);
3255 /* Create the first thread */
3256 DPRINT("Creating thread for process (EntryPoint = 0x%p)\n",
3257 SectionImageInfo
.TransferAddress
);
3258 hThread
= BasepCreateFirstThread(hProcess
,
3263 if (hThread
== NULL
)
3265 DPRINT1("Could not create Initial Thread\n");
3266 /* FIXME - set last error code */
3270 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
3272 NtResumeThread(hThread
, &Dummy
);
3276 lpProcessInformation
->dwProcessId
= (DWORD
)ClientId
.UniqueProcess
;
3277 lpProcessInformation
->dwThreadId
= (DWORD
)ClientId
.UniqueThread
;
3278 lpProcessInformation
->hProcess
= hProcess
;
3279 lpProcessInformation
->hThread
= hThread
;
3280 DPRINT("hThread[%p]: %p inside hProcess[%p]: %p\n", hThread
,
3281 ClientId
.UniqueThread
, ClientId
.UniqueProcess
, hProcess
);
3282 hProcess
= hThread
= NULL
;
3286 /* De-allocate heap strings */
3287 if (NameBuffer
) RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
3288 if (ApplicationName
.Buffer
)
3289 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
3290 if (CurrentDirectory
) RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentDirectory
);
3291 if (QuotedCmdLine
) RtlFreeHeap(RtlGetProcessHeap(), 0, QuotedCmdLine
);
3293 /* Kill any handles still alive */
3294 if (hSection
) NtClose(hSection
);
3297 /* We don't know any more details then this */
3298 NtTerminateProcess(hProcess
, STATUS_UNSUCCESSFUL
);
3301 if (hProcess
) NtClose(hProcess
);
3303 /* Return Success */
3312 CreateProcessW(LPCWSTR lpApplicationName
,
3313 LPWSTR lpCommandLine
,
3314 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3315 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3316 BOOL bInheritHandles
,
3317 DWORD dwCreationFlags
,
3318 LPVOID lpEnvironment
,
3319 LPCWSTR lpCurrentDirectory
,
3320 LPSTARTUPINFOW lpStartupInfo
,
3321 LPPROCESS_INFORMATION lpProcessInformation
)
3323 /* Call the internal (but exported) version */
3324 return CreateProcessInternalW(0,
3327 lpProcessAttributes
,
3334 lpProcessInformation
,
3343 CreateProcessInternalA(HANDLE hToken
,
3344 LPCSTR lpApplicationName
,
3345 LPSTR lpCommandLine
,
3346 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3347 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3348 BOOL bInheritHandles
,
3349 DWORD dwCreationFlags
,
3350 LPVOID lpEnvironment
,
3351 LPCSTR lpCurrentDirectory
,
3352 LPSTARTUPINFOA lpStartupInfo
,
3353 LPPROCESS_INFORMATION lpProcessInformation
,
3356 PUNICODE_STRING CommandLine
= NULL
;
3357 UNICODE_STRING DummyString
;
3358 UNICODE_STRING LiveCommandLine
;
3359 UNICODE_STRING ApplicationName
;
3360 UNICODE_STRING CurrentDirectory
;
3362 STARTUPINFOW StartupInfo
;
3364 DPRINT("dwCreationFlags %x, lpEnvironment %x, lpCurrentDirectory %x, "
3365 "lpStartupInfo %x, lpProcessInformation %x\n",
3366 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
3367 lpStartupInfo
, lpProcessInformation
);
3369 /* Copy Startup Info */
3370 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
3372 /* Initialize all strings to nothing */
3373 LiveCommandLine
.Buffer
= NULL
;
3374 DummyString
.Buffer
= NULL
;
3375 ApplicationName
.Buffer
= NULL
;
3376 CurrentDirectory
.Buffer
= NULL
;
3377 StartupInfo
.lpDesktop
= NULL
;
3378 StartupInfo
.lpReserved
= NULL
;
3379 StartupInfo
.lpTitle
= NULL
;
3381 /* Convert the Command line */
3384 /* If it's too long, then we'll have a problem */
3385 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
3386 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
3388 /* Cache it in the TEB */
3389 CommandLine
= Basep8BitStringToStaticUnicodeString(lpCommandLine
);
3393 /* Use a dynamic version */
3394 Basep8BitStringToDynamicUnicodeString(&LiveCommandLine
,
3400 /* The logic below will use CommandLine, so we must make it valid */
3401 CommandLine
= &DummyString
;
3404 /* Convert the Name and Directory */
3405 if (lpApplicationName
)
3407 Basep8BitStringToDynamicUnicodeString(&ApplicationName
,
3410 if (lpCurrentDirectory
)
3412 Basep8BitStringToDynamicUnicodeString(&CurrentDirectory
,
3413 lpCurrentDirectory
);
3416 /* Now convert Startup Strings */
3417 if (lpStartupInfo
->lpReserved
)
3419 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
3420 &StartupInfo
.lpReserved
);
3422 if (lpStartupInfo
->lpDesktop
)
3424 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
3425 &StartupInfo
.lpDesktop
);
3427 if (lpStartupInfo
->lpTitle
)
3429 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
3430 &StartupInfo
.lpTitle
);
3433 /* Call the Unicode function */
3434 bRetVal
= CreateProcessInternalW(hToken
,
3435 ApplicationName
.Buffer
,
3436 LiveCommandLine
.Buffer
?
3437 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
3438 lpProcessAttributes
,
3443 CurrentDirectory
.Buffer
,
3445 lpProcessInformation
,
3449 RtlFreeUnicodeString(&ApplicationName
);
3450 RtlFreeUnicodeString(&LiveCommandLine
);
3451 RtlFreeUnicodeString(&CurrentDirectory
);
3452 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpDesktop
);
3453 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpReserved
);
3454 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpTitle
);
3456 /* Return what Unicode did */
3461 * FUNCTION: The CreateProcess function creates a new process and its
3462 * primary thread. The new process executes the specified executable file
3465 * lpApplicationName = Pointer to name of executable module
3466 * lpCommandLine = Pointer to command line string
3467 * lpProcessAttributes = Process security attributes
3468 * lpThreadAttributes = Thread security attributes
3469 * bInheritHandles = Handle inheritance flag
3470 * dwCreationFlags = Creation flags
3471 * lpEnvironment = Pointer to new environment block
3472 * lpCurrentDirectory = Pointer to current directory name
3473 * lpStartupInfo = Pointer to startup info
3474 * lpProcessInformation = Pointer to process information
3480 CreateProcessA(LPCSTR lpApplicationName
,
3481 LPSTR lpCommandLine
,
3482 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3483 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3484 BOOL bInheritHandles
,
3485 DWORD dwCreationFlags
,
3486 LPVOID lpEnvironment
,
3487 LPCSTR lpCurrentDirectory
,
3488 LPSTARTUPINFOA lpStartupInfo
,
3489 LPPROCESS_INFORMATION lpProcessInformation
)
3491 /* Call the internal (but exported) version */
3492 return CreateProcessInternalA(0,
3495 lpProcessAttributes
,
3502 lpProcessInformation
,
3511 WinExec(LPCSTR lpCmdLine
,
3514 STARTUPINFOA StartupInfo
;
3515 PROCESS_INFORMATION ProcessInformation
;
3518 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
3519 StartupInfo
.cb
= sizeof(STARTUPINFOA
);
3520 StartupInfo
.wShowWindow
= (WORD
)uCmdShow
;
3521 StartupInfo
.dwFlags
= 0;
3523 if (!CreateProcessA(NULL
,
3532 &ProcessInformation
))
3534 dosErr
= GetLastError();
3535 return dosErr
< 32 ? dosErr
: ERROR_BAD_FORMAT
;
3538 if (NULL
!= UserWaitForInputIdleRoutine
)
3540 UserWaitForInputIdleRoutine(ProcessInformation
.hProcess
,
3544 NtClose(ProcessInformation
.hProcess
);
3545 NtClose(ProcessInformation
.hThread
);
3547 return 33; /* Something bigger than 31 means success. */