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
;
33 PSTRACE(PS_THREAD_DEBUG
,
34 "StartRoutine: %p StartContext: %p\n", StartRoutine
, StartContext
);
36 /* Go to Passive Level */
37 KeLowerIrql(PASSIVE_LEVEL
);
38 Thread
= PsGetCurrentThread();
40 /* Check if the thread is dead */
41 if (Thread
->DeadThread
)
43 /* Remember that we're dead */
48 /* Get the Locale ID and save Preferred Proc */
50 Teb
->CurrentLocale
= MmGetSessionLocaleId();
51 Teb
->IdealProcessor
= Thread
->Tcb
.IdealProcessor
;
54 /* Check if this is a dead thread, or if we're hiding */
55 if (!(Thread
->DeadThread
) && !(Thread
->HideFromDebugger
))
57 /* We're not, so notify the debugger */
58 DbgkCreateThread(StartContext
);
61 /* Make sure we're not already dead */
64 /* Check if the Prefetcher is enabled */
65 if (CcPfEnablePrefetcher
)
67 /* FIXME: Prepare to prefetch this process */
71 KfRaiseIrql(APC_LEVEL
);
73 /* Queue the User APC */
74 KiInitializeUserApc(NULL
,
75 (PVOID
)((ULONG_PTR
)Thread
->Tcb
.InitialStack
-
77 sizeof(FX_SAVE_AREA
)),
78 PspSystemDllEntryPoint
,
83 /* Lower it back to passive */
84 KeLowerIrql(PASSIVE_LEVEL
);
88 /* We're dead, kill us now */
89 PspTerminateThreadByPointer(Thread
,
90 STATUS_THREAD_IS_TERMINATING
,
94 /* Do we have a cookie set yet? */
95 if (!SharedUserData
->Cookie
)
97 LARGE_INTEGER SystemTime
;
101 /* Generate a new cookie */
102 KeQuerySystemTime(&SystemTime
);
103 Prcb
= KeGetCurrentPrcb();
104 NewCookie
= Prcb
->MmPageFaultCount
^ Prcb
->InterruptTime
^
105 SystemTime
.u
.LowPart
^ SystemTime
.u
.HighPart
^
108 /* Set the new cookie*/
109 InterlockedCompareExchange((LONG
*)&SharedUserData
->Cookie
,
115 _SEH_FILTER(PspUnhandledExceptionInSystemThread
)
117 PEXCEPTION_POINTERS ExceptionPointers
= _SEH_GetExceptionPointers();
119 /* Print debugging information */
120 DPRINT1("PS: Unhandled Kernel Mode Exception Pointers = 0x%p\n",
122 DPRINT1("Code %x Addr %p Info0 %p Info1 %p Info2 %p Info3 %p\n",
123 ExceptionPointers
->ExceptionRecord
->ExceptionCode
,
124 ExceptionPointers
->ExceptionRecord
->ExceptionAddress
,
125 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[0],
126 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[1],
127 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[2],
128 ExceptionPointers
->ExceptionRecord
->ExceptionInformation
[3]);
130 /* Bugcheck the system */
132 ExceptionPointers
->ExceptionRecord
->ExceptionCode
,
133 (ULONG_PTR
)ExceptionPointers
->ExceptionRecord
->ExceptionAddress
,
134 (ULONG_PTR
)ExceptionPointers
->ExceptionRecord
,
135 (ULONG_PTR
)ExceptionPointers
->ContextRecord
);
141 PspSystemThreadStartup(IN PKSTART_ROUTINE StartRoutine
,
142 IN PVOID StartContext
)
145 PSTRACE(PS_THREAD_DEBUG
,
146 "StartRoutine: %p StartContext: %p\n", StartRoutine
, StartContext
);
148 /* Unlock the dispatcher Database */
149 KeLowerIrql(PASSIVE_LEVEL
);
150 Thread
= PsGetCurrentThread();
152 /* Make sure the thread isn't gone */
155 if (!(Thread
->Terminated
) && !(Thread
->DeadThread
))
157 /* Call it the Start Routine */
158 StartRoutine(StartContext
);
161 _SEH_EXCEPT(PspUnhandledExceptionInSystemThread
)
163 /* Bugcheck if we got here */
164 KeBugCheck(KMODE_EXCEPTION_NOT_HANDLED
);
168 /* Exit the thread */
169 PspTerminateThreadByPointer(Thread
, STATUS_SUCCESS
, TRUE
);
174 PspCreateThread(OUT PHANDLE ThreadHandle
,
175 IN ACCESS_MASK DesiredAccess
,
176 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL
,
177 IN HANDLE ProcessHandle
,
178 IN PEPROCESS TargetProcess
,
179 OUT PCLIENT_ID ClientId
,
180 IN PCONTEXT ThreadContext
,
181 IN PINITIAL_TEB InitialTeb
,
182 IN BOOLEAN CreateSuspended
,
183 IN PKSTART_ROUTINE StartRoutine OPTIONAL
,
184 IN PVOID StartContext OPTIONAL
)
190 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
191 NTSTATUS Status
, AccessStatus
;
192 HANDLE_TABLE_ENTRY CidEntry
;
193 ACCESS_STATE LocalAccessState
;
194 PACCESS_STATE AccessState
= &LocalAccessState
;
196 BOOLEAN Result
, SdAllocated
;
197 PSECURITY_DESCRIPTOR SecurityDescriptor
;
198 SECURITY_SUBJECT_CONTEXT SubjectContext
;
200 PSTRACE(PS_THREAD_DEBUG
,
201 "ThreadContext: %p TargetProcess: %p ProcessHandle: %p\n",
202 ThreadContext
, TargetProcess
, ProcessHandle
);
204 /* If we were called from PsCreateSystemThread, then we're kernel mode */
205 if (StartRoutine
) PreviousMode
= KernelMode
;
207 /* Reference the Process by handle or pointer, depending on what we got */
210 /* Normal thread or System Thread */
211 Status
= ObReferenceObjectByHandle(ProcessHandle
,
212 PROCESS_CREATE_THREAD
,
221 /* System thread inside System Process, or Normal Thread with a bug */
224 /* Reference the Process by Pointer */
225 ObReferenceObject(TargetProcess
);
226 Process
= TargetProcess
;
227 Status
= STATUS_SUCCESS
;
231 /* Fake ObReference returning this */
232 Status
= STATUS_INVALID_HANDLE
;
236 /* Check for success */
237 if (!NT_SUCCESS(Status
)) return Status
;
239 /* Also make sure that User-Mode isn't trying to create a system thread */
240 if ((PreviousMode
!= KernelMode
) && (Process
== PsInitialSystemProcess
))
243 ObDereferenceObject(Process
);
244 return STATUS_INVALID_HANDLE
;
247 /* Create Thread Object */
248 Status
= ObCreateObject(PreviousMode
,
257 if (!NT_SUCCESS(Status
))
259 /* We failed; dereference the process and exit */
260 ObDereferenceObject(Process
);
264 /* Zero the Object entirely */
265 RtlZeroMemory(Thread
, sizeof(ETHREAD
));
267 /* Initialize rundown protection */
268 ExInitializeRundownProtection(&Thread
->RundownProtect
);
270 /* Initialize exit code */
271 Thread
->ExitStatus
= STATUS_PENDING
;
273 /* Set the Process CID */
274 Thread
->ThreadsProcess
= Process
;
275 Thread
->Cid
.UniqueProcess
= Process
->UniqueProcessId
;
277 /* Create Cid Handle */
278 CidEntry
.Object
= Thread
;
279 CidEntry
.GrantedAccess
= 0;
280 Thread
->Cid
.UniqueThread
= ExCreateHandle(PspCidTable
, &CidEntry
);
281 if (!Thread
->Cid
.UniqueThread
)
283 /* We couldn't create the CID, dereference the thread and fail */
284 ObDereferenceObject(Thread
);
285 return STATUS_INSUFFICIENT_RESOURCES
;
288 /* Save the read cluster size */
289 Thread
->ReadClusterSize
= MmReadClusterSize
;
291 /* Initialize the LPC Reply Semaphore */
292 KeInitializeSemaphore(&Thread
->LpcReplySemaphore
, 0, 1);
294 /* Initialize the list heads and locks */
295 InitializeListHead(&Thread
->LpcReplyChain
);
296 InitializeListHead(&Thread
->IrpList
);
297 InitializeListHead(&Thread
->PostBlockList
);
298 InitializeListHead(&Thread
->ActiveTimerListHead
);
299 KeInitializeSpinLock(&Thread
->ActiveTimerListLock
);
301 /* Acquire rundown protection */
302 if (!ExAcquireRundownProtection (&Process
->RundownProtect
))
305 ObDereferenceObject(Thread
);
306 return STATUS_PROCESS_IS_TERMINATING
;
309 /* Now let the kernel initialize the context */
312 /* User-mode Thread, create Teb */
313 TebBase
= MmCreateTeb(Process
, &Thread
->Cid
, InitialTeb
);
316 /* Failed to create the TEB. Release rundown and dereference */
317 ExReleaseRundownProtection(&Process
->RundownProtect
);
318 ObDereferenceObject(Thread
);
319 return STATUS_INSUFFICIENT_RESOURCES
;
322 /* Set the Start Addresses */
323 Thread
->StartAddress
= (PVOID
)ThreadContext
->Eip
;
324 Thread
->Win32StartAddress
= (PVOID
)ThreadContext
->Eax
;
326 /* Let the kernel intialize the Thread */
327 Status
= KeInitThread(&Thread
->Tcb
,
329 PspUserThreadStartup
,
331 Thread
->StartAddress
,
339 Thread
->StartAddress
= StartRoutine
;
340 PspSetCrossThreadFlag(Thread
, CT_SYSTEM_THREAD_BIT
);
342 /* Let the kernel intialize the Thread */
343 Status
= KeInitThread(&Thread
->Tcb
,
345 PspSystemThreadStartup
,
353 /* Check if we failed */
354 if (!NT_SUCCESS(Status
))
356 /* Delete the TEB if we had done */
357 if (TebBase
) MmDeleteTeb(Process
, TebBase
);
359 /* Release rundown and dereference */
360 ExReleaseRundownProtection(&Process
->RundownProtect
);
361 ObDereferenceObject(Thread
);
365 /* Lock the process */
366 KeEnterCriticalRegion();
367 ExAcquirePushLockExclusive(&Process
->ProcessLock
);
369 /* Make sure the proces didn't just die on us */
370 if (Process
->ProcessDelete
) goto Quickie
;
372 /* Check if the thread was ours, terminated and it was user mode */
373 if ((Thread
->Terminated
) &&
375 (Thread
->ThreadsProcess
== Process
))
377 /* Cleanup, we don't want to start it up and context switch */
382 * Insert the Thread into the Process's Thread List
383 * Note, this is the ETHREAD Thread List. It is removed in
384 * ps/kill.c!PspExitThread.
386 InsertTailList(&Process
->ThreadListHead
, &Thread
->ThreadListEntry
);
387 Process
->ActiveThreads
++;
389 /* Start the thread */
390 KeStartThread(&Thread
->Tcb
);
392 /* Release the process lock */
393 ExReleasePushLockExclusive(&Process
->ProcessLock
);
394 KeLeaveCriticalRegion();
396 /* Release rundown */
397 ExReleaseRundownProtection(&Process
->RundownProtect
);
400 //WmiTraceProcess(Process, TRUE);
401 //WmiTraceThread(Thread, InitialTeb, TRUE);
403 /* Notify Thread Creation */
404 PspRunCreateThreadNotifyRoutines(Thread
, TRUE
);
406 /* Reference ourselves as a keep-alive */
407 ObReferenceObjectEx(Thread
, 2);
409 /* Suspend the Thread if we have to */
410 if (CreateSuspended
) KeSuspendThread(&Thread
->Tcb
);
412 /* Check if we were already terminated */
413 if (Thread
->Terminated
) KeForceResumeThread(&Thread
->Tcb
);
415 /* Create an access state */
416 Status
= SeCreateAccessStateEx(NULL
,
418 PsGetCurrentProcess() : Process
,
422 &PsThreadType
->TypeInfo
.GenericMapping
);
423 if (!NT_SUCCESS(Status
))
425 /* Access state failed, thread is dead */
426 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
428 /* If we were suspended, wake it up */
429 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
431 /* Dispatch thread */
432 KeReadyThread(&Thread
->Tcb
);
434 /* Dereference completely to kill it */
435 ObDereferenceObjectEx(Thread
, 2);
439 /* Insert the Thread into the Object Manager */
440 Status
= ObInsertObject(Thread
,
447 /* Delete the access state if we had one */
448 if (AccessState
) SeDeleteAccessState(AccessState
);
450 /* Check for success */
451 if (NT_SUCCESS(Status
))
453 /* Wrap in SEH to protect against bad user-mode pointers */
456 /* Return Cid and Handle */
457 if (ClientId
) *ClientId
= Thread
->Cid
;
458 *ThreadHandle
= hThread
;
462 /* Get the exception code */
463 Status
= _SEH_GetExceptionCode();
465 /* Thread insertion failed, thread is dead */
466 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
468 /* If we were suspended, wake it up */
469 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
471 /* Dispatch thread */
472 KeReadyThread(&Thread
->Tcb
);
474 /* Dereference it, leaving only the keep-alive */
475 ObDereferenceObject(Thread
);
477 /* Close its handle, killing it */
478 ObCloseHandle(ThreadHandle
, PreviousMode
);
481 if (!NT_SUCCESS(Status
)) return Status
;
485 /* Thread insertion failed, thread is dead */
486 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
488 /* If we were suspended, wake it up */
489 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
492 /* Get the create time */
493 KeQuerySystemTime(&Thread
->CreateTime
);
494 ASSERT(!(Thread
->CreateTime
.HighPart
& 0xF0000000));
496 /* Make sure the thread isn't dead */
497 if (!Thread
->DeadThread
)
499 /* Get the thread's SD */
500 Status
= ObGetObjectSecurity(Thread
,
503 if (!NT_SUCCESS(Status
))
505 /* Thread insertion failed, thread is dead */
506 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
508 /* If we were suspended, wake it up */
509 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
511 /* Dispatch thread */
512 KeReadyThread(&Thread
->Tcb
);
514 /* Dereference it, leaving only the keep-alive */
515 ObDereferenceObject(Thread
);
517 /* Close its handle, killing it */
518 ObCloseHandle(ThreadHandle
, PreviousMode
);
522 /* Create the subject context */
523 SubjectContext
.ProcessAuditId
= Process
;
524 SubjectContext
.PrimaryToken
= PsReferencePrimaryToken(Process
);
525 SubjectContext
.ClientToken
= NULL
;
527 /* Do the access check */
528 Result
= SeAccessCheck(SecurityDescriptor
,
534 &PsThreadType
->TypeInfo
.GenericMapping
,
536 &Thread
->GrantedAccess
,
539 /* Dereference the token and let go the SD */
540 ObFastDereferenceObject(&Process
->Token
,
541 SubjectContext
.PrimaryToken
);
542 ObReleaseObjectSecurity(SecurityDescriptor
, SdAllocated
);
544 /* Remove access if it failed */
545 if (!Result
) Process
->GrantedAccess
= 0;
547 /* Set least some minimum access */
548 Thread
->GrantedAccess
|= (THREAD_TERMINATE
|
549 THREAD_SET_INFORMATION
|
550 THREAD_QUERY_INFORMATION
);
554 /* Set the thread access mask to maximum */
555 Thread
->GrantedAccess
= THREAD_ALL_ACCESS
;
558 /* Dispatch thread */
559 KeReadyThread(&Thread
->Tcb
);
561 /* Dereference it, leaving only the keep-alive */
562 ObDereferenceObject(Thread
);
567 /* Most annoying failure case ever, where we undo almost all manually */
569 /* When we get here, the process is locked, unlock it */
570 ExReleasePushLockExclusive(&Process
->ProcessLock
);
572 /* Uninitailize it */
573 KeUninitThread(&Thread
->Tcb
);
575 /* If we had a TEB, delete it */
576 if (TebBase
) MmDeleteTeb(Process
, TebBase
);
578 /* Release rundown protection, which we also hold */
579 ExReleaseRundownProtection(&Process
->RundownProtect
);
581 /* Dereference the thread and return failure */
582 ObDereferenceObject(Thread
);
583 return STATUS_PROCESS_IS_TERMINATING
;
586 /* PUBLIC FUNCTIONS **********************************************************/
593 PsCreateSystemThread(OUT PHANDLE ThreadHandle
,
594 IN ACCESS_MASK DesiredAccess
,
595 IN POBJECT_ATTRIBUTES ObjectAttributes
,
596 IN HANDLE ProcessHandle
,
597 IN PCLIENT_ID ClientId
,
598 IN PKSTART_ROUTINE StartRoutine
,
599 IN PVOID StartContext
)
601 PEPROCESS TargetProcess
= NULL
;
602 HANDLE Handle
= ProcessHandle
;
604 PSTRACE(PS_THREAD_DEBUG
,
605 "ProcessHandle: %p StartRoutine: %p StartContext: %p\n",
606 ProcessHandle
, StartRoutine
, StartContext
);
608 /* Check if we have a handle. If not, use the System Process */
612 TargetProcess
= PsInitialSystemProcess
;
615 /* Call the shared function */
616 return PspCreateThread(ThreadHandle
,
634 PsLookupThreadByThreadId(IN HANDLE ThreadId
,
635 OUT PETHREAD
*Thread
)
637 PHANDLE_TABLE_ENTRY CidEntry
;
638 PETHREAD FoundThread
;
639 NTSTATUS Status
= STATUS_INVALID_PARAMETER
;
641 PSTRACE(PS_THREAD_DEBUG
, "ThreadId: %p\n", ThreadId
);
642 KeEnterCriticalRegion();
644 /* Get the CID Handle Entry */
645 CidEntry
= ExMapHandleToPointer(PspCidTable
, ThreadId
);
648 /* Get the Process */
649 FoundThread
= CidEntry
->Object
;
651 /* Make sure it's really a process */
652 if (FoundThread
->Tcb
.DispatcherHeader
.Type
== ThreadObject
)
654 /* Safe Reference and return it */
655 if (ObReferenceObjectSafe(FoundThread
))
657 *Thread
= FoundThread
;
658 Status
= STATUS_SUCCESS
;
662 /* Unlock the Entry */
663 ExUnlockHandleTableEntry(PspCidTable
, CidEntry
);
666 /* Return to caller */
667 KeLeaveCriticalRegion();
676 PsGetCurrentThreadId(VOID
)
678 return PsGetCurrentThread()->Cid
.UniqueThread
;
686 PsGetThreadFreezeCount(IN PETHREAD Thread
)
688 return Thread
->Tcb
.FreezeCount
;
696 PsGetThreadHardErrorsAreDisabled(IN PETHREAD Thread
)
698 return Thread
->HardErrorsAreDisabled
;
706 PsGetThreadId(IN PETHREAD Thread
)
708 return Thread
->Cid
.UniqueThread
;
716 PsGetThreadProcess(IN PETHREAD Thread
)
718 return Thread
->ThreadsProcess
;
726 PsGetThreadProcessId(IN PETHREAD Thread
)
728 return Thread
->Cid
.UniqueProcess
;
736 PsGetThreadSessionId(IN PETHREAD Thread
)
738 return (HANDLE
)Thread
->ThreadsProcess
->Session
;
746 PsGetThreadTeb(IN PETHREAD Thread
)
748 return Thread
->Tcb
.Teb
;
756 PsGetThreadWin32Thread(IN PETHREAD Thread
)
758 return Thread
->Tcb
.Win32Thread
;
766 PsGetCurrentThreadPreviousMode(VOID
)
768 return (KPROCESSOR_MODE
)PsGetCurrentThread()->Tcb
.PreviousMode
;
776 PsGetCurrentThreadStackBase(VOID
)
778 return PsGetCurrentThread()->Tcb
.StackBase
;
786 PsGetCurrentThreadStackLimit(VOID
)
788 return (PVOID
)PsGetCurrentThread()->Tcb
.StackLimit
;
796 PsIsThreadTerminating(IN PETHREAD Thread
)
798 return Thread
->Terminated
? TRUE
: FALSE
;
806 PsIsSystemThread(IN PETHREAD Thread
)
808 return Thread
->SystemThread
? TRUE
: FALSE
;
816 PsIsThreadImpersonating(IN PETHREAD Thread
)
818 return Thread
->ActiveImpersonationInfo
;
826 PsSetThreadHardErrorsAreDisabled(IN PETHREAD Thread
,
827 IN BOOLEAN HardErrorsAreDisabled
)
829 Thread
->HardErrorsAreDisabled
= HardErrorsAreDisabled
;
837 PsGetCurrentThreadWin32Thread(VOID
)
839 return PsGetCurrentThread()->Tcb
.Win32Thread
;
847 PsSetThreadWin32Thread(IN PETHREAD Thread
,
848 IN PVOID Win32Thread
)
850 Thread
->Tcb
.Win32Thread
= Win32Thread
;
855 NtCreateThread(OUT PHANDLE ThreadHandle
,
856 IN ACCESS_MASK DesiredAccess
,
857 IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL
,
858 IN HANDLE ProcessHandle
,
859 OUT PCLIENT_ID ClientId
,
860 IN PCONTEXT ThreadContext
,
861 IN PINITIAL_TEB InitialTeb
,
862 IN BOOLEAN CreateSuspended
)
864 INITIAL_TEB SafeInitialTeb
;
865 NTSTATUS Status
= STATUS_SUCCESS
;
867 PSTRACE(PS_THREAD_DEBUG
,
868 "ProcessHandle: %p Context: %p\n", ProcessHandle
, ThreadContext
);
870 /* Check if this was from user-mode */
871 if (KeGetPreviousMode() != KernelMode
)
873 /* Make sure that we got a context */
874 if (!ThreadContext
) return STATUS_INVALID_PARAMETER
;
879 /* Make sure the handle pointer we got is valid */
880 ProbeForWriteHandle(ThreadHandle
);
882 /* Check if the caller wants a client id */
885 /* Make sure we can write to it */
886 ProbeForWrite(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
889 /* Make sure that the entire context is readable */
890 ProbeForRead(ThreadContext
, sizeof(CONTEXT
), sizeof(ULONG
));
892 /* Check the Initial TEB */
893 ProbeForRead(InitialTeb
, sizeof(INITIAL_TEB
), sizeof(ULONG
));
894 SafeInitialTeb
= *InitialTeb
;
898 Status
= _SEH_GetExceptionCode();
901 if (!NT_SUCCESS(Status
)) return Status
;
905 /* Use the Initial TEB as is */
906 SafeInitialTeb
= *InitialTeb
;
909 /* Call the shared function */
910 return PspCreateThread(ThreadHandle
,
928 NtOpenThread(OUT PHANDLE ThreadHandle
,
929 IN ACCESS_MASK DesiredAccess
,
930 IN POBJECT_ATTRIBUTES ObjectAttributes
,
931 IN PCLIENT_ID ClientId OPTIONAL
)
933 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
934 CLIENT_ID SafeClientId
;
935 ULONG Attributes
= 0;
936 HANDLE hThread
= NULL
;
937 NTSTATUS Status
= STATUS_SUCCESS
;
939 BOOLEAN HasObjectName
= FALSE
;
940 ACCESS_STATE AccessState
;
943 PSTRACE(PS_THREAD_DEBUG
,
944 "ClientId: %p ObjectAttributes: %p\n", ClientId
, ObjectAttributes
);
946 /* Check if we were called from user mode */
947 if (PreviousMode
!= KernelMode
)
949 /* Enter SEH for probing */
952 /* Probe the thread handle */
953 ProbeForWriteHandle(ThreadHandle
);
955 /* Check for a CID structure */
958 /* Probe and capture it */
959 ProbeForRead(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
960 SafeClientId
= *ClientId
;
961 ClientId
= &SafeClientId
;
965 * Just probe the object attributes structure, don't capture it
966 * completely. This is done later if necessary
968 ProbeForRead(ObjectAttributes
,
969 sizeof(OBJECT_ATTRIBUTES
),
971 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
972 Attributes
= ObjectAttributes
->Attributes
;
976 /* Get the exception code */
977 Status
= _SEH_GetExceptionCode();
980 if (!NT_SUCCESS(Status
)) return Status
;
984 /* Otherwise just get the data directly */
985 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
986 Attributes
= ObjectAttributes
->Attributes
;
989 /* Can't pass both, fail */
990 if ((HasObjectName
) && (ClientId
)) return STATUS_INVALID_PARAMETER_MIX
;
992 /* Create an access state */
993 Status
= SeCreateAccessState(&AccessState
,
996 &PsProcessType
->TypeInfo
.GenericMapping
);
997 if (!NT_SUCCESS(Status
)) return Status
;
999 /* Check if this is a debugger */
1000 if (SeSinglePrivilegeCheck(SeDebugPrivilege
, PreviousMode
))
1002 /* Did he want full access? */
1003 if (AccessState
.RemainingDesiredAccess
& MAXIMUM_ALLOWED
)
1005 /* Give it to him */
1006 AccessState
.PreviouslyGrantedAccess
|= THREAD_ALL_ACCESS
;
1010 /* Otherwise just give every other access he could want */
1011 AccessState
.PreviouslyGrantedAccess
|=
1012 AccessState
.RemainingDesiredAccess
;
1015 /* The caller desires nothing else now */
1016 AccessState
.RemainingDesiredAccess
= 0;
1019 /* Open by name if one was given */
1023 Status
= ObOpenObjectByName(ObjectAttributes
,
1031 /* Get rid of the access state */
1032 SeDeleteAccessState(&AccessState
);
1036 /* Open by Thread ID */
1037 if (ClientId
->UniqueProcess
)
1039 /* Get the Process */
1040 Status
= PsLookupProcessThreadByCid(ClientId
, NULL
, &Thread
);
1044 /* Get the Process */
1045 Status
= PsLookupThreadByThreadId(ClientId
->UniqueThread
, &Thread
);
1048 /* Check if we didn't find anything */
1049 if (!NT_SUCCESS(Status
))
1051 /* Get rid of the access state and return */
1052 SeDeleteAccessState(&AccessState
);
1056 /* Open the Thread Object */
1057 Status
= ObOpenObjectByPointer(Thread
,
1065 /* Delete the access state and dereference the thread */
1066 SeDeleteAccessState(&AccessState
);
1067 ObDereferenceObject(Thread
);
1071 /* Neither an object name nor a client id was passed */
1072 return STATUS_INVALID_PARAMETER_MIX
;
1075 /* Check for success */
1076 if (NT_SUCCESS(Status
))
1078 /* Protect against bad user-mode pointers */
1081 /* Write back the handle */
1082 *ThreadHandle
= hThread
;
1086 /* Get the exception code */
1087 Status
= _SEH_GetExceptionCode();