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(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
^
107 (ULONG_PTR
)&SystemTime
;
109 /* Set the new cookie*/
110 InterlockedCompareExchange((LONG
*)&SharedUserData
->Cookie
,
117 PspUnhandledExceptionInSystemThread(PEXCEPTION_POINTERS ExceptionPointers
)
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 */
131 KeBugCheckEx(SYSTEM_THREAD_EXCEPTION_NOT_HANDLED
,
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 the Start Routine */
158 StartRoutine(StartContext
);
161 _SEH2_EXCEPT(PspUnhandledExceptionInSystemThread(_SEH2_GetExceptionInformation()))
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
;
195 AUX_ACCESS_DATA AuxData
;
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
)KeGetContextPc(ThreadContext
);
324 Thread
->Win32StartAddress
= (PVOID
)KeGetContextReturnRegister(ThreadContext
);
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
;
460 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
462 /* Thread insertion failed, thread is dead */
463 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
465 /* If we were suspended, wake it up */
466 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
468 /* Dispatch thread */
469 KeReadyThread(&Thread
->Tcb
);
471 /* Dereference it, leaving only the keep-alive */
472 ObDereferenceObject(Thread
);
474 /* Close its handle, killing it */
475 ObCloseHandle(ThreadHandle
, PreviousMode
);
477 /* Return the exception code */
478 _SEH2_YIELD(return _SEH2_GetExceptionCode());
484 /* Thread insertion failed, thread is dead */
485 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
487 /* If we were suspended, wake it up */
488 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
491 /* Get the create time */
492 KeQuerySystemTime(&Thread
->CreateTime
);
493 ASSERT(!(Thread
->CreateTime
.HighPart
& 0xF0000000));
495 /* Make sure the thread isn't dead */
496 if (!Thread
->DeadThread
)
498 /* Get the thread's SD */
499 Status
= ObGetObjectSecurity(Thread
,
502 if (!NT_SUCCESS(Status
))
504 /* Thread insertion failed, thread is dead */
505 PspSetCrossThreadFlag(Thread
, CT_DEAD_THREAD_BIT
);
507 /* If we were suspended, wake it up */
508 if (CreateSuspended
) KeResumeThread(&Thread
->Tcb
);
510 /* Dispatch thread */
511 KeReadyThread(&Thread
->Tcb
);
513 /* Dereference it, leaving only the keep-alive */
514 ObDereferenceObject(Thread
);
516 /* Close its handle, killing it */
517 ObCloseHandle(ThreadHandle
, PreviousMode
);
521 /* Create the subject context */
522 SubjectContext
.ProcessAuditId
= Process
;
523 SubjectContext
.PrimaryToken
= PsReferencePrimaryToken(Process
);
524 SubjectContext
.ClientToken
= NULL
;
526 /* Do the access check */
527 Result
= SeAccessCheck(SecurityDescriptor
,
533 &PsThreadType
->TypeInfo
.GenericMapping
,
535 &Thread
->GrantedAccess
,
538 /* Dereference the token and let go the SD */
539 ObFastDereferenceObject(&Process
->Token
,
540 SubjectContext
.PrimaryToken
);
541 ObReleaseObjectSecurity(SecurityDescriptor
, SdAllocated
);
543 /* Remove access if it failed */
544 if (!Result
) Process
->GrantedAccess
= 0;
546 /* Set least some minimum access */
547 Thread
->GrantedAccess
|= (THREAD_TERMINATE
|
548 THREAD_SET_INFORMATION
|
549 THREAD_QUERY_INFORMATION
);
553 /* Set the thread access mask to maximum */
554 Thread
->GrantedAccess
= THREAD_ALL_ACCESS
;
557 /* Dispatch thread */
558 KeReadyThread(&Thread
->Tcb
);
560 /* Dereference it, leaving only the keep-alive */
561 ObDereferenceObject(Thread
);
566 /* Most annoying failure case ever, where we undo almost all manually */
568 /* When we get here, the process is locked, unlock it */
569 ExReleasePushLockExclusive(&Process
->ProcessLock
);
570 KeLeaveCriticalRegion();
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
? TRUE
: FALSE
;
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
? TRUE
: FALSE
;
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
;
866 PSTRACE(PS_THREAD_DEBUG
,
867 "ProcessHandle: %p Context: %p\n", ProcessHandle
, ThreadContext
);
869 /* Check if this was from user-mode */
870 if (KeGetPreviousMode() != KernelMode
)
872 /* Make sure that we got a context */
873 if (!ThreadContext
) return STATUS_INVALID_PARAMETER
;
878 /* Make sure the handle pointer we got is valid */
879 ProbeForWriteHandle(ThreadHandle
);
881 /* Check if the caller wants a client id */
884 /* Make sure we can write to it */
885 ProbeForWrite(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
888 /* Make sure that the entire context is readable */
889 ProbeForRead(ThreadContext
, sizeof(CONTEXT
), sizeof(ULONG
));
891 /* Check the Initial TEB */
892 ProbeForRead(InitialTeb
, sizeof(INITIAL_TEB
), sizeof(ULONG
));
893 SafeInitialTeb
= *InitialTeb
;
895 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
897 /* Return the exception code */
898 _SEH2_YIELD(return _SEH2_GetExceptionCode());
904 /* Use the Initial TEB as is */
905 SafeInitialTeb
= *InitialTeb
;
908 /* Call the shared function */
909 return PspCreateThread(ThreadHandle
,
927 NtOpenThread(OUT PHANDLE ThreadHandle
,
928 IN ACCESS_MASK DesiredAccess
,
929 IN POBJECT_ATTRIBUTES ObjectAttributes
,
930 IN PCLIENT_ID ClientId OPTIONAL
)
932 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
933 CLIENT_ID SafeClientId
;
934 ULONG Attributes
= 0;
935 HANDLE hThread
= NULL
;
938 BOOLEAN HasObjectName
= FALSE
;
939 ACCESS_STATE AccessState
;
940 AUX_ACCESS_DATA AuxData
;
942 PSTRACE(PS_THREAD_DEBUG
,
943 "ClientId: %p ObjectAttributes: %p\n", ClientId
, ObjectAttributes
);
945 /* Check if we were called from user mode */
946 if (PreviousMode
!= KernelMode
)
948 /* Enter SEH for probing */
951 /* Probe the thread handle */
952 ProbeForWriteHandle(ThreadHandle
);
954 /* Check for a CID structure */
957 /* Probe and capture it */
958 ProbeForRead(ClientId
, sizeof(CLIENT_ID
), sizeof(ULONG
));
959 SafeClientId
= *ClientId
;
960 ClientId
= &SafeClientId
;
964 * Just probe the object attributes structure, don't capture it
965 * completely. This is done later if necessary
967 ProbeForRead(ObjectAttributes
,
968 sizeof(OBJECT_ATTRIBUTES
),
970 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
971 Attributes
= ObjectAttributes
->Attributes
;
973 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
975 /* Return the exception code */
976 _SEH2_YIELD(return _SEH2_GetExceptionCode());
982 /* Otherwise just get the data directly */
983 HasObjectName
= (ObjectAttributes
->ObjectName
!= NULL
);
984 Attributes
= ObjectAttributes
->Attributes
;
987 /* Can't pass both, fail */
988 if ((HasObjectName
) && (ClientId
)) return STATUS_INVALID_PARAMETER_MIX
;
990 /* Create an access state */
991 Status
= SeCreateAccessState(&AccessState
,
994 &PsProcessType
->TypeInfo
.GenericMapping
);
995 if (!NT_SUCCESS(Status
)) return Status
;
997 /* Check if this is a debugger */
998 if (SeSinglePrivilegeCheck(SeDebugPrivilege
, PreviousMode
))
1000 /* Did he want full access? */
1001 if (AccessState
.RemainingDesiredAccess
& MAXIMUM_ALLOWED
)
1003 /* Give it to him */
1004 AccessState
.PreviouslyGrantedAccess
|= THREAD_ALL_ACCESS
;
1008 /* Otherwise just give every other access he could want */
1009 AccessState
.PreviouslyGrantedAccess
|=
1010 AccessState
.RemainingDesiredAccess
;
1013 /* The caller desires nothing else now */
1014 AccessState
.RemainingDesiredAccess
= 0;
1017 /* Open by name if one was given */
1021 Status
= ObOpenObjectByName(ObjectAttributes
,
1029 /* Get rid of the access state */
1030 SeDeleteAccessState(&AccessState
);
1034 /* Open by Thread ID */
1035 if (ClientId
->UniqueProcess
)
1037 /* Get the Process */
1038 Status
= PsLookupProcessThreadByCid(ClientId
, NULL
, &Thread
);
1042 /* Get the Process */
1043 Status
= PsLookupThreadByThreadId(ClientId
->UniqueThread
, &Thread
);
1046 /* Check if we didn't find anything */
1047 if (!NT_SUCCESS(Status
))
1049 /* Get rid of the access state and return */
1050 SeDeleteAccessState(&AccessState
);
1054 /* Open the Thread Object */
1055 Status
= ObOpenObjectByPointer(Thread
,
1063 /* Delete the access state and dereference the thread */
1064 SeDeleteAccessState(&AccessState
);
1065 ObDereferenceObject(Thread
);
1069 /* Neither an object name nor a client id was passed */
1070 return STATUS_INVALID_PARAMETER_MIX
;
1073 /* Check for success */
1074 if (NT_SUCCESS(Status
))
1076 /* Protect against bad user-mode pointers */
1079 /* Write back the handle */
1080 *ThreadHandle
= hThread
;
1082 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1084 /* Get the exception code */
1085 Status
= _SEH2_GetExceptionCode();