2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ps/thread.c
5 * PURPOSE: Process Manager: Thread Management
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Thomas Weidenmueller (w3seek@reactos.org)
10 /* INCLUDES ****************************************************************/
16 /* GLOBALS ******************************************************************/
18 extern BOOLEAN CcPfEnablePrefetcher
;
19 extern ULONG MmReadClusterSize
;
20 POBJECT_TYPE PsThreadType
= NULL
;
22 /* PRIVATE FUNCTIONS *********************************************************/
26 PspUserThreadStartup(IN PKSTART_ROUTINE StartRoutine
,
27 IN PVOID StartContext
)
31 BOOLEAN DeadThread
= FALSE
;
34 PSTRACE(PS_THREAD_DEBUG
,
35 "StartRoutine: %p StartContext: %p\n", StartRoutine
, StartContext
);
37 /* Go to Passive Level */
38 KeLowerIrql(PASSIVE_LEVEL
);
39 Thread
= PsGetCurrentThread();
41 /* Check if the thread is dead */
42 if (Thread
->DeadThread
)
44 /* Remember that we're dead */
49 /* Get the Locale ID and save Preferred Proc */
51 Teb
->CurrentLocale
= MmGetSessionLocaleId();
52 Teb
->IdealProcessor
= Thread
->Tcb
.IdealProcessor
;
55 /* Check if this is a dead thread, or if we're hiding */
56 if (!(Thread
->DeadThread
) && !(Thread
->HideFromDebugger
))
58 /* We're not, so notify the debugger */
59 DbgkCreateThread(Thread
, StartContext
);
62 /* Make sure we're not already dead */
65 /* Check if the Prefetcher is enabled */
66 if (CcPfEnablePrefetcher
)
68 /* FIXME: Prepare to prefetch this process */
72 KeRaiseIrql(APC_LEVEL
, &OldIrql
);
74 /* Queue the User APC */
75 KiInitializeUserApc(KeGetExceptionFrame(&Thread
->Tcb
),
76 KeGetTrapFrame(&Thread
->Tcb
),
77 PspSystemDllEntryPoint
,
82 /* Lower it back to passive */
83 KeLowerIrql(PASSIVE_LEVEL
);
87 /* We're dead, kill us now */
88 PspTerminateThreadByPointer(Thread
,
89 STATUS_THREAD_IS_TERMINATING
,
93 /* Do we have a cookie set yet? */
94 while (!SharedUserData
->Cookie
)
96 LARGE_INTEGER SystemTime
;
100 /* Generate a new cookie */
101 KeQuerySystemTime(&SystemTime
);
102 Prcb
= KeGetCurrentPrcb();
103 NewCookie
= (Prcb
->MmPageFaultCount
^ Prcb
->InterruptTime
^
104 SystemTime
.u
.LowPart
^ SystemTime
.u
.HighPart
^
105 (ULONG
)(ULONG_PTR
)&SystemTime
);
107 /* Set the new cookie*/
108 InterlockedCompareExchange((LONG
*)&SharedUserData
->Cookie
,
115 PspUnhandledExceptionInSystemThread(PEXCEPTION_POINTERS ExceptionPointers
)
117 /* Print debugging information */
118 DPRINT1("PS: Unhandled Kernel Mode Exception Pointers = 0x%p\n",
120 DPRINT1("Code %x Addr %p Info0 %p Info1 %p Info2 %p Info3 %p\n",
121 ExceptionPointers
->ExceptionRecord
->ExceptionCode
,
122 ExceptionPointers
->ExceptionRecord
->ExceptionAddress
,
123 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[0],
124 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[1],
125 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[2],
126 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[3]);
128 /* Bugcheck the system */
129 KeBugCheckEx(SYSTEM_THREAD_EXCEPTION_NOT_HANDLED
,
130 ExceptionPointers
->ExceptionRecord
->ExceptionCode
,
131 (ULONG_PTR
)ExceptionPointers
->ExceptionRecord
->ExceptionAddress
,
132 (ULONG_PTR
)ExceptionPointers
->ExceptionRecord
,
133 (ULONG_PTR
)ExceptionPointers
->ContextRecord
);
139 PspSystemThreadStartup(IN PKSTART_ROUTINE StartRoutine
,
140 IN PVOID StartContext
)
143 PSTRACE(PS_THREAD_DEBUG
,
144 "StartRoutine: %p StartContext: %p\n", StartRoutine
, StartContext
);
146 /* Unlock the dispatcher Database */
147 KeLowerIrql(PASSIVE_LEVEL
);
148 Thread
= PsGetCurrentThread();
150 /* Make sure the thread isn't gone */
153 if (!(Thread
->Terminated
) && !(Thread
->DeadThread
))
155 /* Call the Start Routine */
156 StartRoutine(StartContext
);
159 _SEH2_EXCEPT(PspUnhandledExceptionInSystemThread(_SEH2_GetExceptionInformation()))
161 /* Bugcheck if we got here */
162 KeBugCheck(KMODE_EXCEPTION_NOT_HANDLED
);
166 /* Exit the thread */
167 PspTerminateThreadByPointer(Thread
, STATUS_SUCCESS
, TRUE
);
172 PspCreateThread(OUT PHANDLE ThreadHandle
,
173 IN ACCESS_MASK DesiredAccess
,
174 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL
,
175 IN HANDLE ProcessHandle
,
176 IN PEPROCESS TargetProcess
,
177 OUT PCLIENT_ID ClientId
,
178 IN PCONTEXT ThreadContext
,
179 IN PINITIAL_TEB InitialTeb
,
180 IN BOOLEAN CreateSuspended
,
181 IN PKSTART_ROUTINE StartRoutine OPTIONAL
,
182 IN PVOID StartContext OPTIONAL
)
188 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
189 NTSTATUS Status
, AccessStatus
;
190 HANDLE_TABLE_ENTRY CidEntry
;
191 ACCESS_STATE LocalAccessState
;
192 PACCESS_STATE AccessState
= &LocalAccessState
;
193 AUX_ACCESS_DATA AuxData
;
194 BOOLEAN Result
, SdAllocated
;
195 PSECURITY_DESCRIPTOR SecurityDescriptor
;
196 SECURITY_SUBJECT_CONTEXT SubjectContext
;
198 PSTRACE(PS_THREAD_DEBUG
,
199 "ThreadContext: %p TargetProcess: %p ProcessHandle: %p\n",
200 ThreadContext
, TargetProcess
, ProcessHandle
);
202 /* If we were called from PsCreateSystemThread, then we're kernel mode */
203 if (StartRoutine
) PreviousMode
= KernelMode
;
205 /* Reference the Process by handle or pointer, depending on what we got */
208 /* Normal thread or System Thread */
209 Status
= ObReferenceObjectByHandle(ProcessHandle
,
210 PROCESS_CREATE_THREAD
,
219 /* System thread inside System Process, or Normal Thread with a bug */
222 /* Reference the Process by Pointer */
223 ObReferenceObject(TargetProcess
);
224 Process
= TargetProcess
;
225 Status
= STATUS_SUCCESS
;
229 /* Fake ObReference returning this */
230 Status
= STATUS_INVALID_HANDLE
;
234 /* Check for success */
235 if (!NT_SUCCESS(Status
)) return Status
;
237 /* Also make sure that User-Mode isn't trying to create a system thread */
238 if ((PreviousMode
!= KernelMode
) && (Process
== PsInitialSystemProcess
))
241 ObDereferenceObject(Process
);
242 return STATUS_INVALID_HANDLE
;
245 /* Create Thread Object */
246 Status
= ObCreateObject(PreviousMode
,
255 if (!NT_SUCCESS(Status
))
257 /* We failed; dereference the process and exit */
258 ObDereferenceObject(Process
);
262 /* Zero the Object entirely */
263 RtlZeroMemory(Thread
, sizeof(ETHREAD
));
265 /* Initialize rundown protection */
266 ExInitializeRundownProtection(&Thread
->RundownProtect
);
268 /* Initialize exit code */
269 Thread
->ExitStatus
= STATUS_PENDING
;
271 /* Set the Process CID */
272 Thread
->ThreadsProcess
= Process
;
273 Thread
->Cid
.UniqueProcess
= Process
->UniqueProcessId
;
275 /* Create Cid Handle */
276 CidEntry
.Object
= Thread
;
277 CidEntry
.GrantedAccess
= 0;
278 Thread
->Cid
.UniqueThread
= ExCreateHandle(PspCidTable
, &CidEntry
);
279 if (!Thread
->Cid
.UniqueThread
)
281 /* We couldn't create the CID, dereference the thread and fail */
282 ObDereferenceObject(Thread
);
283 return STATUS_INSUFFICIENT_RESOURCES
;
286 /* Save the read cluster size */
287 Thread
->ReadClusterSize
= MmReadClusterSize
;
289 /* Initialize the LPC Reply Semaphore */
290 KeInitializeSemaphore(&Thread
->LpcReplySemaphore
, 0, 1);
292 /* Initialize the list heads and locks */
293 InitializeListHead(&Thread
->LpcReplyChain
);
294 InitializeListHead(&Thread
->IrpList
);
295 InitializeListHead(&Thread
->PostBlockList
);
296 InitializeListHead(&Thread
->ActiveTimerListHead
);
297 KeInitializeSpinLock(&Thread
->ActiveTimerListLock
);
299 /* Acquire rundown protection */
300 if (!ExAcquireRundownProtection (&Process
->RundownProtect
))
303 ObDereferenceObject(Thread
);
304 return STATUS_PROCESS_IS_TERMINATING
;
307 /* Now let the kernel initialize the context */
310 /* User-mode Thread, create Teb */
311 Status
= MmCreateTeb(Process
, &Thread
->Cid
, InitialTeb
, &TebBase
);
312 if (!NT_SUCCESS(Status
))
314 /* Failed to create the TEB. Release rundown and dereference */
315 ExReleaseRundownProtection(&Process
->RundownProtect
);
316 ObDereferenceObject(Thread
);
320 /* Set the Start Addresses */
321 Thread
->StartAddress
= (PVOID
)KeGetContextPc(ThreadContext
);
322 Thread
->Win32StartAddress
= (PVOID
)KeGetContextReturnRegister(ThreadContext
);
324 /* Let the kernel intialize the Thread */
325 Status
= KeInitThread(&Thread
->Tcb
,
327 PspUserThreadStartup
,
329 Thread
->StartAddress
,
337 Thread
->StartAddress
= StartRoutine
;
338 PspSetCrossThreadFlag(Thread
, CT_SYSTEM_THREAD_BIT
);
340 /* Let the kernel intialize the Thread */
341 Status
= KeInitThread(&Thread
->Tcb
,
343 PspSystemThreadStartup
,
351 /* Check if we failed */
352 if (!NT_SUCCESS(Status
))
354 /* Delete the TEB if we had done */
355 if (TebBase
) MmDeleteTeb(Process
, TebBase
);
357 /* Release rundown and dereference */
358 ExReleaseRundownProtection(&Process
->RundownProtect
);
359 ObDereferenceObject(Thread
);
363 /* Lock the process */
364 KeEnterCriticalRegion();
365 ExAcquirePushLockExclusive(&Process
->ProcessLock
);
367 /* Make sure the proces didn't just die on us */
368 if (Process
->ProcessDelete
) goto Quickie
;
370 /* Check if the thread was ours, terminated and it was user mode */
371 if ((Thread
->Terminated
) &&
373 (Thread
->ThreadsProcess
== Process
))
375 /* Cleanup, we don't want to start it up and context switch */
380 * Insert the Thread into the Process's Thread List
381 * Note, this is the ETHREAD Thread List. It is removed in
382 * ps/kill.c!PspExitThread.
384 InsertTailList(&Process
->ThreadListHead
, &Thread
->ThreadListEntry
);
385 Process
->ActiveThreads
++;
387 /* Start the thread */
388 KeStartThread(&Thread
->Tcb
);
390 /* Release the process lock */
391 ExReleasePushLockExclusive(&Process
->ProcessLock
);
392 KeLeaveCriticalRegion();
394 /* Release rundown */
395 ExReleaseRundownProtection(&Process
->RundownProtect
);
398 //WmiTraceProcess(Process, TRUE);
399 //WmiTraceThread(Thread, InitialTeb, TRUE);
401 /* Notify Thread Creation */
402 PspRunCreateThreadNotifyRoutines(Thread
, TRUE
);
404 /* Reference ourselves as a keep-alive */
405 ObReferenceObjectEx(Thread
, 2);
407 /* Suspend the Thread if we have to */
408 if (CreateSuspended
) KeSuspendThread(&Thread
->Tcb
);
410 /* Check if we were already terminated */
411 if (Thread
->Terminated
) KeForceResumeThread(&Thread
->Tcb
);
413 /* Create an access state */
414 Status
= SeCreateAccessStateEx(NULL
,
416 PsGetCurrentProcess() : Process
,
420 &PsThreadType
->TypeInfo
.GenericMapping
);
421 if (!NT_SUCCESS(Status
))
423 /* Access state failed, thread is dead */
424 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
426 /* If we were suspended, wake it up */
427 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
429 /* Dispatch thread */
430 KeReadyThread(&Thread
->Tcb
);
432 /* Dereference completely to kill it */
433 ObDereferenceObjectEx(Thread
, 2);
437 /* Insert the Thread into the Object Manager */
438 Status
= ObInsertObject(Thread
,
445 /* Delete the access state if we had one */
446 if (AccessState
) SeDeleteAccessState(AccessState
);
448 /* Check for success */
449 if (NT_SUCCESS(Status
))
451 /* Wrap in SEH to protect against bad user-mode pointers */
454 /* Return Cid and Handle */
455 if (ClientId
) *ClientId
= Thread
->Cid
;
456 *ThreadHandle
= hThread
;
458 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
460 /* Thread insertion failed, thread is dead */
461 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
463 /* If we were suspended, wake it up */
464 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
466 /* Dispatch thread */
467 KeReadyThread(&Thread
->Tcb
);
469 /* Dereference it, leaving only the keep-alive */
470 ObDereferenceObject(Thread
);
472 /* Close its handle, killing it */
473 ObCloseHandle(ThreadHandle
, PreviousMode
);
475 /* Return the exception code */
476 _SEH2_YIELD(return _SEH2_GetExceptionCode());
482 /* Thread insertion failed, thread is dead */
483 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
485 /* If we were suspended, wake it up */
486 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
489 /* Get the create time */
490 KeQuerySystemTime(&Thread
->CreateTime
);
491 ASSERT(!(Thread
->CreateTime
.HighPart
& 0xF0000000));
493 /* Make sure the thread isn't dead */
494 if (!Thread
->DeadThread
)
496 /* Get the thread's SD */
497 Status
= ObGetObjectSecurity(Thread
,
500 if (!NT_SUCCESS(Status
))
502 /* Thread insertion failed, thread is dead */
503 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
505 /* If we were suspended, wake it up */
506 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
508 /* Dispatch thread */
509 KeReadyThread(&Thread
->Tcb
);
511 /* Dereference it, leaving only the keep-alive */
512 ObDereferenceObject(Thread
);
514 /* Close its handle, killing it */
515 ObCloseHandle(ThreadHandle
, PreviousMode
);
519 /* Create the subject context */
520 SubjectContext
.ProcessAuditId
= Process
;
521 SubjectContext
.PrimaryToken
= PsReferencePrimaryToken(Process
);
522 SubjectContext
.ClientToken
= NULL
;
524 /* Do the access check */
525 Result
= SeAccessCheck(SecurityDescriptor
,
531 &PsThreadType
->TypeInfo
.GenericMapping
,
533 &Thread
->GrantedAccess
,
536 /* Dereference the token and let go the SD */
537 ObFastDereferenceObject(&Process
->Token
,
538 SubjectContext
.PrimaryToken
);
539 ObReleaseObjectSecurity(SecurityDescriptor
, SdAllocated
);
541 /* Remove access if it failed */
542 if (!Result
) Process
->GrantedAccess
= 0;
544 /* Set least some minimum access */
545 Thread
->GrantedAccess
|= (THREAD_TERMINATE
|
546 THREAD_SET_INFORMATION
|
547 THREAD_QUERY_INFORMATION
);
551 /* Set the thread access mask to maximum */
552 Thread
->GrantedAccess
= THREAD_ALL_ACCESS
;
555 /* Dispatch thread */
556 KeReadyThread(&Thread
->Tcb
);
558 /* Dereference it, leaving only the keep-alive */
559 ObDereferenceObject(Thread
);
564 /* Most annoying failure case ever, where we undo almost all manually */
566 /* When we get here, the process is locked, unlock it */
567 ExReleasePushLockExclusive(&Process
->ProcessLock
);
568 KeLeaveCriticalRegion();
570 /* Uninitailize it */
571 KeUninitThread(&Thread
->Tcb
);
573 /* If we had a TEB, delete it */
574 if (TebBase
) MmDeleteTeb(Process
, TebBase
);
576 /* Release rundown protection, which we also hold */
577 ExReleaseRundownProtection(&Process
->RundownProtect
);
579 /* Dereference the thread and return failure */
580 ObDereferenceObject(Thread
);
581 return STATUS_PROCESS_IS_TERMINATING
;
584 /* PUBLIC FUNCTIONS **********************************************************/
591 PsCreateSystemThread(OUT PHANDLE ThreadHandle
,
592 IN ACCESS_MASK DesiredAccess
,
593 IN POBJECT_ATTRIBUTES ObjectAttributes
,
594 IN HANDLE ProcessHandle
,
595 IN PCLIENT_ID ClientId
,
596 IN PKSTART_ROUTINE StartRoutine
,
597 IN PVOID StartContext
)
599 PEPROCESS TargetProcess
= NULL
;
600 HANDLE Handle
= ProcessHandle
;
602 PSTRACE(PS_THREAD_DEBUG
,
603 "ProcessHandle: %p StartRoutine: %p StartContext: %p\n",
604 ProcessHandle
, StartRoutine
, StartContext
);
606 /* Check if we have a handle. If not, use the System Process */
610 TargetProcess
= PsInitialSystemProcess
;
613 /* Call the shared function */
614 return PspCreateThread(ThreadHandle
,
632 PsLookupThreadByThreadId(IN HANDLE ThreadId
,
633 OUT PETHREAD
*Thread
)
635 PHANDLE_TABLE_ENTRY CidEntry
;
636 PETHREAD FoundThread
;
637 NTSTATUS Status
= STATUS_INVALID_PARAMETER
;
639 PSTRACE(PS_THREAD_DEBUG
, "ThreadId: %p\n", ThreadId
);
640 KeEnterCriticalRegion();
642 /* Get the CID Handle Entry */
643 CidEntry
= ExMapHandleToPointer(PspCidTable
, ThreadId
);
646 /* Get the Process */
647 FoundThread
= CidEntry
->Object
;
649 /* Make sure it's really a process */
650 if (FoundThread
->Tcb
.Header
.Type
== ThreadObject
)
652 /* Safe Reference and return it */
653 if (ObReferenceObjectSafe(FoundThread
))
655 *Thread
= FoundThread
;
656 Status
= STATUS_SUCCESS
;
660 /* Unlock the Entry */
661 ExUnlockHandleTableEntry(PspCidTable
, CidEntry
);
664 /* Return to caller */
665 KeLeaveCriticalRegion();
674 PsGetCurrentThreadId(VOID
)
676 return PsGetCurrentThread()->Cid
.UniqueThread
;
684 PsGetThreadFreezeCount(IN PETHREAD Thread
)
686 return Thread
->Tcb
.FreezeCount
;
694 PsGetThreadHardErrorsAreDisabled(IN PETHREAD Thread
)
696 return Thread
->HardErrorsAreDisabled
? TRUE
: FALSE
;
704 PsGetThreadId(IN PETHREAD Thread
)
706 return Thread
->Cid
.UniqueThread
;
714 PsGetThreadProcess(IN PETHREAD Thread
)
716 return Thread
->ThreadsProcess
;
724 PsGetThreadProcessId(IN PETHREAD Thread
)
726 return Thread
->Cid
.UniqueProcess
;
734 PsGetThreadSessionId(IN PETHREAD Thread
)
736 return (HANDLE
)Thread
->ThreadsProcess
->Session
;
744 PsGetThreadTeb(IN PETHREAD Thread
)
746 return Thread
->Tcb
.Teb
;
754 PsGetThreadWin32Thread(IN PETHREAD Thread
)
756 return Thread
->Tcb
.Win32Thread
;
764 PsGetCurrentThreadPreviousMode(VOID
)
766 return (KPROCESSOR_MODE
)PsGetCurrentThread()->Tcb
.PreviousMode
;
774 PsGetCurrentThreadStackBase(VOID
)
776 return PsGetCurrentThread()->Tcb
.StackBase
;
784 PsGetCurrentThreadStackLimit(VOID
)
786 return (PVOID
)PsGetCurrentThread()->Tcb
.StackLimit
;
794 PsIsThreadTerminating(IN PETHREAD Thread
)
796 return Thread
->Terminated
? TRUE
: FALSE
;
804 PsIsSystemThread(IN PETHREAD Thread
)
806 return Thread
->SystemThread
? TRUE
: FALSE
;
814 PsIsThreadImpersonating(IN PETHREAD Thread
)
816 return Thread
->ActiveImpersonationInfo
? TRUE
: FALSE
;
824 PsSetThreadHardErrorsAreDisabled(IN PETHREAD Thread
,
825 IN BOOLEAN HardErrorsAreDisabled
)
827 Thread
->HardErrorsAreDisabled
= HardErrorsAreDisabled
;
835 PsGetCurrentThreadWin32Thread(VOID
)
837 return PsGetCurrentThread()->Tcb
.Win32Thread
;
845 PsSetThreadWin32Thread(IN PETHREAD Thread
,
846 IN PVOID Win32Thread
)
848 Thread
->Tcb
.Win32Thread
= Win32Thread
;
853 NtCreateThread(OUT PHANDLE ThreadHandle
,
854 IN ACCESS_MASK DesiredAccess
,
855 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL
,
856 IN HANDLE ProcessHandle
,
857 OUT PCLIENT_ID ClientId
,
858 IN PCONTEXT ThreadContext
,
859 IN PINITIAL_TEB InitialTeb
,
860 IN BOOLEAN CreateSuspended
)
862 INITIAL_TEB SafeInitialTeb
;
864 PSTRACE(PS_THREAD_DEBUG
,
865 "ProcessHandle: %p Context: %p\n", ProcessHandle
, ThreadContext
);
867 /* Check if this was from user-mode */
868 if (KeGetPreviousMode() != KernelMode
)
870 /* Make sure that we got a context */
871 if (!ThreadContext
) return STATUS_INVALID_PARAMETER
;
876 /* Make sure the handle pointer we got is valid */
877 ProbeForWriteHandle(ThreadHandle
);
879 /* Check if the caller wants a client id */
882 /* Make sure we can write to it */
883 ProbeForWrite(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
886 /* Make sure that the entire context is readable */
887 ProbeForRead(ThreadContext
, sizeof(CONTEXT
), sizeof(ULONG
));
889 /* Check the Initial TEB */
890 ProbeForRead(InitialTeb
, sizeof(INITIAL_TEB
), sizeof(ULONG
));
891 SafeInitialTeb
= *InitialTeb
;
893 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
895 /* Return the exception code */
896 _SEH2_YIELD(return _SEH2_GetExceptionCode());
902 /* Use the Initial TEB as is */
903 SafeInitialTeb
= *InitialTeb
;
906 /* Call the shared function */
907 return PspCreateThread(ThreadHandle
,
925 NtOpenThread(OUT PHANDLE ThreadHandle
,
926 IN ACCESS_MASK DesiredAccess
,
927 IN POBJECT_ATTRIBUTES ObjectAttributes
,
928 IN PCLIENT_ID ClientId OPTIONAL
)
930 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
931 CLIENT_ID SafeClientId
;
932 ULONG Attributes
= 0;
933 HANDLE hThread
= NULL
;
936 BOOLEAN HasObjectName
= FALSE
;
937 ACCESS_STATE AccessState
;
938 AUX_ACCESS_DATA AuxData
;
940 PSTRACE(PS_THREAD_DEBUG
,
941 "ClientId: %p ObjectAttributes: %p\n", ClientId
, ObjectAttributes
);
943 /* Check if we were called from user mode */
944 if (PreviousMode
!= KernelMode
)
946 /* Enter SEH for probing */
949 /* Probe the thread handle */
950 ProbeForWriteHandle(ThreadHandle
);
952 /* Check for a CID structure */
955 /* Probe and capture it */
956 ProbeForRead(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
957 SafeClientId
= *ClientId
;
958 ClientId
= &SafeClientId
;
962 * Just probe the object attributes structure, don't capture it
963 * completely. This is done later if necessary
965 ProbeForRead(ObjectAttributes
,
966 sizeof(OBJECT_ATTRIBUTES
),
968 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
969 Attributes
= ObjectAttributes
->Attributes
;
971 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
973 /* Return the exception code */
974 _SEH2_YIELD(return _SEH2_GetExceptionCode());
980 /* Otherwise just get the data directly */
981 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
982 Attributes
= ObjectAttributes
->Attributes
;
985 /* Can't pass both, fail */
986 if ((HasObjectName
) && (ClientId
)) return STATUS_INVALID_PARAMETER_MIX
;
988 /* Create an access state */
989 Status
= SeCreateAccessState(&AccessState
,
992 &PsProcessType
->TypeInfo
.GenericMapping
);
993 if (!NT_SUCCESS(Status
)) return Status
;
995 /* Check if this is a debugger */
996 if (SeSinglePrivilegeCheck(SeDebugPrivilege
, PreviousMode
))
998 /* Did he want full access? */
999 if (AccessState
.RemainingDesiredAccess
& MAXIMUM_ALLOWED
)
1001 /* Give it to him */
1002 AccessState
.PreviouslyGrantedAccess
|= THREAD_ALL_ACCESS
;
1006 /* Otherwise just give every other access he could want */
1007 AccessState
.PreviouslyGrantedAccess
|=
1008 AccessState
.RemainingDesiredAccess
;
1011 /* The caller desires nothing else now */
1012 AccessState
.RemainingDesiredAccess
= 0;
1015 /* Open by name if one was given */
1019 Status
= ObOpenObjectByName(ObjectAttributes
,
1027 /* Get rid of the access state */
1028 SeDeleteAccessState(&AccessState
);
1032 /* Open by Thread ID */
1033 if (ClientId
->UniqueProcess
)
1035 /* Get the Process */
1036 Status
= PsLookupProcessThreadByCid(ClientId
, NULL
, &Thread
);
1040 /* Get the Process */
1041 Status
= PsLookupThreadByThreadId(ClientId
->UniqueThread
, &Thread
);
1044 /* Check if we didn't find anything */
1045 if (!NT_SUCCESS(Status
))
1047 /* Get rid of the access state and return */
1048 SeDeleteAccessState(&AccessState
);
1052 /* Open the Thread Object */
1053 Status
= ObOpenObjectByPointer(Thread
,
1061 /* Delete the access state and dereference the thread */
1062 SeDeleteAccessState(&AccessState
);
1063 ObDereferenceObject(Thread
);
1067 /* Neither an object name nor a client id was passed */
1068 return STATUS_INVALID_PARAMETER_MIX
;
1071 /* Check for success */
1072 if (NT_SUCCESS(Status
))
1074 /* Protect against bad user-mode pointers */
1077 /* Write back the handle */
1078 *ThreadHandle
= hThread
;
1080 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1082 /* Get the exception code */
1083 Status
= _SEH2_GetExceptionCode();