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 ****************************************************************/
14 #include <internal/debug.h>
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(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(NULL
,
76 (PVOID
)((ULONG_PTR
)Thread
->Tcb
.InitialStack
-
79 PspSystemDllEntryPoint
,
84 /* Lower it back to passive */
85 KeLowerIrql(PASSIVE_LEVEL
);
89 /* We're dead, kill us now */
90 PspTerminateThreadByPointer(Thread
,
91 STATUS_THREAD_IS_TERMINATING
,
95 /* Do we have a cookie set yet? */
96 if (!SharedUserData
->Cookie
)
98 LARGE_INTEGER SystemTime
;
102 /* Generate a new cookie */
103 KeQuerySystemTime(&SystemTime
);
104 Prcb
= KeGetCurrentPrcb();
105 NewCookie
= Prcb
->MmPageFaultCount
^ Prcb
->InterruptTime
^
106 SystemTime
.u
.LowPart
^ SystemTime
.u
.HighPart
^
109 /* Set the new cookie*/
110 InterlockedCompareExchange((LONG
*)&SharedUserData
->Cookie
,
116 _SEH_FILTER(PspUnhandledExceptionInSystemThread
)
118 PEXCEPTION_POINTERS ExceptionPointers
= _SEH_GetExceptionPointers();
120 /* Print debugging information */
121 DPRINT1("PS: Unhandled Kernel Mode Exception Pointers = 0x%p\n",
123 DPRINT1("Code %x Addr %p Info0 %p Info1 %p Info2 %p Info3 %p\n",
124 ExceptionPointers
->ExceptionRecord
->ExceptionCode
,
125 ExceptionPointers
->ExceptionRecord
->ExceptionAddress
,
126 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[0],
127 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[1],
128 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[2],
129 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[3]);
131 /* Bugcheck the system */
133 ExceptionPointers
->ExceptionRecord
->ExceptionCode
,
134 (ULONG_PTR
)ExceptionPointers
->ExceptionRecord
->ExceptionAddress
,
135 (ULONG_PTR
)ExceptionPointers
->ExceptionRecord
,
136 (ULONG_PTR
)ExceptionPointers
->ContextRecord
);
142 PspSystemThreadStartup(IN PKSTART_ROUTINE StartRoutine
,
143 IN PVOID StartContext
)
146 PSTRACE(PS_THREAD_DEBUG
,
147 "StartRoutine: %p StartContext: %p\n", StartRoutine
, StartContext
);
149 /* Unlock the dispatcher Database */
150 KeLowerIrql(PASSIVE_LEVEL
);
151 Thread
= PsGetCurrentThread();
153 /* Make sure the thread isn't gone */
156 if (!(Thread
->Terminated
) && !(Thread
->DeadThread
))
158 /* Call it the Start Routine */
159 StartRoutine(StartContext
);
162 _SEH_EXCEPT(PspUnhandledExceptionInSystemThread
)
164 /* Bugcheck if we got here */
165 KeBugCheck(KMODE_EXCEPTION_NOT_HANDLED
);
169 /* Exit the thread */
170 PspTerminateThreadByPointer(Thread
, STATUS_SUCCESS
, TRUE
);
175 PspCreateThread(OUT PHANDLE ThreadHandle
,
176 IN ACCESS_MASK DesiredAccess
,
177 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL
,
178 IN HANDLE ProcessHandle
,
179 IN PEPROCESS TargetProcess
,
180 OUT PCLIENT_ID ClientId
,
181 IN PCONTEXT ThreadContext
,
182 IN PINITIAL_TEB InitialTeb
,
183 IN BOOLEAN CreateSuspended
,
184 IN PKSTART_ROUTINE StartRoutine OPTIONAL
,
185 IN PVOID StartContext OPTIONAL
)
191 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
192 NTSTATUS Status
, AccessStatus
;
193 HANDLE_TABLE_ENTRY CidEntry
;
194 ACCESS_STATE LocalAccessState
;
195 PACCESS_STATE AccessState
= &LocalAccessState
;
197 BOOLEAN Result
, SdAllocated
;
198 PSECURITY_DESCRIPTOR SecurityDescriptor
;
199 SECURITY_SUBJECT_CONTEXT SubjectContext
;
201 PSTRACE(PS_THREAD_DEBUG
,
202 "ThreadContext: %p TargetProcess: %p ProcessHandle: %p\n",
203 ThreadContext
, TargetProcess
, ProcessHandle
);
205 /* If we were called from PsCreateSystemThread, then we're kernel mode */
206 if (StartRoutine
) PreviousMode
= KernelMode
;
208 /* Reference the Process by handle or pointer, depending on what we got */
211 /* Normal thread or System Thread */
212 Status
= ObReferenceObjectByHandle(ProcessHandle
,
213 PROCESS_CREATE_THREAD
,
222 /* System thread inside System Process, or Normal Thread with a bug */
225 /* Reference the Process by Pointer */
226 ObReferenceObject(TargetProcess
);
227 Process
= TargetProcess
;
228 Status
= STATUS_SUCCESS
;
232 /* Fake ObReference returning this */
233 Status
= STATUS_INVALID_HANDLE
;
237 /* Check for success */
238 if (!NT_SUCCESS(Status
)) return Status
;
240 /* Also make sure that User-Mode isn't trying to create a system thread */
241 if ((PreviousMode
!= KernelMode
) && (Process
== PsInitialSystemProcess
))
244 ObDereferenceObject(Process
);
245 return STATUS_INVALID_HANDLE
;
248 /* Create Thread Object */
249 Status
= ObCreateObject(PreviousMode
,
258 if (!NT_SUCCESS(Status
))
260 /* We failed; dereference the process and exit */
261 ObDereferenceObject(Process
);
265 /* Zero the Object entirely */
266 RtlZeroMemory(Thread
, sizeof(ETHREAD
));
268 /* Initialize rundown protection */
269 ExInitializeRundownProtection(&Thread
->RundownProtect
);
271 /* Initialize exit code */
272 Thread
->ExitStatus
= STATUS_PENDING
;
274 /* Set the Process CID */
275 Thread
->ThreadsProcess
= Process
;
276 Thread
->Cid
.UniqueProcess
= Process
->UniqueProcessId
;
278 /* Create Cid Handle */
279 CidEntry
.Object
= Thread
;
280 CidEntry
.GrantedAccess
= 0;
281 Thread
->Cid
.UniqueThread
= ExCreateHandle(PspCidTable
, &CidEntry
);
282 if (!Thread
->Cid
.UniqueThread
)
284 /* We couldn't create the CID, dereference the thread and fail */
285 ObDereferenceObject(Thread
);
286 return STATUS_INSUFFICIENT_RESOURCES
;
289 /* Save the read cluster size */
290 Thread
->ReadClusterSize
= MmReadClusterSize
;
292 /* Initialize the LPC Reply Semaphore */
293 KeInitializeSemaphore(&Thread
->LpcReplySemaphore
, 0, 1);
295 /* Initialize the list heads and locks */
296 InitializeListHead(&Thread
->LpcReplyChain
);
297 InitializeListHead(&Thread
->IrpList
);
298 InitializeListHead(&Thread
->PostBlockList
);
299 InitializeListHead(&Thread
->ActiveTimerListHead
);
300 KeInitializeSpinLock(&Thread
->ActiveTimerListLock
);
302 /* Acquire rundown protection */
303 if (!ExAcquireRundownProtection (&Process
->RundownProtect
))
306 ObDereferenceObject(Thread
);
307 return STATUS_PROCESS_IS_TERMINATING
;
310 /* Now let the kernel initialize the context */
313 /* User-mode Thread, create Teb */
314 TebBase
= MmCreateTeb(Process
, &Thread
->Cid
, InitialTeb
);
317 /* Failed to create the TEB. Release rundown and dereference */
318 ExReleaseRundownProtection(&Process
->RundownProtect
);
319 ObDereferenceObject(Thread
);
320 return STATUS_INSUFFICIENT_RESOURCES
;
323 /* Set the Start Addresses */
325 Thread
->StartAddress
= (PVOID
)ThreadContext
->Eip
;
326 Thread
->Win32StartAddress
= (PVOID
)ThreadContext
->Eax
;
327 #elif defined(_M_PPC)
328 Thread
->StartAddress
= (PVOID
)ThreadContext
->Dr0
;
329 Thread
->Win32StartAddress
= (PVOID
)ThreadContext
->Gpr3
;
330 #elif defined(_M_MIPS)
333 #error Unknown architecture
336 /* Let the kernel intialize the Thread */
337 Status
= KeInitThread(&Thread
->Tcb
,
339 PspUserThreadStartup
,
341 Thread
->StartAddress
,
349 Thread
->StartAddress
= StartRoutine
;
350 PspSetCrossThreadFlag(Thread
, CT_SYSTEM_THREAD_BIT
);
352 /* Let the kernel intialize the Thread */
353 Status
= KeInitThread(&Thread
->Tcb
,
355 PspSystemThreadStartup
,
363 /* Check if we failed */
364 if (!NT_SUCCESS(Status
))
366 /* Delete the TEB if we had done */
367 if (TebBase
) MmDeleteTeb(Process
, TebBase
);
369 /* Release rundown and dereference */
370 ExReleaseRundownProtection(&Process
->RundownProtect
);
371 ObDereferenceObject(Thread
);
375 /* Lock the process */
376 KeEnterCriticalRegion();
377 ExAcquirePushLockExclusive(&Process
->ProcessLock
);
379 /* Make sure the proces didn't just die on us */
380 if (Process
->ProcessDelete
) goto Quickie
;
382 /* Check if the thread was ours, terminated and it was user mode */
383 if ((Thread
->Terminated
) &&
385 (Thread
->ThreadsProcess
== Process
))
387 /* Cleanup, we don't want to start it up and context switch */
392 * Insert the Thread into the Process's Thread List
393 * Note, this is the ETHREAD Thread List. It is removed in
394 * ps/kill.c!PspExitThread.
396 InsertTailList(&Process
->ThreadListHead
, &Thread
->ThreadListEntry
);
397 Process
->ActiveThreads
++;
399 /* Start the thread */
400 KeStartThread(&Thread
->Tcb
);
402 /* Release the process lock */
403 ExReleasePushLockExclusive(&Process
->ProcessLock
);
404 KeLeaveCriticalRegion();
406 /* Release rundown */
407 ExReleaseRundownProtection(&Process
->RundownProtect
);
410 //WmiTraceProcess(Process, TRUE);
411 //WmiTraceThread(Thread, InitialTeb, TRUE);
413 /* Notify Thread Creation */
414 PspRunCreateThreadNotifyRoutines(Thread
, TRUE
);
416 /* Reference ourselves as a keep-alive */
417 ObReferenceObjectEx(Thread
, 2);
419 /* Suspend the Thread if we have to */
420 if (CreateSuspended
) KeSuspendThread(&Thread
->Tcb
);
422 /* Check if we were already terminated */
423 if (Thread
->Terminated
) KeForceResumeThread(&Thread
->Tcb
);
425 /* Create an access state */
426 Status
= SeCreateAccessStateEx(NULL
,
428 PsGetCurrentProcess() : Process
,
432 &PsThreadType
->TypeInfo
.GenericMapping
);
433 if (!NT_SUCCESS(Status
))
435 /* Access state failed, thread is dead */
436 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
438 /* If we were suspended, wake it up */
439 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
441 /* Dispatch thread */
442 KeReadyThread(&Thread
->Tcb
);
444 /* Dereference completely to kill it */
445 ObDereferenceObjectEx(Thread
, 2);
449 /* Insert the Thread into the Object Manager */
450 Status
= ObInsertObject(Thread
,
457 /* Delete the access state if we had one */
458 if (AccessState
) SeDeleteAccessState(AccessState
);
460 /* Check for success */
461 if (NT_SUCCESS(Status
))
463 /* Wrap in SEH to protect against bad user-mode pointers */
466 /* Return Cid and Handle */
467 if (ClientId
) *ClientId
= Thread
->Cid
;
468 *ThreadHandle
= hThread
;
472 /* Get the exception code */
473 Status
= _SEH_GetExceptionCode();
475 /* Thread insertion failed, thread is dead */
476 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
478 /* If we were suspended, wake it up */
479 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
481 /* Dispatch thread */
482 KeReadyThread(&Thread
->Tcb
);
484 /* Dereference it, leaving only the keep-alive */
485 ObDereferenceObject(Thread
);
487 /* Close its handle, killing it */
488 ObCloseHandle(ThreadHandle
, PreviousMode
);
491 if (!NT_SUCCESS(Status
)) return Status
;
495 /* Thread insertion failed, thread is dead */
496 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
498 /* If we were suspended, wake it up */
499 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
502 /* Get the create time */
503 KeQuerySystemTime(&Thread
->CreateTime
);
504 ASSERT(!(Thread
->CreateTime
.HighPart
& 0xF0000000));
506 /* Make sure the thread isn't dead */
507 if (!Thread
->DeadThread
)
509 /* Get the thread's SD */
510 Status
= ObGetObjectSecurity(Thread
,
513 if (!NT_SUCCESS(Status
))
515 /* Thread insertion failed, thread is dead */
516 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
518 /* If we were suspended, wake it up */
519 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
521 /* Dispatch thread */
522 KeReadyThread(&Thread
->Tcb
);
524 /* Dereference it, leaving only the keep-alive */
525 ObDereferenceObject(Thread
);
527 /* Close its handle, killing it */
528 ObCloseHandle(ThreadHandle
, PreviousMode
);
532 /* Create the subject context */
533 SubjectContext
.ProcessAuditId
= Process
;
534 SubjectContext
.PrimaryToken
= PsReferencePrimaryToken(Process
);
535 SubjectContext
.ClientToken
= NULL
;
537 /* Do the access check */
538 Result
= SeAccessCheck(SecurityDescriptor
,
544 &PsThreadType
->TypeInfo
.GenericMapping
,
546 &Thread
->GrantedAccess
,
549 /* Dereference the token and let go the SD */
550 ObFastDereferenceObject(&Process
->Token
,
551 SubjectContext
.PrimaryToken
);
552 ObReleaseObjectSecurity(SecurityDescriptor
, SdAllocated
);
554 /* Remove access if it failed */
555 if (!Result
) Process
->GrantedAccess
= 0;
557 /* Set least some minimum access */
558 Thread
->GrantedAccess
|= (THREAD_TERMINATE
|
559 THREAD_SET_INFORMATION
|
560 THREAD_QUERY_INFORMATION
);
564 /* Set the thread access mask to maximum */
565 Thread
->GrantedAccess
= THREAD_ALL_ACCESS
;
568 /* Dispatch thread */
569 KeReadyThread(&Thread
->Tcb
);
571 /* Dereference it, leaving only the keep-alive */
572 ObDereferenceObject(Thread
);
577 /* Most annoying failure case ever, where we undo almost all manually */
579 /* When we get here, the process is locked, unlock it */
580 ExReleasePushLockExclusive(&Process
->ProcessLock
);
582 /* Uninitailize it */
583 KeUninitThread(&Thread
->Tcb
);
585 /* If we had a TEB, delete it */
586 if (TebBase
) MmDeleteTeb(Process
, TebBase
);
588 /* Release rundown protection, which we also hold */
589 ExReleaseRundownProtection(&Process
->RundownProtect
);
591 /* Dereference the thread and return failure */
592 ObDereferenceObject(Thread
);
593 return STATUS_PROCESS_IS_TERMINATING
;
596 /* PUBLIC FUNCTIONS **********************************************************/
603 PsCreateSystemThread(OUT PHANDLE ThreadHandle
,
604 IN ACCESS_MASK DesiredAccess
,
605 IN POBJECT_ATTRIBUTES ObjectAttributes
,
606 IN HANDLE ProcessHandle
,
607 IN PCLIENT_ID ClientId
,
608 IN PKSTART_ROUTINE StartRoutine
,
609 IN PVOID StartContext
)
611 PEPROCESS TargetProcess
= NULL
;
612 HANDLE Handle
= ProcessHandle
;
614 PSTRACE(PS_THREAD_DEBUG
,
615 "ProcessHandle: %p StartRoutine: %p StartContext: %p\n",
616 ProcessHandle
, StartRoutine
, StartContext
);
618 /* Check if we have a handle. If not, use the System Process */
622 TargetProcess
= PsInitialSystemProcess
;
625 /* Call the shared function */
626 return PspCreateThread(ThreadHandle
,
644 PsLookupThreadByThreadId(IN HANDLE ThreadId
,
645 OUT PETHREAD
*Thread
)
647 PHANDLE_TABLE_ENTRY CidEntry
;
648 PETHREAD FoundThread
;
649 NTSTATUS Status
= STATUS_INVALID_PARAMETER
;
651 PSTRACE(PS_THREAD_DEBUG
, "ThreadId: %p\n", ThreadId
);
652 KeEnterCriticalRegion();
654 /* Get the CID Handle Entry */
655 CidEntry
= ExMapHandleToPointer(PspCidTable
, ThreadId
);
658 /* Get the Process */
659 FoundThread
= CidEntry
->Object
;
661 /* Make sure it's really a process */
662 if (FoundThread
->Tcb
.DispatcherHeader
.Type
== ThreadObject
)
664 /* Safe Reference and return it */
665 if (ObReferenceObjectSafe(FoundThread
))
667 *Thread
= FoundThread
;
668 Status
= STATUS_SUCCESS
;
672 /* Unlock the Entry */
673 ExUnlockHandleTableEntry(PspCidTable
, CidEntry
);
676 /* Return to caller */
677 KeLeaveCriticalRegion();
686 PsGetCurrentThreadId(VOID
)
688 return PsGetCurrentThread()->Cid
.UniqueThread
;
696 PsGetThreadFreezeCount(IN PETHREAD Thread
)
698 return Thread
->Tcb
.FreezeCount
;
706 PsGetThreadHardErrorsAreDisabled(IN PETHREAD Thread
)
708 return Thread
->HardErrorsAreDisabled
? TRUE
: FALSE
;
716 PsGetThreadId(IN PETHREAD Thread
)
718 return Thread
->Cid
.UniqueThread
;
726 PsGetThreadProcess(IN PETHREAD Thread
)
728 return Thread
->ThreadsProcess
;
736 PsGetThreadProcessId(IN PETHREAD Thread
)
738 return Thread
->Cid
.UniqueProcess
;
746 PsGetThreadSessionId(IN PETHREAD Thread
)
748 return (HANDLE
)Thread
->ThreadsProcess
->Session
;
756 PsGetThreadTeb(IN PETHREAD Thread
)
758 return Thread
->Tcb
.Teb
;
766 PsGetThreadWin32Thread(IN PETHREAD Thread
)
768 return Thread
->Tcb
.Win32Thread
;
776 PsGetCurrentThreadPreviousMode(VOID
)
778 return (KPROCESSOR_MODE
)PsGetCurrentThread()->Tcb
.PreviousMode
;
786 PsGetCurrentThreadStackBase(VOID
)
788 return PsGetCurrentThread()->Tcb
.StackBase
;
796 PsGetCurrentThreadStackLimit(VOID
)
798 return (PVOID
)PsGetCurrentThread()->Tcb
.StackLimit
;
806 PsIsThreadTerminating(IN PETHREAD Thread
)
808 return Thread
->Terminated
? TRUE
: FALSE
;
816 PsIsSystemThread(IN PETHREAD Thread
)
818 return Thread
->SystemThread
? TRUE
: FALSE
;
826 PsIsThreadImpersonating(IN PETHREAD Thread
)
828 return Thread
->ActiveImpersonationInfo
? TRUE
: FALSE
;
836 PsSetThreadHardErrorsAreDisabled(IN PETHREAD Thread
,
837 IN BOOLEAN HardErrorsAreDisabled
)
839 Thread
->HardErrorsAreDisabled
= HardErrorsAreDisabled
;
847 PsGetCurrentThreadWin32Thread(VOID
)
849 return PsGetCurrentThread()->Tcb
.Win32Thread
;
857 PsSetThreadWin32Thread(IN PETHREAD Thread
,
858 IN PVOID Win32Thread
)
860 Thread
->Tcb
.Win32Thread
= Win32Thread
;
865 NtCreateThread(OUT PHANDLE ThreadHandle
,
866 IN ACCESS_MASK DesiredAccess
,
867 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL
,
868 IN HANDLE ProcessHandle
,
869 OUT PCLIENT_ID ClientId
,
870 IN PCONTEXT ThreadContext
,
871 IN PINITIAL_TEB InitialTeb
,
872 IN BOOLEAN CreateSuspended
)
874 INITIAL_TEB SafeInitialTeb
;
875 NTSTATUS Status
= STATUS_SUCCESS
;
877 PSTRACE(PS_THREAD_DEBUG
,
878 "ProcessHandle: %p Context: %p\n", ProcessHandle
, ThreadContext
);
880 /* Check if this was from user-mode */
881 if (KeGetPreviousMode() != KernelMode
)
883 /* Make sure that we got a context */
884 if (!ThreadContext
) return STATUS_INVALID_PARAMETER
;
889 /* Make sure the handle pointer we got is valid */
890 ProbeForWriteHandle(ThreadHandle
);
892 /* Check if the caller wants a client id */
895 /* Make sure we can write to it */
896 ProbeForWrite(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
899 /* Make sure that the entire context is readable */
900 ProbeForRead(ThreadContext
, sizeof(CONTEXT
), sizeof(ULONG
));
902 /* Check the Initial TEB */
903 ProbeForRead(InitialTeb
, sizeof(INITIAL_TEB
), sizeof(ULONG
));
904 SafeInitialTeb
= *InitialTeb
;
908 Status
= _SEH_GetExceptionCode();
911 if (!NT_SUCCESS(Status
)) return Status
;
915 /* Use the Initial TEB as is */
916 SafeInitialTeb
= *InitialTeb
;
919 /* Call the shared function */
920 return PspCreateThread(ThreadHandle
,
938 NtOpenThread(OUT PHANDLE ThreadHandle
,
939 IN ACCESS_MASK DesiredAccess
,
940 IN POBJECT_ATTRIBUTES ObjectAttributes
,
941 IN PCLIENT_ID ClientId OPTIONAL
)
943 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
944 CLIENT_ID SafeClientId
;
945 ULONG Attributes
= 0;
946 HANDLE hThread
= NULL
;
947 NTSTATUS Status
= STATUS_SUCCESS
;
949 BOOLEAN HasObjectName
= FALSE
;
950 ACCESS_STATE AccessState
;
953 PSTRACE(PS_THREAD_DEBUG
,
954 "ClientId: %p ObjectAttributes: %p\n", ClientId
, ObjectAttributes
);
956 /* Check if we were called from user mode */
957 if (PreviousMode
!= KernelMode
)
959 /* Enter SEH for probing */
962 /* Probe the thread handle */
963 ProbeForWriteHandle(ThreadHandle
);
965 /* Check for a CID structure */
968 /* Probe and capture it */
969 ProbeForRead(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
970 SafeClientId
= *ClientId
;
971 ClientId
= &SafeClientId
;
975 * Just probe the object attributes structure, don't capture it
976 * completely. This is done later if necessary
978 ProbeForRead(ObjectAttributes
,
979 sizeof(OBJECT_ATTRIBUTES
),
981 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
982 Attributes
= ObjectAttributes
->Attributes
;
986 /* Get the exception code */
987 Status
= _SEH_GetExceptionCode();
990 if (!NT_SUCCESS(Status
)) return Status
;
994 /* Otherwise just get the data directly */
995 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
996 Attributes
= ObjectAttributes
->Attributes
;
999 /* Can't pass both, fail */
1000 if ((HasObjectName
) && (ClientId
)) return STATUS_INVALID_PARAMETER_MIX
;
1002 /* Create an access state */
1003 Status
= SeCreateAccessState(&AccessState
,
1006 &PsProcessType
->TypeInfo
.GenericMapping
);
1007 if (!NT_SUCCESS(Status
)) return Status
;
1009 /* Check if this is a debugger */
1010 if (SeSinglePrivilegeCheck(SeDebugPrivilege
, PreviousMode
))
1012 /* Did he want full access? */
1013 if (AccessState
.RemainingDesiredAccess
& MAXIMUM_ALLOWED
)
1015 /* Give it to him */
1016 AccessState
.PreviouslyGrantedAccess
|= THREAD_ALL_ACCESS
;
1020 /* Otherwise just give every other access he could want */
1021 AccessState
.PreviouslyGrantedAccess
|=
1022 AccessState
.RemainingDesiredAccess
;
1025 /* The caller desires nothing else now */
1026 AccessState
.RemainingDesiredAccess
= 0;
1029 /* Open by name if one was given */
1033 Status
= ObOpenObjectByName(ObjectAttributes
,
1041 /* Get rid of the access state */
1042 SeDeleteAccessState(&AccessState
);
1046 /* Open by Thread ID */
1047 if (ClientId
->UniqueProcess
)
1049 /* Get the Process */
1050 Status
= PsLookupProcessThreadByCid(ClientId
, NULL
, &Thread
);
1054 /* Get the Process */
1055 Status
= PsLookupThreadByThreadId(ClientId
->UniqueThread
, &Thread
);
1058 /* Check if we didn't find anything */
1059 if (!NT_SUCCESS(Status
))
1061 /* Get rid of the access state and return */
1062 SeDeleteAccessState(&AccessState
);
1066 /* Open the Thread Object */
1067 Status
= ObOpenObjectByPointer(Thread
,
1075 /* Delete the access state and dereference the thread */
1076 SeDeleteAccessState(&AccessState
);
1077 ObDereferenceObject(Thread
);
1081 /* Neither an object name nor a client id was passed */
1082 return STATUS_INVALID_PARAMETER_MIX
;
1085 /* Check for success */
1086 if (NT_SUCCESS(Status
))
1088 /* Protect against bad user-mode pointers */
1091 /* Write back the handle */
1092 *ThreadHandle
= hThread
;
1096 /* Get the exception code */
1097 Status
= _SEH_GetExceptionCode();