2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * FILE: lib/kernel32/proc/proc.c
5 * PURPOSE: Process functions
6 * PROGRAMMERS: Ariadne (ariadne@xs4all.nl)
11 /* INCLUDES ****************************************************************/
18 /* GLOBALS *******************************************************************/
20 WaitForInputIdleType UserWaitForInputIdleRoutine
;
21 UNICODE_STRING BaseUnicodeCommandLine
;
22 ANSI_STRING BaseAnsiCommandLine
;
23 UNICODE_STRING BasePathVariableName
= RTL_CONSTANT_STRING(L
"PATH");
24 LPSTARTUPINFOA BaseAnsiStartupInfo
= NULL
;
25 PLDR_DATA_TABLE_ENTRY BasepExeLdrEntry
;
26 BOOLEAN g_AppCertInitialized
;
27 BOOLEAN g_HaveAppCerts
;
28 LIST_ENTRY BasepAppCertDllsList
;
29 RTL_CRITICAL_SECTION gcsAppCert
;
30 PBASEP_APPCERT_EMBEDDED_FUNC fEmbeddedCertFunc
;
31 NTSTATUS g_AppCertStatus
;
32 RTL_QUERY_REGISTRY_TABLE BasepAppCertTable
[2] =
35 BasepConfigureAppCertDlls
,
38 &BasepAppCertDllsList
,
45 PSAFER_REPLACE_PROCESS_THREAD_TOKENS g_SaferReplaceProcessThreadTokens
;
46 HMODULE gSaferHandle
= (HMODULE
)-1;
49 RegisterWaitForInputIdle(WaitForInputIdleType lpfnRegisterWaitForInputIdle
);
51 #define CMD_STRING L"cmd /c "
52 #define NTVDM_STRING L"\\ntvdm.exe"
54 /* FUNCTIONS ****************************************************************/
56 // NOTE: Code duplicated from BasepDuplicateAndWriteHandle
59 StuffStdHandle(IN HANDLE ProcessHandle
,
60 IN HANDLE StandardHandle
,
64 HANDLE DuplicatedHandle
;
67 /* Duplicate the handle */
68 Status
= NtDuplicateObject(NtCurrentProcess(),
73 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
)
498 BASE_API_MESSAGE ApiMessage
;
499 PBASE_CREATE_THREAD CreateThreadRequest
= &ApiMessage
.Data
.CreateThreadRequest
;
501 DPRINT("BasepNotifyCsrOfThread: Thread: %lx, Handle %lx\n",
502 ClientId
->UniqueThread
, ThreadHandle
);
504 /* Fill out the request */
505 CreateThreadRequest
->ClientId
= *ClientId
;
506 CreateThreadRequest
->ThreadHandle
= ThreadHandle
;
509 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
511 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepCreateThread
),
512 sizeof(BASE_CREATE_THREAD
));
513 if (!NT_SUCCESS(Status
))
515 DPRINT1("Failed to tell CSRSS about new thread: %lx\n", 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 DWORD dwCreationFlags
)
535 OBJECT_ATTRIBUTES LocalObjectAttributes
;
536 POBJECT_ATTRIBUTES ObjectAttributes
;
538 INITIAL_TEB InitialTeb
;
540 BASE_API_MESSAGE ApiMessage
;
541 PBASE_CREATE_PROCESS CreateProcessRequest
= &ApiMessage
.Data
.CreateProcessRequest
;
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 CreateProcessRequest
->ClientId
= *ClientId
;
579 CreateProcessRequest
->ProcessHandle
= ProcessHandle
;
580 CreateProcessRequest
->ThreadHandle
= hThread
;
581 CreateProcessRequest
->CreationFlags
= dwCreationFlags
;
584 * For GUI applications we turn on the 2nd bit. This also allows
585 * us to know whether or not this is a GUI or a TUI application.
587 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
== SectionImageInfo
->SubSystemType
)
589 CreateProcessRequest
->ProcessHandle
= (HANDLE
)
590 ((ULONG_PTR
)CreateProcessRequest
->ProcessHandle
| 2);
594 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
596 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepCreateProcess
),
597 sizeof(BASE_CREATE_PROCESS
));
598 if (!NT_SUCCESS(Status
))
600 DPRINT1("Failed to tell CSRSS about new process: %lx\n", Status
);
609 * Converts ANSI to Unicode Environment
613 BasepConvertUnicodeEnvironment(OUT SIZE_T
* EnvSize
,
614 IN PVOID lpEnvironment
)
618 UNICODE_STRING UnicodeEnv
;
621 DPRINT("BasepConvertUnicodeEnvironment\n");
623 /* Scan the environment to calculate its Unicode size */
624 AnsiEnv
.Buffer
= pcScan
= (PCHAR
)lpEnvironment
;
627 pcScan
+= strlen(pcScan
) + 1;
630 /* Create our ANSI String */
631 if (pcScan
== (PCHAR
)lpEnvironment
)
633 AnsiEnv
.Length
= 2 * sizeof(CHAR
);
638 AnsiEnv
.Length
= (USHORT
)((ULONG_PTR
)pcScan
- (ULONG_PTR
)lpEnvironment
+ sizeof(CHAR
));
640 AnsiEnv
.MaximumLength
= AnsiEnv
.Length
+ 1;
642 /* Allocate memory for the Unicode Environment */
643 UnicodeEnv
.Buffer
= NULL
;
644 *EnvSize
= AnsiEnv
.MaximumLength
* sizeof(WCHAR
);
645 Status
= NtAllocateVirtualMemory(NtCurrentProcess(),
646 (PVOID
)&UnicodeEnv
.Buffer
,
652 if (!NT_SUCCESS(Status
))
654 SetLastError(Status
);
659 /* Use the allocated size */
660 UnicodeEnv
.MaximumLength
= (USHORT
)*EnvSize
;
663 RtlAnsiStringToUnicodeString(&UnicodeEnv
, &AnsiEnv
, FALSE
);
664 return UnicodeEnv
.Buffer
;
668 * Converts a Win32 Priority Class to NT
672 BasepConvertPriorityClass(IN ULONG dwCreationFlags
)
676 if(dwCreationFlags
& IDLE_PRIORITY_CLASS
)
678 ReturnClass
= PROCESS_PRIORITY_CLASS_IDLE
;
680 else if(dwCreationFlags
& BELOW_NORMAL_PRIORITY_CLASS
)
682 ReturnClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
684 else if(dwCreationFlags
& NORMAL_PRIORITY_CLASS
)
686 ReturnClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
688 else if(dwCreationFlags
& ABOVE_NORMAL_PRIORITY_CLASS
)
690 ReturnClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
692 else if(dwCreationFlags
& HIGH_PRIORITY_CLASS
)
694 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
696 else if(dwCreationFlags
& REALTIME_PRIORITY_CLASS
)
698 /* Check for Privilege First */
699 if (BasepIsRealtimeAllowed(TRUE
))
701 ReturnClass
= PROCESS_PRIORITY_CLASS_REALTIME
;
705 ReturnClass
= PROCESS_PRIORITY_CLASS_HIGH
;
710 ReturnClass
= PROCESS_PRIORITY_CLASS_INVALID
;
717 * Duplicates a standard handle and writes it where requested.
719 // NOTE: Code duplicated from StuffStdHandle
722 BasepDuplicateAndWriteHandle(IN HANDLE ProcessHandle
,
723 IN HANDLE StandardHandle
,
727 HANDLE DuplicatedHandle
;
730 DPRINT("BasepDuplicateAndWriteHandle. hProcess: %lx, Handle: %lx,"
731 "Address: %p\n", ProcessHandle
, StandardHandle
, Address
);
733 /* Don't touch Console Handles */
734 if (IsConsoleHandle(StandardHandle
)) return;
736 /* Duplicate the handle */
737 Status
= NtDuplicateObject(NtCurrentProcess(),
742 DUPLICATE_SAME_ACCESS
| DUPLICATE_SAME_ATTRIBUTES
);
743 if (NT_SUCCESS(Status
))
746 NtWriteVirtualMemory(ProcessHandle
,
756 BasePushProcessParameters(IN ULONG ParameterFlags
,
757 IN HANDLE ProcessHandle
,
759 IN LPCWSTR ApplicationPathName
,
760 IN LPWSTR lpCurrentDirectory
,
761 IN LPWSTR lpCommandLine
,
762 IN LPVOID lpEnvironment
,
763 IN LPSTARTUPINFOW StartupInfo
,
764 IN DWORD CreationFlags
,
765 IN BOOL InheritHandles
,
766 IN ULONG ImageSubsystem
,
767 IN PVOID AppCompatData
,
768 IN ULONG AppCompatDataSize
)
770 WCHAR FullPath
[MAX_PATH
+ 5];
771 PWCHAR Remaining
, DllPathString
, ScanChar
;
772 PRTL_USER_PROCESS_PARAMETERS ProcessParameters
, RemoteParameters
;
773 PVOID RemoteAppCompatData
;
774 UNICODE_STRING DllPath
, ImageName
, CommandLine
, CurrentDirectory
;
775 UNICODE_STRING Desktop
, Shell
, Runtime
, Title
;
779 BOOLEAN HavePebLock
= FALSE
, Result
;
780 PPEB Peb
= NtCurrentPeb();
782 /* Get the full path name */
783 Size
= GetFullPathNameW(ApplicationPathName
,
787 if ((Size
) && (Size
<= (MAX_PATH
+ 4)))
789 /* Get the DLL Path */
790 DllPathString
= BaseComputeProcessDllPath(FullPath
, lpEnvironment
);
794 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
798 /* Initialize Strings */
799 RtlInitUnicodeString(&DllPath
, DllPathString
);
800 RtlInitUnicodeString(&ImageName
, FullPath
);
804 /* Couldn't get the path name. Just take the original path */
805 DllPathString
= BaseComputeProcessDllPath((LPWSTR
)ApplicationPathName
,
810 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
814 /* Initialize Strings */
815 RtlInitUnicodeString(&DllPath
, DllPathString
);
816 RtlInitUnicodeString(&ImageName
, ApplicationPathName
);
819 /* Initialize Strings */
820 RtlInitUnicodeString(&CommandLine
, lpCommandLine
);
821 RtlInitUnicodeString(&CurrentDirectory
, lpCurrentDirectory
);
823 /* Initialize more Strings from the Startup Info */
824 if (StartupInfo
->lpDesktop
)
826 RtlInitUnicodeString(&Desktop
, StartupInfo
->lpDesktop
);
830 RtlInitUnicodeString(&Desktop
, L
"");
832 if (StartupInfo
->lpReserved
)
834 RtlInitUnicodeString(&Shell
, StartupInfo
->lpReserved
);
838 RtlInitUnicodeString(&Shell
, L
"");
840 if (StartupInfo
->lpTitle
)
842 RtlInitUnicodeString(&Title
, StartupInfo
->lpTitle
);
846 RtlInitUnicodeString(&Title
, ApplicationPathName
);
849 /* This one is special because the length can differ */
850 Runtime
.Buffer
= (LPWSTR
)StartupInfo
->lpReserved2
;
851 Runtime
.MaximumLength
= Runtime
.Length
= StartupInfo
->cbReserved2
;
853 /* Enforce no app compat data if the pointer was NULL */
854 if (!AppCompatData
) AppCompatDataSize
= 0;
856 /* Create the Parameter Block */
857 ProcessParameters
= NULL
;
858 Status
= RtlCreateProcessParameters(&ProcessParameters
,
862 &CurrentDirectory
: NULL
,
869 if (!NT_SUCCESS(Status
)) goto FailPath
;
871 /* Clear the current directory handle if not inheriting */
872 if (!InheritHandles
) ProcessParameters
->CurrentDirectory
.Handle
= NULL
;
874 /* Check if the user passed in an environment */
877 /* We should've made it part of the parameters block, enforce this */
878 ASSERT(ProcessParameters
->Environment
== lpEnvironment
);
879 lpEnvironment
= ProcessParameters
->Environment
;
883 /* The user did not, so use the one from the current PEB */
886 lpEnvironment
= Peb
->ProcessParameters
->Environment
;
889 /* Save pointer and start lookup */
890 ScanChar
= lpEnvironment
;
893 /* Find the environment size */
894 while ((ScanChar
[0]) || (ScanChar
[1])) ++ScanChar
;
895 ScanChar
+= (2 * sizeof(UNICODE_NULL
));
896 EnviroSize
= (ULONG_PTR
)ScanChar
- (ULONG_PTR
)lpEnvironment
;
898 /* Allocate and Initialize new Environment Block */
900 ProcessParameters
->Environment
= NULL
;
901 Status
= NtAllocateVirtualMemory(ProcessHandle
,
902 (PVOID
*)&ProcessParameters
->Environment
,
907 if (!NT_SUCCESS(Status
)) goto FailPath
;
909 /* Write the Environment Block */
910 Status
= NtWriteVirtualMemory(ProcessHandle
,
911 ProcessParameters
->Environment
,
916 /* No longer need the PEB lock anymore */
924 /* Check if the write failed */
925 if (!NT_SUCCESS(Status
)) goto FailPath
;
928 /* Write new parameters */
929 ProcessParameters
->StartingX
= StartupInfo
->dwX
;
930 ProcessParameters
->StartingY
= StartupInfo
->dwY
;
931 ProcessParameters
->CountX
= StartupInfo
->dwXSize
;
932 ProcessParameters
->CountY
= StartupInfo
->dwYSize
;
933 ProcessParameters
->CountCharsX
= StartupInfo
->dwXCountChars
;
934 ProcessParameters
->CountCharsY
= StartupInfo
->dwYCountChars
;
935 ProcessParameters
->FillAttribute
= StartupInfo
->dwFillAttribute
;
936 ProcessParameters
->WindowFlags
= StartupInfo
->dwFlags
;
937 ProcessParameters
->ShowWindowFlags
= StartupInfo
->wShowWindow
;
939 /* Write the handles only if we have to */
940 if (StartupInfo
->dwFlags
&
941 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
943 ProcessParameters
->StandardInput
= StartupInfo
->hStdInput
;
944 ProcessParameters
->StandardOutput
= StartupInfo
->hStdOutput
;
945 ProcessParameters
->StandardError
= StartupInfo
->hStdError
;
948 /* Use Special Flags for BasepInitConsole in Kernel32 */
949 if (CreationFlags
& DETACHED_PROCESS
)
951 ProcessParameters
->ConsoleHandle
= HANDLE_DETACHED_PROCESS
;
953 else if (CreationFlags
& CREATE_NEW_CONSOLE
)
955 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NEW_CONSOLE
;
957 else if (CreationFlags
& CREATE_NO_WINDOW
)
959 ProcessParameters
->ConsoleHandle
= HANDLE_CREATE_NO_WINDOW
;
963 /* Inherit our Console Handle */
964 ProcessParameters
->ConsoleHandle
= Peb
->ProcessParameters
->ConsoleHandle
;
966 /* Make sure that the shell isn't trampling on our handles first */
967 if (!(StartupInfo
->dwFlags
&
968 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
970 /* Copy the handle if we are inheriting or if it's a console handle */
971 if ((InheritHandles
) ||
972 (IsConsoleHandle(Peb
->ProcessParameters
->StandardInput
)))
974 ProcessParameters
->StandardInput
= Peb
->ProcessParameters
->StandardInput
;
976 if ((InheritHandles
) ||
977 (IsConsoleHandle(Peb
->ProcessParameters
->StandardOutput
)))
979 ProcessParameters
->StandardOutput
= Peb
->ProcessParameters
->StandardOutput
;
981 if ((InheritHandles
) ||
982 (IsConsoleHandle(Peb
->ProcessParameters
->StandardError
)))
984 ProcessParameters
->StandardError
= Peb
->ProcessParameters
->StandardError
;
989 /* Also set the Console Flag */
990 if ((CreationFlags
& CREATE_NEW_PROCESS_GROUP
) &&
991 (!(CreationFlags
& CREATE_NEW_CONSOLE
)))
993 ProcessParameters
->ConsoleFlags
= 1;
996 /* See if the first 1MB should be reserved */
997 if (ParameterFlags
& 1)
999 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_RESERVE_1MB
;
1002 /* See if the first 16MB should be reserved */
1003 if (ParameterFlags
& 2)
1005 ProcessParameters
->Flags
|= RTL_USER_PROCESS_PARAMETERS_RESERVE_16MB
;
1008 /* Allocate memory for the parameter block */
1009 Size
= ProcessParameters
->Length
;
1010 RemoteParameters
= NULL
;
1011 Status
= NtAllocateVirtualMemory(ProcessHandle
,
1012 (PVOID
*)&RemoteParameters
,
1017 if (!NT_SUCCESS(Status
)) goto FailPath
;
1019 /* Set the allocated size */
1020 ProcessParameters
->MaximumLength
= Size
;
1022 /* Handle some Parameter Flags */
1023 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_USER
) ?
1024 RTL_USER_PROCESS_PARAMETERS_PROFILE_USER
: 0;
1025 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_KERNEL
) ?
1026 RTL_USER_PROCESS_PARAMETERS_PROFILE_KERNEL
: 0;
1027 ProcessParameters
->Flags
|= (CreationFlags
& PROFILE_SERVER
) ?
1028 RTL_USER_PROCESS_PARAMETERS_PROFILE_SERVER
: 0;
1029 ProcessParameters
->Flags
|= (Peb
->ProcessParameters
->Flags
&
1030 RTL_USER_PROCESS_PARAMETERS_DISABLE_HEAP_CHECKS
);
1032 /* Write the Parameter Block */
1033 Status
= NtWriteVirtualMemory(ProcessHandle
,
1036 ProcessParameters
->Length
,
1038 if (!NT_SUCCESS(Status
)) goto FailPath
;
1040 /* Write the PEB Pointer */
1041 Status
= NtWriteVirtualMemory(ProcessHandle
,
1042 &RemotePeb
->ProcessParameters
,
1046 if (!NT_SUCCESS(Status
)) goto FailPath
;
1048 /* Check if there's any app compat data to write */
1049 RemoteAppCompatData
= NULL
;
1052 /* Allocate some space for the application compatibility data */
1053 Size
= AppCompatDataSize
;
1054 Status
= NtAllocateVirtualMemory(ProcessHandle
,
1055 &RemoteAppCompatData
,
1060 if (!NT_SUCCESS(Status
)) goto FailPath
;
1062 /* Write the application compatibility data */
1063 Status
= NtWriteVirtualMemory(ProcessHandle
,
1064 RemoteAppCompatData
,
1068 if (!NT_SUCCESS(Status
)) goto FailPath
;
1071 /* Write the PEB Pointer to the app compat data (might be NULL) */
1072 Status
= NtWriteVirtualMemory(ProcessHandle
,
1073 &RemotePeb
->pShimData
,
1074 &RemoteAppCompatData
,
1077 if (!NT_SUCCESS(Status
)) goto FailPath
;
1079 /* Now write Peb->ImageSubSystem */
1082 NtWriteVirtualMemory(ProcessHandle
,
1083 &RemotePeb
->ImageSubsystem
,
1085 sizeof(ImageSubsystem
),
1094 if (HavePebLock
) RtlReleasePebLock();
1095 RtlFreeHeap(RtlGetProcessHeap(), 0, DllPath
.Buffer
);
1096 if (ProcessParameters
) RtlDestroyProcessParameters(ProcessParameters
);
1099 DPRINT1("Failure to create proecss parameters: %lx\n", Status
);
1100 BaseSetLastNTError(Status
);
1107 InitCommandLines(VOID
)
1111 /* Read the UNICODE_STRING from the PEB */
1112 BaseUnicodeCommandLine
= NtCurrentPeb()->ProcessParameters
->CommandLine
;
1114 /* Convert to ANSI_STRING for the *A callers */
1115 Status
= RtlUnicodeStringToAnsiString(&BaseAnsiCommandLine
,
1116 &BaseUnicodeCommandLine
,
1118 if (!NT_SUCCESS(Status
)) RtlInitEmptyAnsiString(&BaseAnsiCommandLine
, 0, 0);
1121 /* PUBLIC FUNCTIONS ***********************************************************/
1128 GetProcessAffinityMask(IN HANDLE hProcess
,
1129 OUT PDWORD_PTR lpProcessAffinityMask
,
1130 OUT PDWORD_PTR lpSystemAffinityMask
)
1132 PROCESS_BASIC_INFORMATION ProcessInfo
;
1135 /* Query information on the process from the kernel */
1136 Status
= NtQueryInformationProcess(hProcess
,
1137 ProcessBasicInformation
,
1138 (PVOID
)&ProcessInfo
,
1139 sizeof(PROCESS_BASIC_INFORMATION
),
1141 if (!NT_SUCCESS(Status
))
1144 BaseSetLastNTError(Status
);
1148 /* Copy the affinity mask, and get the system one from our shared data */
1149 *lpProcessAffinityMask
= (DWORD
)ProcessInfo
.AffinityMask
;
1150 *lpSystemAffinityMask
= (DWORD
)BaseStaticServerData
->SysInfo
.ActiveProcessorsAffinityMask
;
1159 SetProcessAffinityMask(IN HANDLE hProcess
,
1160 IN DWORD_PTR dwProcessAffinityMask
)
1164 /* Directly set the affinity mask */
1165 Status
= NtSetInformationProcess(hProcess
,
1166 ProcessAffinityMask
,
1167 (PVOID
)&dwProcessAffinityMask
,
1169 if (!NT_SUCCESS(Status
))
1171 /* Handle failure */
1172 BaseSetLastNTError(Status
);
1176 /* Everything was ok */
1185 GetProcessShutdownParameters(OUT LPDWORD lpdwLevel
,
1186 OUT LPDWORD lpdwFlags
)
1189 BASE_API_MESSAGE ApiMessage
;
1190 PBASE_GET_PROCESS_SHUTDOWN_PARAMS GetShutdownParametersRequest
= &ApiMessage
.Data
.GetShutdownParametersRequest
;
1192 /* Ask CSRSS for shutdown information */
1193 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
1195 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepGetProcessShutdownParam
),
1196 sizeof(BASE_GET_PROCESS_SHUTDOWN_PARAMS
));
1197 if (!NT_SUCCESS(Status
))
1199 /* Return the failure from CSRSS */
1200 BaseSetLastNTError(Status
);
1204 /* Get the data back */
1205 *lpdwLevel
= GetShutdownParametersRequest
->Level
;
1206 *lpdwFlags
= GetShutdownParametersRequest
->Flags
;
1215 SetProcessShutdownParameters(IN DWORD dwLevel
,
1219 BASE_API_MESSAGE ApiMessage
;
1220 PBASE_SET_PROCESS_SHUTDOWN_PARAMS SetShutdownParametersRequest
= &ApiMessage
.Data
.SetShutdownParametersRequest
;
1222 /* Write the data into the CSRSS request and send it */
1223 SetShutdownParametersRequest
->Level
= dwLevel
;
1224 SetShutdownParametersRequest
->Flags
= dwFlags
;
1225 Status
= CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
1227 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepSetProcessShutdownParam
),
1228 sizeof(BASE_SET_PROCESS_SHUTDOWN_PARAMS
));
1229 if (!NT_SUCCESS(Status
))
1231 /* Return the failure from CSRSS */
1232 BaseSetLastNTError(Status
);
1245 GetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1246 OUT PSIZE_T lpMinimumWorkingSetSize
,
1247 OUT PSIZE_T lpMaximumWorkingSetSize
,
1250 QUOTA_LIMITS_EX QuotaLimits
;
1253 /* Query the kernel about this */
1254 Status
= NtQueryInformationProcess(hProcess
,
1257 sizeof(QUOTA_LIMITS_EX
),
1259 if (!NT_SUCCESS(Status
))
1262 BaseSetLastNTError(Status
);
1266 /* Copy the quota information out */
1267 *lpMinimumWorkingSetSize
= QuotaLimits
.MinimumWorkingSetSize
;
1268 *lpMaximumWorkingSetSize
= QuotaLimits
.MaximumWorkingSetSize
;
1269 *Flags
= QuotaLimits
.Flags
;
1278 GetProcessWorkingSetSize(IN HANDLE hProcess
,
1279 OUT PSIZE_T lpMinimumWorkingSetSize
,
1280 OUT PSIZE_T lpMaximumWorkingSetSize
)
1283 return GetProcessWorkingSetSizeEx(hProcess
,
1284 lpMinimumWorkingSetSize
,
1285 lpMaximumWorkingSetSize
,
1294 SetProcessWorkingSetSizeEx(IN HANDLE hProcess
,
1295 IN SIZE_T dwMinimumWorkingSetSize
,
1296 IN SIZE_T dwMaximumWorkingSetSize
,
1299 QUOTA_LIMITS_EX QuotaLimits
;
1300 NTSTATUS Status
, ReturnStatus
;
1303 ULONG Privilege
= SE_INC_BASE_PRIORITY_PRIVILEGE
;
1305 /* Zero out the input structure */
1306 RtlZeroMemory(&QuotaLimits
, sizeof(QuotaLimits
));
1308 /* Check if the caller sent any limits */
1309 if ((dwMinimumWorkingSetSize
) && (dwMaximumWorkingSetSize
))
1311 /* Write the quota information */
1312 QuotaLimits
.MinimumWorkingSetSize
= dwMinimumWorkingSetSize
;
1313 QuotaLimits
.MaximumWorkingSetSize
= dwMaximumWorkingSetSize
;
1314 QuotaLimits
.Flags
= Flags
;
1316 /* Acquire the required privilege */
1317 Status
= RtlAcquirePrivilege(&Privilege
, 1, 0, &State
);
1319 /* Request the new quotas */
1320 ReturnStatus
= NtSetInformationProcess(hProcess
,
1323 sizeof(QuotaLimits
));
1324 Result
= NT_SUCCESS(ReturnStatus
);
1325 if (NT_SUCCESS(Status
))
1327 /* Release the privilege and set succes code */
1328 ASSERT(State
!= NULL
);
1329 RtlReleasePrivilege(State
);
1335 /* No limits, fail the call */
1336 ReturnStatus
= STATUS_INVALID_PARAMETER
;
1340 /* Return result code, set error code if this was a failure */
1341 if (!Result
) BaseSetLastNTError(ReturnStatus
);
1350 SetProcessWorkingSetSize(IN HANDLE hProcess
,
1351 IN SIZE_T dwMinimumWorkingSetSize
,
1352 IN SIZE_T dwMaximumWorkingSetSize
)
1354 /* Call the newer API */
1355 return SetProcessWorkingSetSizeEx(hProcess
,
1356 dwMinimumWorkingSetSize
,
1357 dwMaximumWorkingSetSize
,
1366 GetProcessTimes(IN HANDLE hProcess
,
1367 IN LPFILETIME lpCreationTime
,
1368 IN LPFILETIME lpExitTime
,
1369 IN LPFILETIME lpKernelTime
,
1370 IN LPFILETIME lpUserTime
)
1372 KERNEL_USER_TIMES Kut
;
1375 /* Query the times */
1376 Status
= NtQueryInformationProcess(hProcess
,
1381 if (!NT_SUCCESS(Status
))
1383 /* Handle failure */
1384 BaseSetLastNTError(Status
);
1388 /* Copy all the times and return success */
1389 lpCreationTime
->dwLowDateTime
= Kut
.CreateTime
.u
.LowPart
;
1390 lpCreationTime
->dwHighDateTime
= Kut
.CreateTime
.u
.HighPart
;
1391 lpExitTime
->dwLowDateTime
= Kut
.ExitTime
.u
.LowPart
;
1392 lpExitTime
->dwHighDateTime
= Kut
.ExitTime
.u
.HighPart
;
1393 lpKernelTime
->dwLowDateTime
= Kut
.KernelTime
.u
.LowPart
;
1394 lpKernelTime
->dwHighDateTime
= Kut
.KernelTime
.u
.HighPart
;
1395 lpUserTime
->dwLowDateTime
= Kut
.UserTime
.u
.LowPart
;
1396 lpUserTime
->dwHighDateTime
= Kut
.UserTime
.u
.HighPart
;
1405 GetCurrentProcess(VOID
)
1407 return (HANDLE
)NtCurrentProcess();
1415 GetCurrentThread(VOID
)
1417 return (HANDLE
)NtCurrentThread();
1425 GetCurrentProcessId(VOID
)
1427 return HandleToUlong(NtCurrentTeb()->ClientId
.UniqueProcess
);
1435 GetExitCodeProcess(IN HANDLE hProcess
,
1436 IN LPDWORD lpExitCode
)
1438 PROCESS_BASIC_INFORMATION ProcessBasic
;
1441 /* Ask the kernel */
1442 Status
= NtQueryInformationProcess(hProcess
,
1443 ProcessBasicInformation
,
1445 sizeof(PROCESS_BASIC_INFORMATION
),
1447 if (!NT_SUCCESS(Status
))
1449 /* We failed, was this because this is a VDM process? */
1450 if (BaseCheckForVDM(hProcess
, lpExitCode
) == TRUE
) return TRUE
;
1452 /* Not a VDM process, fail the call */
1453 BaseSetLastNTError(Status
);
1457 /* Succes case, return the exit code */
1458 *lpExitCode
= (DWORD
)ProcessBasic
.ExitStatus
;
1467 GetProcessId(IN HANDLE Process
)
1469 PROCESS_BASIC_INFORMATION ProcessBasic
;
1472 /* Query the kernel */
1473 Status
= NtQueryInformationProcess(Process
,
1474 ProcessBasicInformation
,
1476 sizeof(PROCESS_BASIC_INFORMATION
),
1478 if (!NT_SUCCESS(Status
))
1480 /* Handle failure */
1481 BaseSetLastNTError(Status
);
1485 /* Return the PID */
1486 return (DWORD
)ProcessBasic
.UniqueProcessId
;
1494 OpenProcess(IN DWORD dwDesiredAccess
,
1495 IN BOOL bInheritHandle
,
1496 IN DWORD dwProcessId
)
1499 HANDLE ProcessHandle
;
1500 OBJECT_ATTRIBUTES ObjectAttributes
;
1503 /* Setup the input client ID structure */
1504 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
1505 ClientId
.UniqueThread
= 0;
1507 /* This is needed just to define the inheritance flags */
1508 InitializeObjectAttributes(&ObjectAttributes
,
1510 (bInheritHandle
? OBJ_INHERIT
: 0),
1514 /* Now try to open the process */
1515 Status
= NtOpenProcess(&ProcessHandle
,
1519 if (!NT_SUCCESS(Status
))
1521 /* Handle failure */
1522 BaseSetLastNTError(Status
);
1526 /* Otherwise return a handle to the process */
1527 return ProcessHandle
;
1535 RegisterWaitForInputIdle(IN WaitForInputIdleType lpfnRegisterWaitForInputIdle
)
1537 /* Write the global function pointer */
1538 UserWaitForInputIdleRoutine
= lpfnRegisterWaitForInputIdle
;
1546 GetStartupInfoW(IN LPSTARTUPINFOW lpStartupInfo
)
1548 PRTL_USER_PROCESS_PARAMETERS Params
;
1550 /* Get the process parameters */
1551 Params
= NtCurrentPeb()->ProcessParameters
;
1553 /* Copy the data out of there */
1554 lpStartupInfo
->cb
= sizeof(STARTUPINFOW
);
1555 lpStartupInfo
->lpReserved
= Params
->ShellInfo
.Buffer
;
1556 lpStartupInfo
->lpDesktop
= Params
->DesktopInfo
.Buffer
;
1557 lpStartupInfo
->lpTitle
= Params
->WindowTitle
.Buffer
;
1558 lpStartupInfo
->dwX
= Params
->StartingX
;
1559 lpStartupInfo
->dwY
= Params
->StartingY
;
1560 lpStartupInfo
->dwXSize
= Params
->CountX
;
1561 lpStartupInfo
->dwYSize
= Params
->CountY
;
1562 lpStartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1563 lpStartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1564 lpStartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1565 lpStartupInfo
->dwFlags
= Params
->WindowFlags
;
1566 lpStartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1567 lpStartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1568 lpStartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1570 /* Check if the standard handles are being used for other features */
1571 if (lpStartupInfo
->dwFlags
& (STARTF_USESTDHANDLES
|
1573 STARTF_SHELLPRIVATE
))
1575 /* These are, so copy the standard handles too */
1576 lpStartupInfo
->hStdInput
= Params
->StandardInput
;
1577 lpStartupInfo
->hStdOutput
= Params
->StandardOutput
;
1578 lpStartupInfo
->hStdError
= Params
->StandardError
;
1587 GetStartupInfoA(IN LPSTARTUPINFOA lpStartupInfo
)
1589 PRTL_USER_PROCESS_PARAMETERS Params
;
1590 ANSI_STRING TitleString
, ShellString
, DesktopString
;
1591 LPSTARTUPINFOA StartupInfo
;
1594 /* Get the cached information as well as the PEB parameters */
1595 StartupInfo
= BaseAnsiStartupInfo
;
1596 Params
= NtCurrentPeb()->ProcessParameters
;
1598 /* Check if this is the first time we have to get the cached version */
1599 while (!StartupInfo
)
1601 /* Create new ANSI startup info */
1602 StartupInfo
= RtlAllocateHeap(RtlGetProcessHeap(),
1604 sizeof(*StartupInfo
));
1607 /* Zero out string pointers in case we fail to create them */
1608 StartupInfo
->lpReserved
= 0;
1609 StartupInfo
->lpDesktop
= 0;
1610 StartupInfo
->lpTitle
= 0;
1613 StartupInfo
->cb
= sizeof(*StartupInfo
);
1615 /* Copy what's already stored in the PEB */
1616 StartupInfo
->dwX
= Params
->StartingX
;
1617 StartupInfo
->dwY
= Params
->StartingY
;
1618 StartupInfo
->dwXSize
= Params
->CountX
;
1619 StartupInfo
->dwYSize
= Params
->CountY
;
1620 StartupInfo
->dwXCountChars
= Params
->CountCharsX
;
1621 StartupInfo
->dwYCountChars
= Params
->CountCharsY
;
1622 StartupInfo
->dwFillAttribute
= Params
->FillAttribute
;
1623 StartupInfo
->dwFlags
= Params
->WindowFlags
;
1624 StartupInfo
->wShowWindow
= (WORD
)Params
->ShowWindowFlags
;
1625 StartupInfo
->cbReserved2
= Params
->RuntimeData
.Length
;
1626 StartupInfo
->lpReserved2
= (LPBYTE
)Params
->RuntimeData
.Buffer
;
1627 StartupInfo
->hStdInput
= Params
->StandardInput
;
1628 StartupInfo
->hStdOutput
= Params
->StandardOutput
;
1629 StartupInfo
->hStdError
= Params
->StandardError
;
1631 /* Copy shell info string */
1632 Status
= RtlUnicodeStringToAnsiString(&ShellString
,
1635 if (NT_SUCCESS(Status
))
1638 StartupInfo
->lpReserved
= ShellString
.Buffer
;
1640 /* Copy desktop info string */
1641 Status
= RtlUnicodeStringToAnsiString(&DesktopString
,
1642 &Params
->DesktopInfo
,
1644 if (NT_SUCCESS(Status
))
1647 StartupInfo
->lpDesktop
= DesktopString
.Buffer
;
1649 /* Copy window title string */
1650 Status
= RtlUnicodeStringToAnsiString(&TitleString
,
1651 &Params
->WindowTitle
,
1653 if (NT_SUCCESS(Status
))
1656 StartupInfo
->lpTitle
= TitleString
.Buffer
;
1658 /* We finished with the ANSI version, try to cache it */
1659 if (!InterlockedCompareExchangePointer(&BaseAnsiStartupInfo
,
1663 /* We were the first thread through, use the data */
1667 /* Someone beat us to it, use their data instead */
1668 StartupInfo
= BaseAnsiStartupInfo
;
1669 Status
= STATUS_SUCCESS
;
1671 /* We're going to free our own stuff, but not raise */
1672 RtlFreeAnsiString(&TitleString
);
1674 RtlFreeAnsiString(&DesktopString
);
1676 RtlFreeAnsiString(&ShellString
);
1678 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
);
1682 /* No memory, fail */
1683 Status
= STATUS_NO_MEMORY
;
1686 /* Raise an error unless we got here due to the race condition */
1687 if (!NT_SUCCESS(Status
)) RtlRaiseStatus(Status
);
1690 /* Now copy from the cached ANSI version */
1691 lpStartupInfo
->cb
= StartupInfo
->cb
;
1692 lpStartupInfo
->lpReserved
= StartupInfo
->lpReserved
;
1693 lpStartupInfo
->lpDesktop
= StartupInfo
->lpDesktop
;
1694 lpStartupInfo
->lpTitle
= StartupInfo
->lpTitle
;
1695 lpStartupInfo
->dwX
= StartupInfo
->dwX
;
1696 lpStartupInfo
->dwY
= StartupInfo
->dwY
;
1697 lpStartupInfo
->dwXSize
= StartupInfo
->dwXSize
;
1698 lpStartupInfo
->dwYSize
= StartupInfo
->dwYSize
;
1699 lpStartupInfo
->dwXCountChars
= StartupInfo
->dwXCountChars
;
1700 lpStartupInfo
->dwYCountChars
= StartupInfo
->dwYCountChars
;
1701 lpStartupInfo
->dwFillAttribute
= StartupInfo
->dwFillAttribute
;
1702 lpStartupInfo
->dwFlags
= StartupInfo
->dwFlags
;
1703 lpStartupInfo
->wShowWindow
= StartupInfo
->wShowWindow
;
1704 lpStartupInfo
->cbReserved2
= StartupInfo
->cbReserved2
;
1705 lpStartupInfo
->lpReserved2
= StartupInfo
->lpReserved2
;
1707 /* Check if the shell is hijacking the handles for other features */
1708 if (lpStartupInfo
->dwFlags
&
1709 (STARTF_USESTDHANDLES
| STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
))
1711 /* It isn't, so we can return the raw values */
1712 lpStartupInfo
->hStdInput
= StartupInfo
->hStdInput
;
1713 lpStartupInfo
->hStdOutput
= StartupInfo
->hStdOutput
;
1714 lpStartupInfo
->hStdError
= StartupInfo
->hStdError
;
1718 /* It is, so make sure nobody uses these as console handles */
1719 lpStartupInfo
->hStdInput
= INVALID_HANDLE_VALUE
;
1720 lpStartupInfo
->hStdOutput
= INVALID_HANDLE_VALUE
;
1721 lpStartupInfo
->hStdError
= INVALID_HANDLE_VALUE
;
1730 FlushInstructionCache(IN HANDLE hProcess
,
1731 IN LPCVOID lpBaseAddress
,
1736 /* Call the native function */
1737 Status
= NtFlushInstructionCache(hProcess
, (PVOID
)lpBaseAddress
, dwSize
);
1738 if (!NT_SUCCESS(Status
))
1740 /* Handle failure case */
1741 BaseSetLastNTError(Status
);
1754 ExitProcess(IN UINT uExitCode
)
1756 BASE_API_MESSAGE ApiMessage
;
1757 PBASE_EXIT_PROCESS ExitProcessRequest
= &ApiMessage
.Data
.ExitProcessRequest
;
1759 ASSERT(!BaseRunningInServerProcess
);
1763 /* Acquire the PEB lock */
1764 RtlAcquirePebLock();
1766 /* Kill all the threads */
1767 NtTerminateProcess(NULL
, 0);
1769 /* Unload all DLLs */
1770 LdrShutdownProcess();
1772 /* Notify Base Server of process termination */
1773 ExitProcessRequest
->uExitCode
= uExitCode
;
1774 CsrClientCallServer((PCSR_API_MESSAGE
)&ApiMessage
,
1776 CSR_CREATE_API_NUMBER(BASESRV_SERVERDLL_INDEX
, BasepExitProcess
),
1777 sizeof(BASE_EXIT_PROCESS
));
1779 /* Now do it again */
1780 NtTerminateProcess(NtCurrentProcess(), uExitCode
);
1784 /* Release the PEB lock */
1785 RtlReleasePebLock();
1789 /* should never get here */
1799 TerminateProcess(IN HANDLE hProcess
,
1804 /* Check if no handle was passed in */
1807 /* Set error code */
1808 SetLastError(ERROR_INVALID_HANDLE
);
1812 /* Otherwise, try to terminate the process */
1813 Status
= NtTerminateProcess(hProcess
, uExitCode
);
1814 if (NT_SUCCESS(Status
)) return TRUE
;
1816 /* It failed, convert error code */
1817 BaseSetLastNTError(Status
);
1820 /* This is the failure path */
1829 FatalAppExitA(UINT uAction
,
1830 LPCSTR lpMessageText
)
1832 PUNICODE_STRING MessageTextU
;
1833 ANSI_STRING MessageText
;
1836 /* Initialize the string using the static TEB pointer */
1837 MessageTextU
= &NtCurrentTeb()->StaticUnicodeString
;
1838 RtlInitAnsiString(&MessageText
, (LPSTR
)lpMessageText
);
1840 /* Convert to unicode and just exit normally if this failed */
1841 Status
= RtlAnsiStringToUnicodeString(MessageTextU
, &MessageText
, FALSE
);
1842 if (!NT_SUCCESS(Status
)) ExitProcess(0);
1844 /* Call the Wide function */
1845 FatalAppExitW(uAction
, MessageTextU
->Buffer
);
1853 FatalAppExitW(IN UINT uAction
,
1854 IN LPCWSTR lpMessageText
)
1856 UNICODE_STRING UnicodeString
;
1860 /* Setup the string to print out */
1861 RtlInitUnicodeString(&UnicodeString
, lpMessageText
);
1863 /* Display the hard error no matter what */
1864 Status
= NtRaiseHardError(STATUS_FATAL_APP_EXIT
| HARDERROR_OVERRIDE_ERRORMODE
,
1867 (PULONG_PTR
)&UnicodeString
,
1871 /* Give the user a chance to abort */
1872 if ((NT_SUCCESS(Status
)) && (Response
== ResponseCancel
)) return;
1874 /* Otherwise kill the process */
1883 FatalExit(IN
int ExitCode
)
1886 /* On Checked builds, Windows gives you a nice little debugger UI */
1888 DbgPrint("FatalExit...\n");
1893 DbgPrompt( "A (Abort), B (Break), I (Ignore)? ", ch
, sizeof(ch
));
1901 ExitProcess(ExitCode
);
1908 /* On other builds, just kill the process */
1909 ExitProcess(ExitCode
);
1917 GetPriorityClass(IN HANDLE hProcess
)
1920 PROCESS_PRIORITY_CLASS PriorityClass
;
1922 /* Query the kernel */
1923 Status
= NtQueryInformationProcess(hProcess
,
1924 ProcessPriorityClass
,
1926 sizeof(PROCESS_PRIORITY_CLASS
),
1928 if (NT_SUCCESS(Status
))
1930 /* Handle the conversion from NT to Win32 classes */
1931 switch (PriorityClass
.PriorityClass
)
1933 case PROCESS_PRIORITY_CLASS_IDLE
: return IDLE_PRIORITY_CLASS
;
1934 case PROCESS_PRIORITY_CLASS_BELOW_NORMAL
: return BELOW_NORMAL_PRIORITY_CLASS
;
1935 case PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
: return ABOVE_NORMAL_PRIORITY_CLASS
;
1936 case PROCESS_PRIORITY_CLASS_HIGH
: return HIGH_PRIORITY_CLASS
;
1937 case PROCESS_PRIORITY_CLASS_REALTIME
: return REALTIME_PRIORITY_CLASS
;
1938 case PROCESS_PRIORITY_CLASS_NORMAL
: default: return NORMAL_PRIORITY_CLASS
;
1943 BaseSetLastNTError(Status
);
1952 SetPriorityClass(IN HANDLE hProcess
,
1953 IN DWORD dwPriorityClass
)
1957 PROCESS_PRIORITY_CLASS PriorityClass
;
1959 /* Handle conversion from Win32 to NT priority classes */
1960 switch (dwPriorityClass
)
1962 case IDLE_PRIORITY_CLASS
:
1963 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_IDLE
;
1966 case BELOW_NORMAL_PRIORITY_CLASS
:
1967 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_BELOW_NORMAL
;
1970 case NORMAL_PRIORITY_CLASS
:
1971 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_NORMAL
;
1974 case ABOVE_NORMAL_PRIORITY_CLASS
:
1975 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_ABOVE_NORMAL
;
1978 case HIGH_PRIORITY_CLASS
:
1979 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1982 case REALTIME_PRIORITY_CLASS
:
1983 /* Try to acquire the privilege. If it fails, just use HIGH */
1984 State
= BasepIsRealtimeAllowed(TRUE
);
1985 PriorityClass
.PriorityClass
= PROCESS_PRIORITY_CLASS_HIGH
;
1986 PriorityClass
.PriorityClass
+= (State
!= NULL
);
1990 /* Unrecognized priority classes don't make it to the kernel */
1991 SetLastError(ERROR_INVALID_PARAMETER
);
1995 /* Send the request to the kernel, and don't touch the foreground flag */
1996 PriorityClass
.Foreground
= FALSE
;
1997 Status
= NtSetInformationProcess(hProcess
,
1998 ProcessPriorityClass
,
2000 sizeof(PROCESS_PRIORITY_CLASS
));
2002 /* Release the privilege if we had it */
2003 if (State
) RtlReleasePrivilege(State
);
2004 if (!NT_SUCCESS(Status
))
2006 /* Handle error path */
2007 BaseSetLastNTError(Status
);
2020 GetProcessVersion(IN DWORD ProcessId
)
2023 PIMAGE_NT_HEADERS NtHeader
;
2024 PIMAGE_DOS_HEADER DosHeader
;
2026 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
2029 HANDLE ProcessHandle
= NULL
;
2031 USHORT VersionData
[2];
2034 /* We'll be accessing stuff that can fault, so protect everything with SEH */
2037 /* It this an in-process or out-of-process request? */
2038 if (!(ProcessId
) || (GetCurrentProcessId() == ProcessId
))
2040 /* It's in-process, so just read our own header */
2041 NtHeader
= RtlImageNtHeader(NtCurrentPeb()->ImageBaseAddress
);
2044 /* Unable to read the NT header, something is wrong here... */
2045 Status
= STATUS_INVALID_IMAGE_FORMAT
;
2049 /* Get the version straight out of the NT header */
2050 Version
= MAKELONG(NtHeader
->OptionalHeader
.MinorSubsystemVersion
,
2051 NtHeader
->OptionalHeader
.MajorSubsystemVersion
);
2055 /* Out-of-process, so open it */
2056 ProcessHandle
= OpenProcess(PROCESS_VM_READ
| PROCESS_QUERY_INFORMATION
,
2059 if (!ProcessHandle
) return 0;
2061 /* Try to find out where its PEB lives */
2062 Status
= NtQueryInformationProcess(ProcessHandle
,
2063 ProcessBasicInformation
,
2065 sizeof(ProcessBasicInfo
),
2068 if (!NT_SUCCESS(Status
)) goto Error
;
2069 Peb
= ProcessBasicInfo
.PebBaseAddress
;
2071 /* Now that we have the PEB, read the image base address out of it */
2072 Result
= ReadProcessMemory(ProcessHandle
,
2073 &Peb
->ImageBaseAddress
,
2075 sizeof(BaseAddress
),
2077 if (!Result
) goto Error
;
2079 /* Now read the e_lfanew (offset to NT header) from the base */
2080 DosHeader
= BaseAddress
;
2081 Result
= ReadProcessMemory(ProcessHandle
,
2082 &DosHeader
->e_lfanew
,
2086 if (!Result
) goto Error
;
2088 /* And finally, read the NT header itself by adding the offset */
2089 NtHeader
= (PVOID
)((ULONG_PTR
)BaseAddress
+ e_lfanew
);
2090 Result
= ReadProcessMemory(ProcessHandle
,
2091 &NtHeader
->OptionalHeader
.MajorSubsystemVersion
,
2093 sizeof(VersionData
),
2095 if (!Result
) goto Error
;
2097 /* Get the version straight out of the NT header */
2098 Version
= MAKELONG(VersionData
[0], VersionData
[1]);
2101 /* If there was an error anywhere, set the last error */
2102 if (!NT_SUCCESS(Status
)) BaseSetLastNTError(Status
);
2107 /* Close the process handle */
2108 if (ProcessHandle
) CloseHandle(ProcessHandle
);
2112 /* And return the version data */
2121 GetProcessIoCounters(IN HANDLE hProcess
,
2122 OUT PIO_COUNTERS lpIoCounters
)
2126 /* Query the kernel. Structures are identical, so let it do the copy too. */
2127 Status
= NtQueryInformationProcess(hProcess
,
2130 sizeof(IO_COUNTERS
),
2132 if (!NT_SUCCESS(Status
))
2134 /* Handle error path */
2135 BaseSetLastNTError(Status
);
2148 GetProcessPriorityBoost(IN HANDLE hProcess
,
2149 OUT PBOOL pDisablePriorityBoost
)
2152 ULONG PriorityBoost
;
2154 /* Query the kernel */
2155 Status
= NtQueryInformationProcess(hProcess
,
2156 ProcessPriorityBoost
,
2160 if (NT_SUCCESS(Status
))
2162 /* Convert from ULONG to a BOOL */
2163 *pDisablePriorityBoost
= PriorityBoost
? TRUE
: FALSE
;
2167 /* Handle error path */
2168 BaseSetLastNTError(Status
);
2177 SetProcessPriorityBoost(IN HANDLE hProcess
,
2178 IN BOOL bDisablePriorityBoost
)
2181 ULONG PriorityBoost
;
2183 /* Enforce that this is a BOOL, and send it to the kernel as a ULONG */
2184 PriorityBoost
= (bDisablePriorityBoost
? TRUE
: FALSE
);
2185 Status
= NtSetInformationProcess(hProcess
,
2186 ProcessPriorityBoost
,
2189 if (!NT_SUCCESS(Status
))
2191 /* Handle error path */
2192 BaseSetLastNTError(Status
);
2205 GetProcessHandleCount(IN HANDLE hProcess
,
2206 OUT PDWORD pdwHandleCount
)
2211 /* Query the kernel */
2212 Status
= NtQueryInformationProcess(hProcess
,
2217 if (NT_SUCCESS(Status
))
2219 /* Copy the count and return sucecss */
2220 *pdwHandleCount
= phc
;
2224 /* Handle error path */
2225 BaseSetLastNTError(Status
);
2234 IsWow64Process(IN HANDLE hProcess
,
2235 OUT PBOOL Wow64Process
)
2240 /* Query the kernel */
2241 Status
= NtQueryInformationProcess(hProcess
,
2242 ProcessWow64Information
,
2246 if (!NT_SUCCESS(Status
))
2248 /* Handle error path */
2249 BaseSetLastNTError(Status
);
2253 /* Enforce this is a BOOL, and return success */
2254 *Wow64Process
= (pbi
!= 0);
2263 GetCommandLineA(VOID
)
2265 return BaseAnsiCommandLine
.Buffer
;
2273 GetCommandLineW(VOID
)
2275 return BaseUnicodeCommandLine
.Buffer
;
2283 ReadProcessMemory(IN HANDLE hProcess
,
2284 IN LPCVOID lpBaseAddress
,
2287 OUT SIZE_T
* lpNumberOfBytesRead
)
2292 Status
= NtReadVirtualMemory(hProcess
,
2293 (PVOID
)lpBaseAddress
,
2298 /* In user-mode, this parameter is optional */
2299 if (lpNumberOfBytesRead
) *lpNumberOfBytesRead
= nSize
;
2300 if (!NT_SUCCESS(Status
))
2303 BaseSetLastNTError(Status
);
2307 /* Return success */
2316 WriteProcessMemory(IN HANDLE hProcess
,
2317 IN LPVOID lpBaseAddress
,
2318 IN LPCVOID lpBuffer
,
2320 OUT SIZE_T
*lpNumberOfBytesWritten
)
2328 /* Set parameters for protect call */
2330 Base
= lpBaseAddress
;
2332 /* Check the current status */
2333 Status
= NtProtectVirtualMemory(hProcess
,
2336 PAGE_EXECUTE_READWRITE
,
2338 if (NT_SUCCESS(Status
))
2340 /* Check if we are unprotecting */
2341 UnProtect
= OldValue
& (PAGE_READWRITE
|
2343 PAGE_EXECUTE_READWRITE
|
2344 PAGE_EXECUTE_WRITECOPY
) ? FALSE
: TRUE
;
2347 /* Set the new protection */
2348 Status
= NtProtectVirtualMemory(hProcess
,
2354 /* Write the memory */
2355 Status
= NtWriteVirtualMemory(hProcess
,
2361 /* In Win32, the parameter is optional, so handle this case */
2362 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2364 if (!NT_SUCCESS(Status
))
2367 BaseSetLastNTError(Status
);
2371 /* Flush the ITLB */
2372 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2377 /* Check if we were read only */
2378 if (OldValue
& (PAGE_NOACCESS
| PAGE_READONLY
))
2380 /* Restore protection and fail */
2381 NtProtectVirtualMemory(hProcess
,
2386 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2388 /* Note: This is what Windows returns and code depends on it */
2389 return STATUS_ACCESS_VIOLATION
;
2392 /* Otherwise, do the write */
2393 Status
= NtWriteVirtualMemory(hProcess
,
2399 /* In Win32, the parameter is optional, so handle this case */
2400 if (lpNumberOfBytesWritten
) *lpNumberOfBytesWritten
= nSize
;
2402 /* And restore the protection */
2403 NtProtectVirtualMemory(hProcess
,
2408 if (!NT_SUCCESS(Status
))
2411 BaseSetLastNTError(STATUS_ACCESS_VIOLATION
);
2413 /* Note: This is what Windows returns and code depends on it */
2414 return STATUS_ACCESS_VIOLATION
;
2417 /* Flush the ITLB */
2418 NtFlushInstructionCache(hProcess
, lpBaseAddress
, nSize
);
2425 BaseSetLastNTError(Status
);
2435 ProcessIdToSessionId(IN DWORD dwProcessId
,
2436 OUT PDWORD pSessionId
)
2438 PROCESS_SESSION_INFORMATION SessionInformation
;
2439 OBJECT_ATTRIBUTES ObjectAttributes
;
2441 HANDLE ProcessHandle
;
2444 /* Do a quick check if the pointer is not writable */
2445 if (IsBadWritePtr(pSessionId
, sizeof(DWORD
)))
2448 SetLastError(ERROR_INVALID_PARAMETER
);
2452 /* Open the process passed in by ID */
2453 ClientId
.UniqueProcess
= UlongToHandle(dwProcessId
);
2454 ClientId
.UniqueThread
= 0;
2455 InitializeObjectAttributes(&ObjectAttributes
, NULL
, 0, NULL
, NULL
);
2456 Status
= NtOpenProcess(&ProcessHandle
,
2457 PROCESS_QUERY_INFORMATION
,
2460 if (NT_SUCCESS(Status
))
2462 /* Query the session ID from the kernel */
2463 Status
= NtQueryInformationProcess(ProcessHandle
,
2464 ProcessSessionInformation
,
2465 &SessionInformation
,
2466 sizeof(SessionInformation
),
2469 /* Close the handle and check if we suceeded */
2470 NtClose(ProcessHandle
);
2471 if (NT_SUCCESS(Status
))
2473 /* Return the session ID */
2474 *pSessionId
= SessionInformation
.SessionId
;
2479 /* Set error code and fail */
2480 BaseSetLastNTError(Status
);
2489 CreateProcessInternalW(HANDLE hToken
,
2490 LPCWSTR lpApplicationName
,
2491 LPWSTR lpCommandLine
,
2492 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
2493 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
2494 BOOL bInheritHandles
,
2495 DWORD dwCreationFlags
,
2496 LPVOID lpEnvironment
,
2497 LPCWSTR lpCurrentDirectory
,
2498 LPSTARTUPINFOW lpStartupInfo
,
2499 LPPROCESS_INFORMATION lpProcessInformation
,
2503 PROCESS_PRIORITY_CLASS PriorityClass
;
2504 BOOLEAN FoundQuotes
= FALSE
;
2505 BOOLEAN QuotesNeeded
= FALSE
;
2506 BOOLEAN CmdLineIsAppName
= FALSE
;
2507 UNICODE_STRING ApplicationName
= { 0, 0, NULL
};
2508 OBJECT_ATTRIBUTES LocalObjectAttributes
;
2509 POBJECT_ATTRIBUTES ObjectAttributes
;
2510 HANDLE hSection
= NULL
, hProcess
= NULL
, hThread
= NULL
, hDebug
= NULL
;
2511 SECTION_IMAGE_INFORMATION SectionImageInfo
;
2512 LPWSTR CurrentDirectory
= NULL
;
2513 LPWSTR CurrentDirectoryPart
;
2514 PROCESS_BASIC_INFORMATION ProcessBasicInfo
;
2515 STARTUPINFOW StartupInfo
;
2517 LPWSTR BatchCommandLine
;
2518 ULONG CmdLineLength
;
2519 UNICODE_STRING CommandLineString
;
2521 LPWSTR QuotedCmdLine
= NULL
;
2523 LPWSTR NullBuffer
= NULL
;
2524 LPWSTR NameBuffer
= NULL
;
2529 BOOLEAN SearchDone
= FALSE
;
2530 BOOLEAN Escape
= FALSE
;
2532 PPEB OurPeb
= NtCurrentPeb();
2536 WCHAR VdmPath
[MAX_PATH
];
2538 /* FIXME should process
2539 * HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
2540 * key (see http://blogs.msdn.com/oldnewthing/archive/2005/12/19/505449.aspx)
2543 DPRINT("CreateProcessW: lpApplicationName: %S lpCommandLine: %S"
2544 " lpEnvironment: %p lpCurrentDirectory: %S dwCreationFlags: %lx\n",
2545 lpApplicationName
, lpCommandLine
, lpEnvironment
, lpCurrentDirectory
,
2548 /* Flags we don't handle yet */
2549 if (dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
)
2551 DPRINT1("CREATE_SEPARATE_WOW_VDM not handled\n");
2553 if (dwCreationFlags
& CREATE_SHARED_WOW_VDM
)
2555 DPRINT1("CREATE_SHARED_WOW_VDM not handled\n");
2557 if (dwCreationFlags
& CREATE_FORCEDOS
)
2559 DPRINT1("CREATE_FORCEDOS not handled\n");
2562 /* Fail on this flag, it's only valid with the WithLogonW function */
2563 if (dwCreationFlags
& CREATE_PRESERVE_CODE_AUTHZ_LEVEL
)
2565 DPRINT1("Invalid flag used\n");
2566 SetLastError(ERROR_INVALID_PARAMETER
);
2570 /* This combination is illegal (see MSDN) */
2571 if ((dwCreationFlags
& (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
)) ==
2572 (DETACHED_PROCESS
| CREATE_NEW_CONSOLE
))
2574 DPRINT1("Invalid flag combo used\n");
2575 SetLastError(ERROR_INVALID_PARAMETER
);
2579 /* Another illegal combo */
2580 if ((dwCreationFlags
& (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
)) ==
2581 (CREATE_SEPARATE_WOW_VDM
| CREATE_SHARED_WOW_VDM
))
2583 DPRINT1("Invalid flag combo used\n");
2584 SetLastError(ERROR_INVALID_PARAMETER
);
2588 if (lpCurrentDirectory
)
2590 if ((GetFileAttributesW(lpCurrentDirectory
) == INVALID_FILE_ATTRIBUTES
) ||
2591 !(GetFileAttributesW(lpCurrentDirectory
) & FILE_ATTRIBUTE_DIRECTORY
))
2593 SetLastError(ERROR_DIRECTORY
);
2599 * We're going to modify and mask out flags and stuff in lpStartupInfo,
2600 * so we'll use our own local copy for that.
2602 StartupInfo
= *lpStartupInfo
;
2604 /* FIXME: Use default Separate/Shared VDM Flag */
2606 /* If we are inside a Job, use Separate VDM so it won't escape the Job */
2607 if (!(dwCreationFlags
& CREATE_SEPARATE_WOW_VDM
))
2609 if (NtIsProcessInJob(NtCurrentProcess(), NULL
))
2611 /* Remove the shared flag and add the separate flag. */
2612 dwCreationFlags
= (dwCreationFlags
&~ CREATE_SHARED_WOW_VDM
) |
2613 CREATE_SEPARATE_WOW_VDM
;
2617 /* Get the path to the VDM host */
2618 Length
= GetSystemDirectoryW(VdmPath
, MAX_PATH
- wcslen(NTVDM_STRING
));
2619 if ((Length
== 0) || (Length
>= MAX_PATH
- wcslen(NTVDM_STRING
)))
2621 /* System path not found for some reason, fail */
2622 SetLastError(ERROR_INVALID_NAME
);
2625 wcscat(VdmPath
, NTVDM_STRING
);
2628 * According to some sites, ShellExecuteEx uses an undocumented flag to
2629 * send private handle data (such as HMONITOR or HICON). See:
2630 * www.catch22.net/tuts/undoc01.asp. This implies that we can't use the
2631 * standard handles anymore since we'd be overwriting this private data
2633 if ((StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
2634 (StartupInfo
.dwFlags
& (STARTF_USEHOTKEY
| STARTF_SHELLPRIVATE
)))
2636 StartupInfo
.dwFlags
&= ~STARTF_USESTDHANDLES
;
2639 /* Start by zeroing out the fields */
2640 RtlZeroMemory(lpProcessInformation
, sizeof(PROCESS_INFORMATION
));
2642 /* Easy stuff first, convert the process priority class */
2643 PriorityClass
.Foreground
= FALSE
;
2644 PriorityClass
.PriorityClass
= (UCHAR
)BasepConvertPriorityClass(dwCreationFlags
);
2648 /* Search for escape sequences */
2649 ScanString
= lpCommandLine
;
2650 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
2653 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\\')
2661 /* Get the application name and do all the proper formating necessary */
2663 /* See if we have an application name (oh please let us have one!) */
2664 if (!lpApplicationName
)
2666 /* The fun begins */
2667 NameBuffer
= RtlAllocateHeap(RtlGetProcessHeap(),
2669 MAX_PATH
* sizeof(WCHAR
));
2670 if (NameBuffer
== NULL
)
2672 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2676 /* This is all we have to work with :( */
2677 lpApplicationName
= lpCommandLine
;
2679 /* Initialize our friends at the beginning */
2680 NullBuffer
= (LPWSTR
)lpApplicationName
;
2681 ScanString
= (LPWSTR
)lpApplicationName
;
2683 /* We will start by looking for a quote */
2684 if (*ScanString
== L
'\"')
2686 /* That was quick */
2689 /* Advance past quote */
2691 lpApplicationName
= ScanString
;
2693 /* Find the closing quote */
2696 if (*ScanString
== L
'\"' && *(ScanString
- 1) != L
'^')
2699 NullBuffer
= ScanString
;
2706 NullBuffer
= ScanString
;
2711 /* No quotes, so we'll be looking for white space */
2713 /* Reset the pointer */
2714 lpApplicationName
= lpCommandLine
;
2716 /* Find whitespace of Tab */
2719 if (*ScanString
== ' ' || *ScanString
== '\t')
2722 NullBuffer
= ScanString
;
2728 NullBuffer
= ScanString
;
2732 /* Set the Null Buffer */
2733 SaveChar
= *NullBuffer
;
2734 *NullBuffer
= UNICODE_NULL
;
2736 /* Do a search for the file */
2737 DPRINT("Ready for SearchPathW: %S\n", lpApplicationName
);
2738 RetVal
= SearchPathW(NULL
,
2743 NULL
) * sizeof(WCHAR
);
2745 /* Did it find something? */
2748 /* Get file attributes */
2749 ULONG Attributes
= GetFileAttributesW(NameBuffer
);
2750 if (Attributes
& FILE_ATTRIBUTE_DIRECTORY
)
2752 /* Give it a length of 0 to fail, this was a directory. */
2758 RetVal
+= sizeof(WCHAR
);
2762 /* Now check if we have a file, and if the path size is OK */
2763 if (!RetVal
|| RetVal
>= (MAX_PATH
* sizeof(WCHAR
)))
2768 /* We failed, try to get the Path Type */
2769 DPRINT("SearchPathW failed. Retval: %ld\n", RetVal
);
2770 PathType
= RtlDetermineDosPathNameType_U(lpApplicationName
);
2772 /* If it's not relative, try to get the error */
2773 if (PathType
!= RtlPathTypeRelative
)
2775 /* This should fail, and give us a detailed LastError */
2776 hFile
= CreateFileW(lpApplicationName
,
2778 FILE_SHARE_READ
| FILE_SHARE_WRITE
,
2781 FILE_ATTRIBUTE_NORMAL
,
2784 /* Did it actually NOT fail? */
2785 if (hFile
!= INVALID_HANDLE_VALUE
)
2787 /* Fake the error */
2789 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2794 /* Immediately set the error */
2795 BaseSetLastNTError(STATUS_OBJECT_NAME_NOT_FOUND
);
2798 /* Did we already fail once? */
2801 SetLastError(Error
);
2805 /* Not yet, cache it */
2806 Error
= GetLastError();
2809 /* Put back the command line */
2810 *NullBuffer
= SaveChar
;
2811 lpApplicationName
= NameBuffer
;
2814 * If the search isn't done and we still have cmdline
2815 * then start over. Ex: c:\ha ha ha\haha.exe
2817 if (*ScanString
&& !SearchDone
)
2819 /* Move in the buffer */
2821 NullBuffer
= ScanString
;
2823 /* We will have to add a quote, since there is a space*/
2824 QuotesNeeded
= TRUE
;
2826 /* And we will also fake the fact we found one */
2833 /* We totally failed */
2837 /* Put back the command line */
2838 *NullBuffer
= SaveChar
;
2839 lpApplicationName
= NameBuffer
;
2840 DPRINT("SearchPathW suceeded (%ld): %S\n", RetVal
, NameBuffer
);
2842 else if (!lpCommandLine
|| *lpCommandLine
== UNICODE_NULL
)
2844 /* We have an app name (good!) but no command line */
2845 CmdLineIsAppName
= TRUE
;
2846 lpCommandLine
= (LPWSTR
)lpApplicationName
;
2849 /* At this point the name has been toyed with enough to be openable */
2850 Status
= BasepMapFile(lpApplicationName
, &hSection
, &ApplicationName
);
2852 /* Check for failure */
2853 if (!NT_SUCCESS(Status
))
2855 /* Could be a non-PE File */
2858 /* Check if the Kernel tells us it's not even valid MZ */
2859 case STATUS_INVALID_IMAGE_NE_FORMAT
:
2860 case STATUS_INVALID_IMAGE_PROTECT
:
2861 case STATUS_INVALID_IMAGE_NOT_MZ
:
2863 /* If it's a DOS app, use VDM */
2864 if (BaseIsDosApplication(&ApplicationName
, Status
))
2866 DPRINT1("Launching VDM...\n");
2867 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2868 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2869 return CreateProcessW(VdmPath
,
2870 (LPWSTR
)((ULONG_PTR
)lpApplicationName
), /* FIXME: Buffer must be writable!!! */
2871 lpProcessAttributes
,
2878 lpProcessInformation
);
2880 /* It's a batch file */
2881 Extension
= &ApplicationName
.Buffer
[ApplicationName
.Length
/
2884 /* Make sure the extensions are correct */
2885 if (_wcsnicmp(Extension
, L
".bat", 4) && _wcsnicmp(Extension
, L
".cmd", 4))
2887 SetLastError(ERROR_BAD_EXE_FORMAT
);
2891 /* Calculate the length of the command line */
2892 CmdLineLength
= wcslen(CMD_STRING
) + wcslen(lpCommandLine
) + 1;
2894 /* If we found quotes, then add them into the length size */
2895 if (CmdLineIsAppName
|| FoundQuotes
) CmdLineLength
+= 2;
2896 CmdLineLength
*= sizeof(WCHAR
);
2898 /* Allocate space for the new command line */
2899 BatchCommandLine
= RtlAllocateHeap(RtlGetProcessHeap(),
2902 if (BatchCommandLine
== NULL
)
2904 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
2909 wcscpy(BatchCommandLine
, CMD_STRING
);
2910 if (CmdLineIsAppName
|| FoundQuotes
)
2912 wcscat(BatchCommandLine
, L
"\"");
2914 wcscat(BatchCommandLine
, lpCommandLine
);
2915 if (CmdLineIsAppName
|| FoundQuotes
)
2917 wcscat(BatchCommandLine
, L
"\"");
2920 /* Create it as a Unicode String */
2921 RtlInitUnicodeString(&CommandLineString
, BatchCommandLine
);
2923 /* Set the command line to this */
2924 lpCommandLine
= CommandLineString
.Buffer
;
2925 lpApplicationName
= NULL
;
2928 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2929 ApplicationName
.Buffer
= NULL
;
2933 case STATUS_INVALID_IMAGE_WIN_16
:
2935 /* It's a Win16 Image, use VDM */
2936 DPRINT1("Launching VDM...\n");
2937 RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
2938 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
2939 return CreateProcessW(VdmPath
,
2940 (LPWSTR
)((ULONG_PTR
)lpApplicationName
), /* FIXME: Buffer must be writable!!! */
2941 lpProcessAttributes
,
2948 lpProcessInformation
);
2950 case STATUS_OBJECT_NAME_NOT_FOUND
:
2951 case STATUS_OBJECT_PATH_NOT_FOUND
:
2952 BaseSetLastNTError(Status
);
2956 /* Invalid Image Type */
2957 SetLastError(ERROR_BAD_EXE_FORMAT
);
2962 /* Use our desktop if we didn't get any */
2963 if (!StartupInfo
.lpDesktop
)
2965 StartupInfo
.lpDesktop
= OurPeb
->ProcessParameters
->DesktopInfo
.Buffer
;
2968 /* FIXME: Check if Application is allowed to run */
2970 /* FIXME: Allow CREATE_SEPARATE only for WOW Apps, once we have that. */
2972 /* Get some information about the executable */
2973 Status
= NtQuerySection(hSection
,
2974 SectionImageInformation
,
2976 sizeof(SectionImageInfo
),
2978 if(!NT_SUCCESS(Status
))
2980 DPRINT1("Unable to get SectionImageInformation, status 0x%x\n", Status
);
2981 BaseSetLastNTError(Status
);
2985 /* Don't execute DLLs */
2986 if (SectionImageInfo
.ImageCharacteristics
& IMAGE_FILE_DLL
)
2988 DPRINT1("Can't execute a DLL\n");
2989 SetLastError(ERROR_BAD_EXE_FORMAT
);
2993 /* FIXME: Check for Debugger */
2995 /* FIXME: Check if Machine Type and SubSys Version Match */
2997 /* We don't support POSIX or anything else for now */
2998 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
!= SectionImageInfo
.SubSystemType
&&
2999 IMAGE_SUBSYSTEM_WINDOWS_CUI
!= SectionImageInfo
.SubSystemType
)
3001 DPRINT1("Invalid subsystem %d\n", SectionImageInfo
.SubSystemType
);
3003 * Despite the name of the error code suggests, it corresponds to the
3004 * well-known "The %1 application cannot be run in Win32 mode" message.
3006 SetLastError(ERROR_CHILD_NOT_COMPLETE
);
3010 if (IMAGE_SUBSYSTEM_WINDOWS_GUI
== SectionImageInfo
.SubSystemType
)
3012 /* Do not create a console for GUI applications */
3013 dwCreationFlags
&= ~CREATE_NEW_CONSOLE
;
3014 dwCreationFlags
|= DETACHED_PROCESS
;
3017 /* Initialize the process object attributes */
3018 ObjectAttributes
= BaseFormatObjectAttributes(&LocalObjectAttributes
,
3019 lpProcessAttributes
,
3022 /* Check if we're going to be debugged */
3023 if (dwCreationFlags
& DEBUG_PROCESS
)
3025 /* FIXME: Set process flag */
3028 /* Check if we're going to be debugged */
3029 if (dwCreationFlags
& (DEBUG_PROCESS
| DEBUG_ONLY_THIS_PROCESS
))
3031 /* Connect to DbgUi */
3032 Status
= DbgUiConnectToDbg();
3033 if (!NT_SUCCESS(Status
))
3035 DPRINT1("Failed to connect to DbgUI!\n");
3036 BaseSetLastNTError(Status
);
3040 /* Get the debug object */
3041 hDebug
= DbgUiGetThreadDebugObject();
3043 /* Check if only this process will be debugged */
3044 if (dwCreationFlags
& DEBUG_ONLY_THIS_PROCESS
)
3046 /* Set process flag */
3047 hDebug
= (HANDLE
)((ULONG_PTR
)hDebug
| 0x1);
3051 /* Create the Process */
3052 Status
= NtCreateProcess(&hProcess
,
3056 (BOOLEAN
)bInheritHandles
,
3060 if (!NT_SUCCESS(Status
))
3062 DPRINT1("Unable to create process, status 0x%x\n", Status
);
3063 BaseSetLastNTError(Status
);
3067 if (PriorityClass
.PriorityClass
!= PROCESS_PRIORITY_CLASS_INVALID
)
3070 Status
= NtSetInformationProcess(hProcess
,
3071 ProcessPriorityClass
,
3073 sizeof(PROCESS_PRIORITY_CLASS
));
3074 if(!NT_SUCCESS(Status
))
3076 DPRINT1("Unable to set new process priority, status 0x%x\n", Status
);
3077 BaseSetLastNTError(Status
);
3082 /* Set Error Mode */
3083 if (dwCreationFlags
& CREATE_DEFAULT_ERROR_MODE
)
3085 ULONG ErrorMode
= SEM_FAILCRITICALERRORS
;
3086 NtSetInformationProcess(hProcess
,
3087 ProcessDefaultHardErrorMode
,
3092 /* Convert the directory to a full path */
3093 if (lpCurrentDirectory
)
3095 /* Allocate a buffer */
3096 CurrentDirectory
= RtlAllocateHeap(RtlGetProcessHeap(),
3098 (MAX_PATH
+ 1) * sizeof(WCHAR
));
3099 if (CurrentDirectory
== NULL
)
3101 DPRINT1("Cannot allocate memory for directory name\n");
3102 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3106 /* Get the length */
3107 if (GetFullPathNameW(lpCurrentDirectory
,
3110 &CurrentDirectoryPart
) > MAX_PATH
)
3112 DPRINT1("Directory name too long\n");
3113 SetLastError(ERROR_DIRECTORY
);
3118 /* Insert quotes if needed */
3119 if (QuotesNeeded
|| CmdLineIsAppName
)
3121 /* Allocate a buffer */
3122 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3124 (wcslen(lpCommandLine
) + 2 + 1) *
3126 if (QuotedCmdLine
== NULL
)
3128 DPRINT1("Cannot allocate memory for quoted command line\n");
3129 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3133 /* Copy the first quote */
3134 wcscpy(QuotedCmdLine
, L
"\"");
3136 /* Save a null char */
3139 SaveChar
= *NullBuffer
;
3140 *NullBuffer
= UNICODE_NULL
;
3143 /* Add the command line and the finishing quote */
3144 wcscat(QuotedCmdLine
, lpCommandLine
);
3145 wcscat(QuotedCmdLine
, L
"\"");
3147 /* Add the null char */
3150 *NullBuffer
= SaveChar
;
3151 wcscat(QuotedCmdLine
, NullBuffer
);
3154 DPRINT("Quoted CmdLine: %S\n", QuotedCmdLine
);
3159 if (QuotedCmdLine
== NULL
)
3161 QuotedCmdLine
= RtlAllocateHeap(RtlGetProcessHeap(),
3163 (wcslen(lpCommandLine
) + 1) * sizeof(WCHAR
));
3164 if (QuotedCmdLine
== NULL
)
3166 SetLastError(ERROR_NOT_ENOUGH_MEMORY
);
3169 wcscpy(QuotedCmdLine
, lpCommandLine
);
3172 ScanString
= QuotedCmdLine
;
3173 while (NULL
!= (ScanString
= wcschr(ScanString
, L
'^')))
3176 if (*ScanString
== L
'\"' || *ScanString
== L
'^' || *ScanString
== L
'\\')
3178 memmove(ScanString
-1, ScanString
, wcslen(ScanString
) * sizeof(WCHAR
) + sizeof(WCHAR
));
3183 /* Get the Process Information */
3184 Status
= NtQueryInformationProcess(hProcess
,
3185 ProcessBasicInformation
,
3187 sizeof(ProcessBasicInfo
),
3190 /* Convert the environment */
3191 if(lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3193 lpEnvironment
= BasepConvertUnicodeEnvironment(&EnvSize
, lpEnvironment
);
3194 if (!lpEnvironment
) goto Cleanup
;
3197 /* Create Process Environment */
3198 RemotePeb
= ProcessBasicInfo
.PebBaseAddress
;
3199 Ret
= BasePushProcessParameters(0,
3202 (LPWSTR
)lpApplicationName
,
3204 (QuotesNeeded
|| CmdLineIsAppName
|| Escape
) ?
3205 QuotedCmdLine
: lpCommandLine
,
3213 if (!Ret
) goto Cleanup
;
3215 /* Cleanup Environment */
3216 if (lpEnvironment
&& !(dwCreationFlags
& CREATE_UNICODE_ENVIRONMENT
))
3218 RtlDestroyEnvironment(lpEnvironment
);
3221 /* Close the section */
3225 /* Duplicate the handles if needed */
3226 if (!bInheritHandles
&& !(StartupInfo
.dwFlags
& STARTF_USESTDHANDLES
) &&
3227 SectionImageInfo
.SubSystemType
== IMAGE_SUBSYSTEM_WINDOWS_CUI
)
3229 PRTL_USER_PROCESS_PARAMETERS RemoteParameters
;
3231 /* Get the remote parameters */
3232 Status
= NtReadVirtualMemory(hProcess
,
3233 &RemotePeb
->ProcessParameters
,
3237 if (!NT_SUCCESS(Status
))
3239 DPRINT1("Failed to read memory\n");
3243 /* Duplicate and write the handles */
3244 BasepDuplicateAndWriteHandle(hProcess
,
3245 OurPeb
->ProcessParameters
->StandardInput
,
3246 &RemoteParameters
->StandardInput
);
3247 BasepDuplicateAndWriteHandle(hProcess
,
3248 OurPeb
->ProcessParameters
->StandardOutput
,
3249 &RemoteParameters
->StandardOutput
);
3250 BasepDuplicateAndWriteHandle(hProcess
,
3251 OurPeb
->ProcessParameters
->StandardError
,
3252 &RemoteParameters
->StandardError
);
3255 /* Create the first thread */
3256 DPRINT("Creating thread for process (EntryPoint = 0x%p)\n",
3257 SectionImageInfo
.TransferAddress
);
3258 hThread
= BasepCreateFirstThread(hProcess
,
3264 if (hThread
== NULL
)
3266 DPRINT1("Could not create Initial Thread\n");
3267 /* FIXME - set last error code */
3271 if (!(dwCreationFlags
& CREATE_SUSPENDED
))
3273 NtResumeThread(hThread
, &Dummy
);
3277 lpProcessInformation
->dwProcessId
= (DWORD
)ClientId
.UniqueProcess
;
3278 lpProcessInformation
->dwThreadId
= (DWORD
)ClientId
.UniqueThread
;
3279 lpProcessInformation
->hProcess
= hProcess
;
3280 lpProcessInformation
->hThread
= hThread
;
3281 DPRINT("hThread[%p]: %p inside hProcess[%p]: %p\n", hThread
,
3282 ClientId
.UniqueThread
, ClientId
.UniqueProcess
, hProcess
);
3283 hProcess
= hThread
= NULL
;
3287 /* De-allocate heap strings */
3288 if (NameBuffer
) RtlFreeHeap(RtlGetProcessHeap(), 0, NameBuffer
);
3289 if (ApplicationName
.Buffer
)
3290 RtlFreeHeap(RtlGetProcessHeap(), 0, ApplicationName
.Buffer
);
3291 if (CurrentDirectory
) RtlFreeHeap(RtlGetProcessHeap(), 0, CurrentDirectory
);
3292 if (QuotedCmdLine
) RtlFreeHeap(RtlGetProcessHeap(), 0, QuotedCmdLine
);
3294 /* Kill any handles still alive */
3295 if (hSection
) NtClose(hSection
);
3298 /* We don't know any more details than this */
3299 NtTerminateProcess(hProcess
, STATUS_UNSUCCESSFUL
);
3302 if (hProcess
) NtClose(hProcess
);
3304 /* Return Success */
3313 CreateProcessW(LPCWSTR lpApplicationName
,
3314 LPWSTR lpCommandLine
,
3315 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3316 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3317 BOOL bInheritHandles
,
3318 DWORD dwCreationFlags
,
3319 LPVOID lpEnvironment
,
3320 LPCWSTR lpCurrentDirectory
,
3321 LPSTARTUPINFOW lpStartupInfo
,
3322 LPPROCESS_INFORMATION lpProcessInformation
)
3324 /* Call the internal (but exported) version */
3325 return CreateProcessInternalW(0,
3328 lpProcessAttributes
,
3335 lpProcessInformation
,
3344 CreateProcessInternalA(HANDLE hToken
,
3345 LPCSTR lpApplicationName
,
3346 LPSTR lpCommandLine
,
3347 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3348 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3349 BOOL bInheritHandles
,
3350 DWORD dwCreationFlags
,
3351 LPVOID lpEnvironment
,
3352 LPCSTR lpCurrentDirectory
,
3353 LPSTARTUPINFOA lpStartupInfo
,
3354 LPPROCESS_INFORMATION lpProcessInformation
,
3357 PUNICODE_STRING CommandLine
= NULL
;
3358 UNICODE_STRING DummyString
;
3359 UNICODE_STRING LiveCommandLine
;
3360 UNICODE_STRING ApplicationName
;
3361 UNICODE_STRING CurrentDirectory
;
3363 STARTUPINFOW StartupInfo
;
3365 DPRINT("dwCreationFlags %x, lpEnvironment %x, lpCurrentDirectory %x, "
3366 "lpStartupInfo %x, lpProcessInformation %x\n",
3367 dwCreationFlags
, lpEnvironment
, lpCurrentDirectory
,
3368 lpStartupInfo
, lpProcessInformation
);
3370 /* Copy Startup Info */
3371 RtlMoveMemory(&StartupInfo
, lpStartupInfo
, sizeof(*lpStartupInfo
));
3373 /* Initialize all strings to nothing */
3374 LiveCommandLine
.Buffer
= NULL
;
3375 DummyString
.Buffer
= NULL
;
3376 ApplicationName
.Buffer
= NULL
;
3377 CurrentDirectory
.Buffer
= NULL
;
3378 StartupInfo
.lpDesktop
= NULL
;
3379 StartupInfo
.lpReserved
= NULL
;
3380 StartupInfo
.lpTitle
= NULL
;
3382 /* Convert the Command line */
3385 /* If it's too long, then we'll have a problem */
3386 if ((strlen(lpCommandLine
) + 1) * sizeof(WCHAR
) <
3387 NtCurrentTeb()->StaticUnicodeString
.MaximumLength
)
3389 /* Cache it in the TEB */
3390 CommandLine
= Basep8BitStringToStaticUnicodeString(lpCommandLine
);
3394 /* Use a dynamic version */
3395 Basep8BitStringToDynamicUnicodeString(&LiveCommandLine
,
3401 /* The logic below will use CommandLine, so we must make it valid */
3402 CommandLine
= &DummyString
;
3405 /* Convert the Name and Directory */
3406 if (lpApplicationName
)
3408 Basep8BitStringToDynamicUnicodeString(&ApplicationName
,
3411 if (lpCurrentDirectory
)
3413 Basep8BitStringToDynamicUnicodeString(&CurrentDirectory
,
3414 lpCurrentDirectory
);
3417 /* Now convert Startup Strings */
3418 if (lpStartupInfo
->lpReserved
)
3420 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpReserved
,
3421 &StartupInfo
.lpReserved
);
3423 if (lpStartupInfo
->lpDesktop
)
3425 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpDesktop
,
3426 &StartupInfo
.lpDesktop
);
3428 if (lpStartupInfo
->lpTitle
)
3430 BasepAnsiStringToHeapUnicodeString(lpStartupInfo
->lpTitle
,
3431 &StartupInfo
.lpTitle
);
3434 /* Call the Unicode function */
3435 bRetVal
= CreateProcessInternalW(hToken
,
3436 ApplicationName
.Buffer
,
3437 LiveCommandLine
.Buffer
?
3438 LiveCommandLine
.Buffer
: CommandLine
->Buffer
,
3439 lpProcessAttributes
,
3444 CurrentDirectory
.Buffer
,
3446 lpProcessInformation
,
3450 RtlFreeUnicodeString(&ApplicationName
);
3451 RtlFreeUnicodeString(&LiveCommandLine
);
3452 RtlFreeUnicodeString(&CurrentDirectory
);
3453 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpDesktop
);
3454 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpReserved
);
3455 RtlFreeHeap(RtlGetProcessHeap(), 0, StartupInfo
.lpTitle
);
3457 /* Return what Unicode did */
3462 * FUNCTION: The CreateProcess function creates a new process and its
3463 * primary thread. The new process executes the specified executable file
3466 * lpApplicationName = Pointer to name of executable module
3467 * lpCommandLine = Pointer to command line string
3468 * lpProcessAttributes = Process security attributes
3469 * lpThreadAttributes = Thread security attributes
3470 * bInheritHandles = Handle inheritance flag
3471 * dwCreationFlags = Creation flags
3472 * lpEnvironment = Pointer to new environment block
3473 * lpCurrentDirectory = Pointer to current directory name
3474 * lpStartupInfo = Pointer to startup info
3475 * lpProcessInformation = Pointer to process information
3481 CreateProcessA(LPCSTR lpApplicationName
,
3482 LPSTR lpCommandLine
,
3483 LPSECURITY_ATTRIBUTES lpProcessAttributes
,
3484 LPSECURITY_ATTRIBUTES lpThreadAttributes
,
3485 BOOL bInheritHandles
,
3486 DWORD dwCreationFlags
,
3487 LPVOID lpEnvironment
,
3488 LPCSTR lpCurrentDirectory
,
3489 LPSTARTUPINFOA lpStartupInfo
,
3490 LPPROCESS_INFORMATION lpProcessInformation
)
3492 /* Call the internal (but exported) version */
3493 return CreateProcessInternalA(0,
3496 lpProcessAttributes
,
3503 lpProcessInformation
,
3512 WinExec(LPCSTR lpCmdLine
,
3515 STARTUPINFOA StartupInfo
;
3516 PROCESS_INFORMATION ProcessInformation
;
3519 RtlZeroMemory(&StartupInfo
, sizeof(StartupInfo
));
3520 StartupInfo
.cb
= sizeof(STARTUPINFOA
);
3521 StartupInfo
.wShowWindow
= (WORD
)uCmdShow
;
3522 StartupInfo
.dwFlags
= 0;
3524 if (!CreateProcessA(NULL
,
3533 &ProcessInformation
))
3535 dosErr
= GetLastError();
3536 return dosErr
< 32 ? dosErr
: ERROR_BAD_FORMAT
;
3539 if (NULL
!= UserWaitForInputIdleRoutine
)
3541 UserWaitForInputIdleRoutine(ProcessInformation
.hProcess
,
3545 NtClose(ProcessInformation
.hProcess
);
3546 NtClose(ProcessInformation
.hThread
);
3548 return 33; /* Something bigger than 31 means success. */