[NTOSKRNL]
[reactos.git] / reactos / ntoskrnl / ps / thread.c
index 4c92748..d05fc85 100644 (file)
@@ -4,49 +4,35 @@
  * FILE:            ntoskrnl/ps/thread.c
  * PURPOSE:         Process Manager: Thread Management
  * PROGRAMMERS:     Alex Ionescu (alex.ionescu@reactos.org)
- *                  Thomas Weidenmueller (w3seek@reactos.org
- */
-
-/*
- * Alex FIXMEs:
- *  - CRITICAL: NtCurrentTeb returns KPCR.
- *  - MAJOR: Use Process Rundown
- *  - MAJOR: Use Process Pushlock Locks
- *  - MAJOR: Implement Safe Referencing (See PsGetNextProcess/Thread).
- *  - MAJOR: Use Guarded Mutex instead of Fast Mutex for Active Process Locks.
- *  - Generate process cookie for user-more thread.
- *  - Add security calls where necessary.
- *  - KeInit/StartThread for better isolation of code
+ *                  Thomas Weidenmueller (w3seek@reactos.org)
  */
 
 /* INCLUDES ****************************************************************/
 
 #include <ntoskrnl.h>
 #define NDEBUG
-#include <internal/debug.h>
+#include <debug.h>
 
 /* GLOBALS ******************************************************************/
 
-extern LIST_ENTRY PsActiveProcessHead;
-extern PEPROCESS PsIdleProcess;
-extern PVOID PspSystemDllEntryPoint;
-extern PVOID PspSystemDllBase;
-extern PHANDLE_TABLE PspCidTable;
 extern BOOLEAN CcPfEnablePrefetcher;
 extern ULONG MmReadClusterSize;
 POBJECT_TYPE PsThreadType = NULL;
 
-/* FUNCTIONS ***************************************************************/
+/* PRIVATE FUNCTIONS *********************************************************/
 
 VOID
 NTAPI
-PspUserThreadStartup(PKSTART_ROUTINE StartRoutine,
-                     PVOID StartContext)
+PspUserThreadStartup(IN PKSTART_ROUTINE StartRoutine,
+                     IN PVOID StartContext)
 {
     PETHREAD Thread;
     PTEB Teb;
     BOOLEAN DeadThread = FALSE;
+    KIRQL OldIrql;
     PAGED_CODE();
+    PSTRACE(PS_THREAD_DEBUG,
+            "StartRoutine: %p StartContext: %p\n", StartRoutine, StartContext);
 
     /* Go to Passive Level */
     KeLowerIrql(PASSIVE_LEVEL);
@@ -56,22 +42,21 @@ PspUserThreadStartup(PKSTART_ROUTINE StartRoutine,
     if (Thread->DeadThread)
     {
         /* Remember that we're dead */
-        DPRINT1("This thread is already dead\n");
         DeadThread = TRUE;
-}
+    }
     else
     {
         /* Get the Locale ID and save Preferred Proc */
-        Teb =  NtCurrentTeb(); /* FIXME: This returns KPCR!!! */
-        //Teb->CurrentLocale = MmGetSessionLocaleId();
-        //Teb->IdealProcessor = Thread->Tcb.IdealProcessor;
+        Teb =  NtCurrentTeb();
+        Teb->CurrentLocale = MmGetSessionLocaleId();
+        Teb->IdealProcessor = Thread->Tcb.IdealProcessor;
     }
 
-    /* Check if this is a system thread, or if we're hiding */
-    if ((Thread->SystemThread) || (Thread->HideFromDebugger))
-{
-        /* Notify the debugger */
-        DbgkCreateThread(StartContext);
+    /* Check if this is a dead thread, or if we're hiding */
+    if (!(Thread->DeadThread) && !(Thread->HideFromDebugger))
+    {
+        /* We're not, so notify the debugger */
+        DbgkCreateThread(Thread, StartContext);
     }
 
     /* Make sure we're not already dead */
@@ -84,17 +69,15 @@ PspUserThreadStartup(PKSTART_ROUTINE StartRoutine,
         }
 
         /* Raise to APC */
-        KfRaiseIrql(APC_LEVEL);
+        KeRaiseIrql(APC_LEVEL, &OldIrql);
 
         /* Queue the User APC */
-        KiInitializeUserApc(NULL,
-                            (PVOID)((ULONG_PTR)Thread->Tcb.InitialStack -
-                            sizeof(KTRAP_FRAME) -
-                            sizeof(FX_SAVE_AREA)),
+        KiInitializeUserApc(KeGetExceptionFrame(&Thread->Tcb),
+                            KeGetTrapFrame(&Thread->Tcb),
                             PspSystemDllEntryPoint,
-                        NULL,
+                            NULL,
                             PspSystemDllBase,
-                        NULL);
+                            NULL);
 
         /* Lower it back to passive */
         KeLowerIrql(PASSIVE_LEVEL);
@@ -102,33 +85,83 @@ PspUserThreadStartup(PKSTART_ROUTINE StartRoutine,
     else
     {
         /* We're dead, kill us now */
-        PspTerminateThreadByPointer(Thread, STATUS_THREAD_IS_TERMINATING, TRUE);
+        PspTerminateThreadByPointer(Thread,
+                                    STATUS_THREAD_IS_TERMINATING,
+                                    TRUE);
     }
 
     /* Do we have a cookie set yet? */
     if (!SharedUserData->Cookie)
     {
-        /* FIXME: Generate cookie */
+        LARGE_INTEGER SystemTime;
+        ULONG NewCookie;
+        PKPRCB Prcb;
+
+        /* Generate a new cookie */
+        KeQuerySystemTime(&SystemTime);
+        Prcb = KeGetCurrentPrcb();
+        NewCookie = Prcb->MmPageFaultCount ^ Prcb->InterruptTime ^
+                    SystemTime.u.LowPart ^ SystemTime.u.HighPart ^
+                    (ULONG_PTR)&SystemTime;
+
+        /* Set the new cookie*/
+        InterlockedCompareExchange((LONG*)&SharedUserData->Cookie,
+                                   NewCookie,
+                                   0);
     }
 }
 
+LONG
+PspUnhandledExceptionInSystemThread(PEXCEPTION_POINTERS ExceptionPointers)
+{
+    /* Print debugging information */
+    DPRINT1("PS: Unhandled Kernel Mode Exception Pointers = 0x%p\n",
+            ExceptionPointers);
+    DPRINT1("Code %x Addr %p Info0 %p Info1 %p Info2 %p Info3 %p\n",
+            ExceptionPointers->ExceptionRecord->ExceptionCode,
+            ExceptionPointers->ExceptionRecord->ExceptionAddress,
+            ExceptionPointers->ExceptionRecord->ExceptionInformation[0],
+            ExceptionPointers->ExceptionRecord->ExceptionInformation[1],
+            ExceptionPointers->ExceptionRecord->ExceptionInformation[2],
+            ExceptionPointers->ExceptionRecord->ExceptionInformation[3]);
+
+    /* Bugcheck the system */
+    KeBugCheckEx(SYSTEM_THREAD_EXCEPTION_NOT_HANDLED,
+                 ExceptionPointers->ExceptionRecord->ExceptionCode,
+                 (ULONG_PTR)ExceptionPointers->ExceptionRecord->ExceptionAddress,
+                 (ULONG_PTR)ExceptionPointers->ExceptionRecord,
+                 (ULONG_PTR)ExceptionPointers->ContextRecord);
+    return 0;
+}
+
 VOID
 NTAPI
-PspSystemThreadStartup(PKSTART_ROUTINE StartRoutine,
-                       PVOID StartContext)
+PspSystemThreadStartup(IN PKSTART_ROUTINE StartRoutine,
+                       IN PVOID StartContext)
 {
     PETHREAD Thread;
+    PSTRACE(PS_THREAD_DEBUG,
+            "StartRoutine: %p StartContext: %p\n", StartRoutine, StartContext);
 
     /* Unlock the dispatcher Database */
     KeLowerIrql(PASSIVE_LEVEL);
     Thread = PsGetCurrentThread();
 
     /* Make sure the thread isn't gone */
-    if (!(Thread->Terminated) || !(Thread->DeadThread))
+    _SEH2_TRY
+    {
+        if (!(Thread->Terminated) && !(Thread->DeadThread))
+        {
+            /* Call the Start Routine */
+            StartRoutine(StartContext);
+        }
+    }
+    _SEH2_EXCEPT(PspUnhandledExceptionInSystemThread(_SEH2_GetExceptionInformation()))
     {
-        /* Call it the Start Routine */
-        StartRoutine(StartContext);
+        /* Bugcheck if we got here */
+        KeBugCheck(KMODE_EXCEPTION_NOT_HANDLED);
     }
+    _SEH2_END;
 
     /* Exit the thread */
     PspTerminateThreadByPointer(Thread, STATUS_SUCCESS, TRUE);
@@ -138,7 +171,7 @@ NTSTATUS
 NTAPI
 PspCreateThread(OUT PHANDLE ThreadHandle,
                 IN ACCESS_MASK DesiredAccess,
-                IN POBJECT_ATTRIBUTES ObjectAttributes  OPTIONAL,
+                IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
                 IN HANDLE ProcessHandle,
                 IN PEPROCESS TargetProcess,
                 OUT PCLIENT_ID ClientId,
@@ -151,13 +184,20 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     HANDLE hThread;
     PEPROCESS Process;
     PETHREAD Thread;
-    PTEB TebBase;
-    KIRQL OldIrql;
+    PTEB TebBase = NULL;
     KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
-    NTSTATUS Status;
+    NTSTATUS Status, AccessStatus;
     HANDLE_TABLE_ENTRY CidEntry;
-    ULONG_PTR KernelStack;
+    ACCESS_STATE LocalAccessState;
+    PACCESS_STATE AccessState = &LocalAccessState;
+    AUX_ACCESS_DATA AuxData;
+    BOOLEAN Result, SdAllocated;
+    PSECURITY_DESCRIPTOR SecurityDescriptor;
+    SECURITY_SUBJECT_CONTEXT SubjectContext;
     PAGED_CODE();
+    PSTRACE(PS_THREAD_DEBUG,
+            "ThreadContext: %p TargetProcess: %p ProcessHandle: %p\n",
+            ThreadContext, TargetProcess, ProcessHandle);
 
     /* If we were called from PsCreateSystemThread, then we're kernel mode */
     if (StartRoutine) PreviousMode = KernelMode;
@@ -172,6 +212,7 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
                                            PreviousMode,
                                            (PVOID*)&Process,
                                            NULL);
+        PSREFTRACE(Process);
     }
     else
     {
@@ -191,15 +232,12 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     }
 
     /* Check for success */
-    if(!NT_SUCCESS(Status))
-    {
-        DPRINT1("Invalid Process Handle, or no handle given\n");
-        return Status;
-    }
+    if (!NT_SUCCESS(Status)) return Status;
 
     /* Also make sure that User-Mode isn't trying to create a system thread */
     if ((PreviousMode != KernelMode) && (Process == PsInitialSystemProcess))
     {
+        /* Fail */
         ObDereferenceObject(Process);
         return STATUS_INVALID_HANDLE;
     }
@@ -208,7 +246,7 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     Status = ObCreateObject(PreviousMode,
                             PsThreadType,
                             ObjectAttributes,
-                            KernelMode,
+                            PreviousMode,
                             NULL,
                             sizeof(ETHREAD),
                             0,
@@ -217,7 +255,6 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     if (!NT_SUCCESS(Status))
     {
         /* We failed; dereference the process and exit */
-        DPRINT1("Failed to Create Thread Object\n");
         ObDereferenceObject(Process);
         return Status;
     }
@@ -225,6 +262,12 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     /* Zero the Object entirely */
     RtlZeroMemory(Thread, sizeof(ETHREAD));
 
+    /* Initialize rundown protection */
+    ExInitializeRundownProtection(&Thread->RundownProtect);
+
+    /* Initialize exit code */
+    Thread->ExitStatus = STATUS_PENDING;
+
     /* Set the Process CID */
     Thread->ThreadsProcess = Process;
     Thread->Cid.UniqueProcess = Process->UniqueProcessId;
@@ -235,9 +278,7 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     Thread->Cid.UniqueThread = ExCreateHandle(PspCidTable, &CidEntry);
     if (!Thread->Cid.UniqueThread)
     {
-        /* We couldn't create the CID, dereference everything and fail */
-        DPRINT1("Failed to create Thread Handle (CID)\n");
-        ObDereferenceObject(Process);
+        /* We couldn't create the CID, dereference the thread and fail */
         ObDereferenceObject(Thread);
         return STATUS_INSUFFICIENT_RESOURCES;
     }
@@ -246,7 +287,7 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     Thread->ReadClusterSize = MmReadClusterSize;
 
     /* Initialize the LPC Reply Semaphore */
-    KeInitializeSemaphore(&Thread->LpcReplySemaphore, 0, MAXLONG);
+    KeInitializeSemaphore(&Thread->LpcReplySemaphore, 0, 1);
 
     /* Initialize the list heads and locks */
     InitializeListHead(&Thread->LpcReplyChain);
@@ -255,44 +296,84 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     InitializeListHead(&Thread->ActiveTimerListHead);
     KeInitializeSpinLock(&Thread->ActiveTimerListLock);
 
-    /* Allocate Stack for non-GUI Thread */
-    KernelStack = (ULONG_PTR)MmCreateKernelStack(FALSE) + KERNEL_STACK_SIZE;
+    /* Acquire rundown protection */
+    if (!ExAcquireRundownProtection (&Process->RundownProtect))
+    {
+        /* Fail */
+        ObDereferenceObject(Thread);
+        return STATUS_PROCESS_IS_TERMINATING;
+    }
 
     /* Now let the kernel initialize the context */
     if (ThreadContext)
     {
         /* User-mode Thread, create Teb */
-        TebBase = MmCreateTeb(Process, &Thread->Cid, InitialTeb);
+        Status = MmCreateTeb(Process, &Thread->Cid, InitialTeb, &TebBase);
+        if (!NT_SUCCESS(Status))
+        {
+            /* Failed to create the TEB. Release rundown and dereference */
+            ExReleaseRundownProtection(&Process->RundownProtect);
+            ObDereferenceObject(Thread);
+            return Status;
+        }
 
         /* Set the Start Addresses */
-        Thread->StartAddress = (PVOID)ThreadContext->Eip;
-        Thread->Win32StartAddress = (PVOID)ThreadContext->Eax;
+        Thread->StartAddress = (PVOID)KeGetContextPc(ThreadContext);
+        Thread->Win32StartAddress = (PVOID)KeGetContextReturnRegister(ThreadContext);
 
         /* Let the kernel intialize the Thread */
-        KeInitializeThread(&Process->Pcb,
-                           &Thread->Tcb,
-                           PspUserThreadStartup,
-                           NULL,
-                           NULL,
-                           ThreadContext,
-                           TebBase,
-                           (PVOID)KernelStack);
+        Status = KeInitThread(&Thread->Tcb,
+                              NULL,
+                              PspUserThreadStartup,
+                              NULL,
+                              Thread->StartAddress,
+                              ThreadContext,
+                              TebBase,
+                              &Process->Pcb);
     }
     else
     {
         /* System Thread */
         Thread->StartAddress = StartRoutine;
-        InterlockedOr((PLONG)&Thread->CrossThreadFlags, 0x10);
+        PspSetCrossThreadFlag(Thread, CT_SYSTEM_THREAD_BIT);
 
         /* Let the kernel intialize the Thread */
-        KeInitializeThread(&Process->Pcb,
-                           &Thread->Tcb,
-                           PspSystemThreadStartup,
-                           StartRoutine,
-                           StartContext,
-                           NULL,
-                           NULL,
-                           (PVOID)KernelStack);
+        Status = KeInitThread(&Thread->Tcb,
+                              NULL,
+                              PspSystemThreadStartup,
+                              StartRoutine,
+                              StartContext,
+                              NULL,
+                              NULL,
+                              &Process->Pcb);
+    }
+
+    /* Check if we failed */
+    if (!NT_SUCCESS(Status))
+    {
+        /* Delete the TEB if we had done */
+        if (TebBase) MmDeleteTeb(Process, TebBase);
+
+        /* Release rundown and dereference */
+        ExReleaseRundownProtection(&Process->RundownProtect);
+        ObDereferenceObject(Thread);
+        return Status;
+    }
+
+    /* Lock the process */
+    KeEnterCriticalRegion();
+    ExAcquirePushLockExclusive(&Process->ProcessLock);
+
+    /* Make sure the proces didn't just die on us */
+    if (Process->ProcessDelete) goto Quickie;
+
+    /* Check if the thread was ours, terminated and it was user mode */
+    if ((Thread->Terminated) &&
+        (ThreadContext) &&
+        (Thread->ThreadsProcess == Process))
+    {
+        /* Cleanup, we don't want to start it up and context switch */
+        goto Quickie;
     }
 
     /*
@@ -303,6 +384,16 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     InsertTailList(&Process->ThreadListHead, &Thread->ThreadListEntry);
     Process->ActiveThreads++;
 
+    /* Start the thread */
+    KeStartThread(&Thread->Tcb);
+
+    /* Release the process lock */
+    ExReleasePushLockExclusive(&Process->ProcessLock);
+    KeLeaveCriticalRegion();
+
+    /* Release rundown */
+    ExReleaseRundownProtection(&Process->RundownProtect);
+
     /* Notify WMI */
     //WmiTraceProcess(Process, TRUE);
     //WmiTraceThread(Thread, InitialTeb, TRUE);
@@ -310,72 +401,207 @@ PspCreateThread(OUT PHANDLE ThreadHandle,
     /* Notify Thread Creation */
     PspRunCreateThreadNotifyRoutines(Thread, TRUE);
 
+    /* Reference ourselves as a keep-alive */
+    ObReferenceObjectEx(Thread, 2);
+
     /* Suspend the Thread if we have to */
-    if (CreateSuspended)
-    {
-        KeSuspendThread(&Thread->Tcb);
-    }
+    if (CreateSuspended) KeSuspendThread(&Thread->Tcb);
 
     /* Check if we were already terminated */
-    if (Thread->Terminated)
+    if (Thread->Terminated) KeForceResumeThread(&Thread->Tcb);
+
+    /* Create an access state */
+    Status = SeCreateAccessStateEx(NULL,
+                                   ThreadContext ?
+                                   PsGetCurrentProcess() : Process,
+                                   &LocalAccessState,
+                                   &AuxData,
+                                   DesiredAccess,
+                                   &PsThreadType->TypeInfo.GenericMapping);
+    if (!NT_SUCCESS(Status))
     {
-        /* Force us to wake up to terminate */
-        KeForceResumeThread(&Thread->Tcb);
-    }
+        /* Access state failed, thread is dead */
+        PspSetCrossThreadFlag(Thread, CT_DEAD_THREAD_BIT);
 
-    /* Reference ourselves as a keep-alive */
-    ObReferenceObject(Thread);
+        /* If we were suspended, wake it up */
+        if (CreateSuspended) KeResumeThread(&Thread->Tcb);
+
+        /* Dispatch thread */
+        KeReadyThread(&Thread->Tcb);
+
+        /* Dereference completely to kill it */
+        ObDereferenceObjectEx(Thread, 2);
+        return Status;
+    }
 
     /* Insert the Thread into the Object Manager */
-    Status = ObInsertObject((PVOID)Thread,
-                            NULL,
+    Status = ObInsertObject(Thread,
+                            AccessState,
                             DesiredAccess,
                             0,
                             NULL,
                             &hThread);
-    if(NT_SUCCESS(Status))
+
+    /* Delete the access state if we had one */
+    if (AccessState) SeDeleteAccessState(AccessState);
+
+    /* Check for success */
+    if (NT_SUCCESS(Status))
     {
         /* Wrap in SEH to protect against bad user-mode pointers */
-        _SEH_TRY
+        _SEH2_TRY
         {
             /* Return Cid and Handle */
-            if(ClientId) *ClientId = Thread->Cid;
+            if (ClientId) *ClientId = Thread->Cid;
             *ThreadHandle = hThread;
         }
-        _SEH_HANDLE
+        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
         {
-            Status = _SEH_GetExceptionCode();
+            /* Thread insertion failed, thread is dead */
+            PspSetCrossThreadFlag(Thread, CT_DEAD_THREAD_BIT);
+
+            /* If we were suspended, wake it up */
+            if (CreateSuspended) KeResumeThread(&Thread->Tcb);
+
+            /* Dispatch thread */
+            KeReadyThread(&Thread->Tcb);
+
+            /* Dereference it, leaving only the keep-alive */
+            ObDereferenceObject(Thread);
+
+            /* Close its handle, killing it */
+            ObCloseHandle(ThreadHandle, PreviousMode);
+
+            /* Return the exception code */
+            _SEH2_YIELD(return _SEH2_GetExceptionCode());
         }
-        _SEH_END;
+        _SEH2_END;
     }
+    else
+    {
+        /* Thread insertion failed, thread is dead */
+        PspSetCrossThreadFlag(Thread, CT_DEAD_THREAD_BIT);
+
+        /* If we were suspended, wake it up */
+        if (CreateSuspended) KeResumeThread(&Thread->Tcb);
+    }
+
+    /* Get the create time */
+    KeQuerySystemTime(&Thread->CreateTime);
+    ASSERT(!(Thread->CreateTime.HighPart & 0xF0000000));
 
-    /* FIXME: SECURITY */
+    /* Make sure the thread isn't dead */
+    if (!Thread->DeadThread)
+    {
+        /* Get the thread's SD */
+        Status = ObGetObjectSecurity(Thread,
+                                     &SecurityDescriptor,
+                                     &SdAllocated);
+        if (!NT_SUCCESS(Status))
+        {
+            /* Thread insertion failed, thread is dead */
+            PspSetCrossThreadFlag(Thread, CT_DEAD_THREAD_BIT);
+
+            /* If we were suspended, wake it up */
+            if (CreateSuspended) KeResumeThread(&Thread->Tcb);
+
+            /* Dispatch thread */
+            KeReadyThread(&Thread->Tcb);
+
+            /* Dereference it, leaving only the keep-alive */
+            ObDereferenceObject(Thread);
+
+            /* Close its handle, killing it */
+            ObCloseHandle(ThreadHandle, PreviousMode);
+            return Status;
+        }
+
+        /* Create the subject context */
+        SubjectContext.ProcessAuditId = Process;
+        SubjectContext.PrimaryToken = PsReferencePrimaryToken(Process);
+        SubjectContext.ClientToken = NULL;
+
+        /* Do the access check */
+        Result = SeAccessCheck(SecurityDescriptor,
+                               &SubjectContext,
+                               FALSE,
+                               MAXIMUM_ALLOWED,
+                               0,
+                               NULL,
+                               &PsThreadType->TypeInfo.GenericMapping,
+                               PreviousMode,
+                               &Thread->GrantedAccess,
+                               &AccessStatus);
+
+        /* Dereference the token and let go the SD */
+        ObFastDereferenceObject(&Process->Token,
+                                SubjectContext.PrimaryToken);
+        ObReleaseObjectSecurity(SecurityDescriptor, SdAllocated);
+
+        /* Remove access if it failed */
+        if (!Result) Process->GrantedAccess = 0;
+
+        /* Set least some minimum access */
+        Thread->GrantedAccess |= (THREAD_TERMINATE |
+                                  THREAD_SET_INFORMATION |
+                                  THREAD_QUERY_INFORMATION);
+    }
+    else
+    {
+        /* Set the thread access mask to maximum */
+        Thread->GrantedAccess = THREAD_ALL_ACCESS;
+    }
 
     /* Dispatch thread */
-    OldIrql = KeAcquireDispatcherDatabaseLock ();
-    KiUnblockThread(&Thread->Tcb, NULL, 0);
-    KeReleaseDispatcherDatabaseLock(OldIrql);
+    KeReadyThread(&Thread->Tcb);
+
+    /* Dereference it, leaving only the keep-alive */
+    ObDereferenceObject(Thread);
 
     /* Return */
     return Status;
+
+    /* Most annoying failure case ever, where we undo almost all manually */
+Quickie:
+    /* When we get here, the process is locked, unlock it */
+    ExReleasePushLockExclusive(&Process->ProcessLock);
+    KeLeaveCriticalRegion();
+
+    /* Uninitailize it */
+    KeUninitThread(&Thread->Tcb);
+
+    /* If we had a TEB, delete it */
+    if (TebBase) MmDeleteTeb(Process, TebBase);
+
+    /* Release rundown protection, which we also hold */
+    ExReleaseRundownProtection(&Process->RundownProtect);
+
+    /* Dereference the thread and return failure */
+    ObDereferenceObject(Thread);
+    return STATUS_PROCESS_IS_TERMINATING;
 }
 
+/* PUBLIC FUNCTIONS **********************************************************/
+
 /*
  * @implemented
  */
 NTSTATUS
 NTAPI
-PsCreateSystemThread(PHANDLE ThreadHandle,
-                     ACCESS_MASK DesiredAccess,
-                     POBJECT_ATTRIBUTES ObjectAttributes,
-                     HANDLE ProcessHandle,
-                     PCLIENT_ID ClientId,
-                     PKSTART_ROUTINE StartRoutine,
-                     PVOID StartContext)
+PsCreateSystemThread(OUT PHANDLE ThreadHandle,
+                     IN ACCESS_MASK DesiredAccess,
+                     IN POBJECT_ATTRIBUTES ObjectAttributes,
+                     IN HANDLE ProcessHandle,
+                     IN PCLIENT_ID ClientId,
+                     IN PKSTART_ROUTINE StartRoutine,
+                     IN PVOID StartContext)
 {
     PEPROCESS TargetProcess = NULL;
     HANDLE Handle = ProcessHandle;
     PAGED_CODE();
+    PSTRACE(PS_THREAD_DEBUG,
+            "ProcessHandle: %p StartRoutine: %p StartContext: %p\n",
+            ProcessHandle, StartRoutine, StartContext);
 
     /* Check if we have a handle. If not, use the System Process */
     if (!ProcessHandle)
@@ -410,11 +636,12 @@ PsLookupThreadByThreadId(IN HANDLE ThreadId,
     PETHREAD FoundThread;
     NTSTATUS Status = STATUS_INVALID_PARAMETER;
     PAGED_CODE();
+    PSTRACE(PS_THREAD_DEBUG, "ThreadId: %p\n", ThreadId);
     KeEnterCriticalRegion();
 
     /* Get the CID Handle Entry */
-    if ((CidEntry = ExMapHandleToPointer(PspCidTable,
-                                         ThreadId)))
+    CidEntry = ExMapHandleToPointer(PspCidTable, ThreadId);
+    if (CidEntry)
     {
         /* Get the Process */
         FoundThread = CidEntry->Object;
@@ -422,16 +649,18 @@ PsLookupThreadByThreadId(IN HANDLE ThreadId,
         /* Make sure it's really a process */
         if (FoundThread->Tcb.DispatcherHeader.Type == ThreadObject)
         {
-            /* Reference and return it */
-            ObReferenceObject(FoundThread);
-            *Thread = FoundThread;
-            Status = STATUS_SUCCESS;
+            /* Safe Reference and return it */
+            if (ObReferenceObjectSafe(FoundThread))
+            {
+                *Thread = FoundThread;
+                Status = STATUS_SUCCESS;
+            }
         }
 
         /* Unlock the Entry */
         ExUnlockHandleTableEntry(PspCidTable, CidEntry);
     }
-    
+
     /* Return to caller */
     KeLeaveCriticalRegion();
     return Status;
@@ -444,7 +673,7 @@ HANDLE
 NTAPI
 PsGetCurrentThreadId(VOID)
 {
-    return(PsGetCurrentThread()->Cid.UniqueThread);
+    return PsGetCurrentThread()->Cid.UniqueThread;
 }
 
 /*
@@ -452,7 +681,7 @@ PsGetCurrentThreadId(VOID)
  */
 ULONG
 NTAPI
-PsGetThreadFreezeCount(PETHREAD Thread)
+PsGetThreadFreezeCount(IN PETHREAD Thread)
 {
     return Thread->Tcb.FreezeCount;
 }
@@ -462,9 +691,9 @@ PsGetThreadFreezeCount(PETHREAD Thread)
  */
 BOOLEAN
 NTAPI
-PsGetThreadHardErrorsAreDisabled(PETHREAD Thread)
+PsGetThreadHardErrorsAreDisabled(IN PETHREAD Thread)
 {
-    return Thread->HardErrorsAreDisabled;
+    return Thread->HardErrorsAreDisabled ? TRUE : FALSE;
 }
 
 /*
@@ -472,7 +701,7 @@ PsGetThreadHardErrorsAreDisabled(PETHREAD Thread)
  */
 HANDLE
 NTAPI
-PsGetThreadId(PETHREAD Thread)
+PsGetThreadId(IN PETHREAD Thread)
 {
     return Thread->Cid.UniqueThread;
 }
@@ -482,7 +711,7 @@ PsGetThreadId(PETHREAD Thread)
  */
 PEPROCESS
 NTAPI
-PsGetThreadProcess(PETHREAD Thread)
+PsGetThreadProcess(IN PETHREAD Thread)
 {
     return Thread->ThreadsProcess;
 }
@@ -492,7 +721,7 @@ PsGetThreadProcess(PETHREAD Thread)
  */
 HANDLE
 NTAPI
-PsGetThreadProcessId(PETHREAD Thread)
+PsGetThreadProcessId(IN PETHREAD Thread)
 {
     return Thread->Cid.UniqueProcess;
 }
@@ -502,7 +731,7 @@ PsGetThreadProcessId(PETHREAD Thread)
  */
 HANDLE
 NTAPI
-PsGetThreadSessionId(PETHREAD Thread)
+PsGetThreadSessionId(IN PETHREAD Thread)
 {
     return (HANDLE)Thread->ThreadsProcess->Session;
 }
@@ -512,7 +741,7 @@ PsGetThreadSessionId(PETHREAD Thread)
  */
 PTEB
 NTAPI
-PsGetThreadTeb(PETHREAD Thread)
+PsGetThreadTeb(IN PETHREAD Thread)
 {
     return Thread->Tcb.Teb;
 }
@@ -522,7 +751,7 @@ PsGetThreadTeb(PETHREAD Thread)
  */
 PVOID
 NTAPI
-PsGetThreadWin32Thread(PETHREAD Thread)
+PsGetThreadWin32Thread(IN PETHREAD Thread)
 {
     return Thread->Tcb.Win32Thread;
 }
@@ -564,7 +793,7 @@ BOOLEAN
 NTAPI
 PsIsThreadTerminating(IN PETHREAD Thread)
 {
-    return (Thread->Terminated ? TRUE : FALSE);
+    return Thread->Terminated ? TRUE : FALSE;
 }
 
 /*
@@ -572,9 +801,9 @@ PsIsThreadTerminating(IN PETHREAD Thread)
  */
 BOOLEAN
 NTAPI
-PsIsSystemThread(PETHREAD Thread)
+PsIsSystemThread(IN PETHREAD Thread)
 {
-    return (Thread->SystemThread ? TRUE: FALSE);
+    return Thread->SystemThread ? TRUE: FALSE;
 }
 
 /*
@@ -582,9 +811,9 @@ PsIsSystemThread(PETHREAD Thread)
  */
 BOOLEAN
 NTAPI
-PsIsThreadImpersonating(PETHREAD Thread)
+PsIsThreadImpersonating(IN PETHREAD Thread)
 {
-    return Thread->ActiveImpersonationInfo;
+    return Thread->ActiveImpersonationInfo ? TRUE : FALSE;
 }
 
 /*
@@ -592,19 +821,29 @@ PsIsThreadImpersonating(PETHREAD Thread)
  */
 VOID
 NTAPI
-PsSetThreadHardErrorsAreDisabled(PETHREAD Thread,
-                                 BOOLEAN HardErrorsAreDisabled)
+PsSetThreadHardErrorsAreDisabled(IN PETHREAD Thread,
+                                 IN BOOLEAN HardErrorsAreDisabled)
 {
     Thread->HardErrorsAreDisabled = HardErrorsAreDisabled;
 }
 
+/*
+ * @implemented
+ */
+PVOID
+NTAPI
+PsGetCurrentThreadWin32Thread(VOID)
+{
+    return PsGetCurrentThread()->Tcb.Win32Thread;
+}
+
 /*
  * @implemented
  */
 VOID
 NTAPI
-PsSetThreadWin32Thread(PETHREAD Thread,
-                       PVOID Win32Thread)
+PsSetThreadWin32Thread(IN PETHREAD Thread,
+                       IN PVOID Win32Thread)
 {
     Thread->Tcb.Win32Thread = Win32Thread;
 }
@@ -613,7 +852,7 @@ NTSTATUS
 NTAPI
 NtCreateThread(OUT PHANDLE ThreadHandle,
                IN ACCESS_MASK DesiredAccess,
-               IN POBJECT_ATTRIBUTES ObjectAttributes  OPTIONAL,
+               IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
                IN HANDLE ProcessHandle,
                OUT PCLIENT_ID ClientId,
                IN PCONTEXT ThreadContext,
@@ -621,27 +860,24 @@ NtCreateThread(OUT PHANDLE ThreadHandle,
                IN BOOLEAN CreateSuspended)
 {
     INITIAL_TEB SafeInitialTeb;
-    NTSTATUS Status = STATUS_SUCCESS;
     PAGED_CODE();
+    PSTRACE(PS_THREAD_DEBUG,
+            "ProcessHandle: %p Context: %p\n", ProcessHandle, ThreadContext);
 
     /* Check if this was from user-mode */
-    if(KeGetPreviousMode() != KernelMode)
+    if (KeGetPreviousMode() != KernelMode)
     {
         /* Make sure that we got a context */
-        if (!ThreadContext)
-        {
-            DPRINT1("No context for User-Mode Thread!!\n");
-            return STATUS_INVALID_PARAMETER;
-        }
+        if (!ThreadContext) return STATUS_INVALID_PARAMETER;
 
         /* Protect checks */
-        _SEH_TRY
+        _SEH2_TRY
         {
             /* Make sure the handle pointer we got is valid */
             ProbeForWriteHandle(ThreadHandle);
 
             /* Check if the caller wants a client id */
-            if(ClientId)
+            if (ClientId)
             {
                 /* Make sure we can write to it */
                 ProbeForWrite(ClientId, sizeof(CLIENT_ID), sizeof(ULONG));
@@ -653,15 +889,13 @@ NtCreateThread(OUT PHANDLE ThreadHandle,
             /* Check the Initial TEB */
             ProbeForRead(InitialTeb, sizeof(INITIAL_TEB), sizeof(ULONG));
             SafeInitialTeb = *InitialTeb;
-            }
-        _SEH_HANDLE
+        }
+        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
         {
-            Status = _SEH_GetExceptionCode();
+            /* Return the exception code */
+            _SEH2_YIELD(return _SEH2_GetExceptionCode());
         }
-        _SEH_END;
-
-        /* Handle any failures in our SEH checks */
-        if (!NT_SUCCESS(Status)) return Status;
+        _SEH2_END;
     }
     else
     {
@@ -691,63 +925,91 @@ NTAPI
 NtOpenThread(OUT PHANDLE ThreadHandle,
              IN ACCESS_MASK DesiredAccess,
              IN POBJECT_ATTRIBUTES ObjectAttributes,
-             IN PCLIENT_ID ClientId  OPTIONAL)
+             IN PCLIENT_ID ClientId OPTIONAL)
 {
-    KPROCESSOR_MODE PreviousMode;
+    KPROCESSOR_MODE PreviousMode = KeGetPreviousMode();
     CLIENT_ID SafeClientId;
     ULONG Attributes = 0;
     HANDLE hThread = NULL;
-    NTSTATUS Status = STATUS_SUCCESS;
+    NTSTATUS Status;
     PETHREAD Thread;
     BOOLEAN HasObjectName = FALSE;
-
+    ACCESS_STATE AccessState;
+    AUX_ACCESS_DATA AuxData;
     PAGED_CODE();
+    PSTRACE(PS_THREAD_DEBUG,
+            "ClientId: %p ObjectAttributes: %p\n", ClientId, ObjectAttributes);
 
-    PreviousMode = KeGetPreviousMode();
-
-    /* Probe the paraemeters */
-    if(PreviousMode != KernelMode)
+    /* Check if we were called from user mode */
+    if (PreviousMode != KernelMode)
     {
-        _SEH_TRY
+        /* Enter SEH for probing */
+        _SEH2_TRY
         {
+            /* Probe the thread handle */
             ProbeForWriteHandle(ThreadHandle);
 
-            if(ClientId != NULL)
+            /* Check for a CID structure */
+            if (ClientId)
             {
-                ProbeForRead(ClientId,
-                             sizeof(CLIENT_ID),
-                             sizeof(ULONG));
-
+                /* Probe and capture it */
+                ProbeForRead(ClientId, sizeof(CLIENT_ID), sizeof(ULONG));
                 SafeClientId = *ClientId;
                 ClientId = &SafeClientId;
             }
 
-            /* just probe the object attributes structure, don't capture it
-               completely. This is done later if necessary */
+            /*
+             * Just probe the object attributes structure, don't capture it
+             * completely. This is done later if necessary
+             */
             ProbeForRead(ObjectAttributes,
                          sizeof(OBJECT_ATTRIBUTES),
                          sizeof(ULONG));
             HasObjectName = (ObjectAttributes->ObjectName != NULL);
             Attributes = ObjectAttributes->Attributes;
         }
-        _SEH_HANDLE
+        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
         {
-            Status = _SEH_GetExceptionCode();
+            /* Return the exception code */
+            _SEH2_YIELD(return _SEH2_GetExceptionCode());
         }
-        _SEH_END;
-
-        if(!NT_SUCCESS(Status)) return Status;
+        _SEH2_END;
     }
     else
     {
+        /* Otherwise just get the data directly */
         HasObjectName = (ObjectAttributes->ObjectName != NULL);
         Attributes = ObjectAttributes->Attributes;
     }
-    
-    if (HasObjectName && ClientId != NULL)
+
+    /* Can't pass both, fail */
+    if ((HasObjectName) && (ClientId)) return STATUS_INVALID_PARAMETER_MIX;
+
+    /* Create an access state */
+    Status = SeCreateAccessState(&AccessState,
+                                 &AuxData,
+                                 DesiredAccess,
+                                 &PsProcessType->TypeInfo.GenericMapping);
+    if (!NT_SUCCESS(Status)) return Status;
+
+    /* Check if this is a debugger */
+    if (SeSinglePrivilegeCheck(SeDebugPrivilege, PreviousMode))
     {
-        /* can't pass both, n object name and a client id */
-        return STATUS_INVALID_PARAMETER_MIX;
+        /* Did he want full access? */
+        if (AccessState.RemainingDesiredAccess & MAXIMUM_ALLOWED)
+        {
+            /* Give it to him */
+            AccessState.PreviouslyGrantedAccess |= THREAD_ALL_ACCESS;
+        }
+        else
+        {
+            /* Otherwise just give every other access he could want */
+            AccessState.PreviouslyGrantedAccess |=
+                AccessState.RemainingDesiredAccess;
+        }
+
+        /* The caller desires nothing else now */
+        AccessState.RemainingDesiredAccess = 0;
     }
 
     /* Open by name if one was given */
@@ -757,101 +1019,74 @@ NtOpenThread(OUT PHANDLE ThreadHandle,
         Status = ObOpenObjectByName(ObjectAttributes,
                                     PsThreadType,
                                     PreviousMode,
-                                    NULL,
-                                    DesiredAccess,
+                                    &AccessState,
+                                    0,
                                     NULL,
                                     &hThread);
-        if (!NT_SUCCESS(Status)) DPRINT1("Could not open object by name\n");
-        }
-    else if (ClientId != NULL)
+
+        /* Get rid of the access state */
+        SeDeleteAccessState(&AccessState);
+    }
+    else if (ClientId)
     {
         /* Open by Thread ID */
         if (ClientId->UniqueProcess)
         {
             /* Get the Process */
-            Status = PsLookupProcessThreadByCid(ClientId,
-                                                NULL,
-                                                &Thread);
+            Status = PsLookupProcessThreadByCid(ClientId, NULL, &Thread);
         }
         else
         {
             /* Get the Process */
-            Status = PsLookupThreadByThreadId(ClientId->UniqueThread,
-                                              &Thread);
+            Status = PsLookupThreadByThreadId(ClientId->UniqueThread, &Thread);
         }
 
-        if(!NT_SUCCESS(Status))
+        /* Check if we didn't find anything */
+        if (!NT_SUCCESS(Status))
         {
-            DPRINT1("Failure to find Thread\n");
+            /* Get rid of the access state and return */
+            SeDeleteAccessState(&AccessState);
             return Status;
         }
 
         /* Open the Thread Object */
         Status = ObOpenObjectByPointer(Thread,
                                        Attributes,
-                                       NULL,
-                                       DesiredAccess,
+                                       &AccessState,
+                                       0,
                                        PsThreadType,
                                        PreviousMode,
                                        &hThread);
-        if(!NT_SUCCESS(Status))
-        {
-            DPRINT1("Failure to open Thread\n");
-        }
 
-        /* Dereference the thread */
+        /* Delete the access state and dereference the thread */
+        SeDeleteAccessState(&AccessState);
         ObDereferenceObject(Thread);
     }
     else
     {
-        /* neither an object name nor a client id was passed */
+        /* Neither an object name nor a client id was passed */
         return STATUS_INVALID_PARAMETER_MIX;
     }
 
     /* Check for success */
-    if(NT_SUCCESS(Status))
+    if (NT_SUCCESS(Status))
     {
         /* Protect against bad user-mode pointers */
-        _SEH_TRY
+        _SEH2_TRY
         {
             /* Write back the handle */
             *ThreadHandle = hThread;
         }
-        _SEH_HANDLE
+        _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
         {
-            Status = _SEH_GetExceptionCode();
+            /* Get the exception code */
+            Status = _SEH2_GetExceptionCode();
         }
-        _SEH_END;
+        _SEH2_END;
     }
 
     /* Return status */
     return Status;
 }
 
-NTSTATUS
-NTAPI
-NtYieldExecution(VOID)
-{
-    KiDispatchThread(Ready);
-    return(STATUS_SUCCESS);
-}
-
-NTSTATUS
-NTAPI
-NtTestAlert(VOID)
-{
-    /* Check and Alert Thread if needed */
-    return KeTestAlertThread(ExGetPreviousMode()) ? STATUS_ALERTED : STATUS_SUCCESS;
-}
-
-/*
- * @implemented
- */
-KPROCESSOR_MODE
-NTAPI
-ExGetPreviousMode (VOID)
-{
-    return (KPROCESSOR_MODE)PsGetCurrentThread()->Tcb.PreviousMode;
-}
-
 /* EOF */