[WIN32K:NTUSER]
[reactos.git] / reactos / win32ss / user / ntuser / msgqueue.c
index d311307..bba976a 100644 (file)
@@ -14,10 +14,13 @@ DBG_DEFAULT_CHANNEL(UserMsgQ);
 /* GLOBALS *******************************************************************/
 
 static PPAGED_LOOKASIDE_LIST pgMessageLookasideList;
+static PPAGED_LOOKASIDE_LIST pgSendMsgLookasideList;
+INT PostMsgCount = 0;
+INT SendMsgCount = 0;
 PUSER_MESSAGE_QUEUE gpqCursor;
 ULONG_PTR gdwMouseMoveExtraInfo = 0;
 DWORD gdwMouseMoveTimeStamp = 0;
-
+LIST_ENTRY usmList;
 
 /* FUNCTIONS *****************************************************************/
 
@@ -26,6 +29,7 @@ NTSTATUS
 NTAPI
 MsqInitializeImpl(VOID)
 {
+   // Setup Post Messages
    pgMessageLookasideList = ExAllocatePoolWithTag(NonPagedPool, sizeof(PAGED_LOOKASIDE_LIST), TAG_USRMSG);
    if (!pgMessageLookasideList)
       return STATUS_NO_MEMORY;
@@ -36,6 +40,19 @@ MsqInitializeImpl(VOID)
                                   sizeof(USER_MESSAGE),
                                   TAG_USRMSG,
                                   256);
+   // Setup Send Messages
+   pgSendMsgLookasideList = ExAllocatePoolWithTag(NonPagedPool, sizeof(PAGED_LOOKASIDE_LIST), TAG_USRMSG);
+   if (!pgSendMsgLookasideList)
+      return STATUS_NO_MEMORY;
+   ExInitializePagedLookasideList(pgSendMsgLookasideList,
+                                  NULL,
+                                  NULL,
+                                  0,
+                                  sizeof(USER_SENT_MESSAGE),
+                                  TAG_USRMSG,
+                                  16);
+
+   InitializeListHead(&usmList);
 
    return(STATUS_SUCCESS);
 }
@@ -62,7 +79,7 @@ IntTopLevelWindowFromPoint(INT x, INT y)
         }
 
         if ((pWnd->style & WS_VISIBLE) &&
-            (pWnd->ExStyle & (WS_EX_LAYERED|WS_EX_TRANSPARENT)) == 0 &&
+            (pWnd->ExStyle & (WS_EX_LAYERED|WS_EX_TRANSPARENT)) != (WS_EX_LAYERED|WS_EX_TRANSPARENT) &&
             IntPtInWindow(pWnd, x, y))
             return pWnd;
     }
@@ -639,7 +656,13 @@ co_MsqInsertMouseMessage(MSG* Msg, DWORD flags, ULONG_PTR dwExtraInfo, BOOL Hook
           return;
        }
 
-       MessageQueue->ptiMouse = pti;
+       // Check to see if this is attached.
+       if ( pti != MessageQueue->ptiMouse &&
+            MessageQueue->cThreads > 1 )
+       {
+          // Set the send pti to the message queue mouse pti.
+          pti = MessageQueue->ptiMouse;
+       }
 
        if (Msg->message == WM_MOUSEMOVE)
        {
@@ -721,20 +744,133 @@ MsqCreateMessage(LPMSG Msg)
 
    RtlZeroMemory(Message, sizeof(*Message));
    RtlMoveMemory(&Message->Msg, Msg, sizeof(MSG));
-
+   PostMsgCount++;
    return Message;
 }
 
 VOID FASTCALL
 MsqDestroyMessage(PUSER_MESSAGE Message)
 {
+   TRACE("Post Destroy %d\n",PostMsgCount)
    if (Message->pti == NULL)
    {
       ERR("Double Free Message\n");
       return;
    }
+   RemoveEntryList(&Message->ListEntry);
    Message->pti = NULL;
    ExFreeToPagedLookasideList(pgMessageLookasideList, Message);
+   PostMsgCount--;
+}
+
+PUSER_SENT_MESSAGE FASTCALL
+AllocateUserMessage(BOOL KEvent)
+{
+   PUSER_SENT_MESSAGE Message;
+
+   if(!(Message = ExAllocateFromPagedLookasideList(pgSendMsgLookasideList)))
+   {
+       ERR("AllocateUserMessage(): Not enough memory to allocate a message");
+       return NULL;
+   }
+   RtlZeroMemory(Message, sizeof(USER_SENT_MESSAGE));
+
+   if (KEvent)
+   {
+      Message->pkCompletionEvent = &Message->CompletionEvent;
+
+      KeInitializeEvent(Message->pkCompletionEvent, NotificationEvent, FALSE);
+   }
+   SendMsgCount++;
+   TRACE("AUM pti %p msg %p\n",PsGetCurrentThreadWin32Thread(),Message);
+   return Message;
+}
+
+VOID FASTCALL
+FreeUserMessage(PUSER_SENT_MESSAGE Message)
+{
+   Message->pkCompletionEvent = NULL;
+
+   /* Remove it from the list */
+   RemoveEntryList(&Message->ListEntry);
+
+   ExFreeToPagedLookasideList(pgSendMsgLookasideList, Message);
+   SendMsgCount--;
+}
+
+VOID APIENTRY
+MsqRemoveWindowMessagesFromQueue(PWND Window)
+{
+   PTHREADINFO pti;
+   PUSER_SENT_MESSAGE SentMessage;
+   PUSER_MESSAGE PostedMessage;
+   PLIST_ENTRY CurrentEntry, ListHead;
+
+   ASSERT(Window);
+
+   pti = Window->head.pti;
+
+   /* remove the posted messages for this window */
+   CurrentEntry = pti->PostedMessagesListHead.Flink;
+   ListHead = &pti->PostedMessagesListHead;
+   while (CurrentEntry != ListHead)
+   {
+      PostedMessage = CONTAINING_RECORD(CurrentEntry, USER_MESSAGE, ListEntry);
+
+      if (PostedMessage->Msg.hwnd == Window->head.h)
+      {
+         if (PostedMessage->Msg.message == WM_QUIT && pti->QuitPosted == 0)
+         {
+            pti->QuitPosted = 1;
+            pti->exitCode = PostedMessage->Msg.wParam;
+         }
+         ClearMsgBitsMask(pti, PostedMessage->QS_Flags);
+         MsqDestroyMessage(PostedMessage);
+         CurrentEntry = pti->PostedMessagesListHead.Flink;
+      }
+      else
+      {
+         CurrentEntry = CurrentEntry->Flink;
+      }
+   }
+
+   /* remove the sent messages for this window */
+   CurrentEntry = pti->SentMessagesListHead.Flink;
+   ListHead = &pti->SentMessagesListHead;
+   while (CurrentEntry != ListHead)
+   {
+      SentMessage = CONTAINING_RECORD(CurrentEntry, USER_SENT_MESSAGE, ListEntry);
+
+      if(SentMessage->Msg.hwnd == Window->head.h)
+      {
+         ERR("Remove Window Messages %p From Sent Queue\n",SentMessage);
+#if 0 // Should mark these as invalid and allow the rest clean up, so far no harm by just commenting out. See CORE-9210.
+         ClearMsgBitsMask(pti, SentMessage->QS_Flags);
+
+         /* wake the sender's thread */
+         if (SentMessage->pkCompletionEvent != NULL)
+         {
+            KeSetEvent(SentMessage->pkCompletionEvent, IO_NO_INCREMENT, FALSE);
+         }
+
+         if (SentMessage->HasPackedLParam)
+         {
+            if (SentMessage->Msg.lParam)
+               ExFreePool((PVOID)SentMessage->Msg.lParam);
+         }
+
+         /* free the message */
+         FreeUserMessage(SentMessage);
+
+         CurrentEntry = pti->SentMessagesListHead.Flink;
+#endif
+         CurrentEntry = CurrentEntry->Flink;
+      }
+      else
+      {
+         CurrentEntry = CurrentEntry->Flink;
+      }
+   }
 }
 
 BOOLEAN FASTCALL
@@ -757,6 +893,9 @@ co_MsqDispatchOneSentMessage(
    Entry = RemoveHeadList(&pti->SentMessagesListHead);
    Message = CONTAINING_RECORD(Entry, USER_SENT_MESSAGE, ListEntry);
 
+   // Signal this message is being processed.
+   Message->flags |= SMF_RECEIVERBUSY|SMF_RECEIVEDMESSAGE;
+
    SaveMsg = pti->pusmCurrent;
    pti->pusmCurrent = Message;
 
@@ -767,15 +906,14 @@ co_MsqDispatchOneSentMessage(
       pti->pcti->CTI_flags |= CTI_INSENDMESSAGE; // Let the user know...
    }
 
-   /* insert it to the list of messages that are currently dispatched by this
-      message queue */
-   InsertTailList(&pti->LocalDispatchingMessagesHead, &Message->ListEntry);
+   /* Now insert it to the global list of messages that can be removed Justin Case there's Trouble */
+   InsertTailList(&usmList, &Message->ListEntry);
 
    ClearMsgBitsMask(pti, Message->QS_Flags);
 
    if (Message->HookMessage == MSQ_ISHOOK)
    {  // Direct Hook Call processor
-      Result = co_CallHook( Message->Msg.message,     // HookId
+      Result = co_CallHook( Message->Msg.message,           // HookId
                            (INT)(INT_PTR)Message->Msg.hwnd, // Code
                             Message->Msg.wParam,
                             Message->Msg.lParam);
@@ -804,7 +942,9 @@ co_MsqDispatchOneSentMessage(
          /* The message has not been processed yet, reinsert it. */
          RemoveEntryList(&Message->ListEntry);
          InsertTailList(&Message->ptiCallBackSender->SentMessagesListHead, &Message->ListEntry);
-         TRACE("Callback Message not processed yet. Requeuing the message\n");
+         // List is occupied need to set the bit.
+         MsqWakeQueue(Message->ptiCallBackSender, QS_SENDMESSAGE, TRUE);
+         ERR("Callback Message not processed yet. Requeuing the message\n"); //// <---- Need to see if this happens.
          Ret = FALSE;
          goto Exit;
       }
@@ -817,10 +957,6 @@ co_MsqDispatchOneSentMessage(
                                   Message->Msg.lParam);
    }
 
-   /* remove the message from the local dispatching list, because it doesn't need
-      to be cleaned up on thread termination anymore */
-   RemoveEntryList(&Message->ListEntry);
-
    /* If the message is a callback, insert it in the callback senders MessageQueue */
    if (Message->CompletionCallback)
    {
@@ -830,6 +966,7 @@ co_MsqDispatchOneSentMessage(
          Message->QS_Flags |= QS_SMRESULT;
 
          /* insert it in the callers message queue */
+         RemoveEntryList(&Message->ListEntry);
          InsertTailList(&Message->ptiCallBackSender->SentMessagesListHead, &Message->ListEntry);
          MsqWakeQueue(Message->ptiCallBackSender, QS_SENDMESSAGE, TRUE);
       }
@@ -837,28 +974,14 @@ co_MsqDispatchOneSentMessage(
       goto Exit;
    }
 
-   /* remove the message from the dispatching list if needed, so lock the sender's message queue */
-   if (Message->ptiSender && !(Message->ptiSender->TIF_flags & TIF_INCLEANUP))
-   {
-      if (Message->DispatchingListEntry.Flink != NULL)
-      {
-         /* only remove it from the dispatching list if not already removed by a timeout */
-         RemoveEntryList(&Message->DispatchingListEntry);
-      }
-   }
-   /* still keep the sender's message queue locked, so the sender can't exit the
-      MsqSendMessage() function (if timed out) */
-
+   // Retrieve the result from callback.
    if (Message->QS_Flags & QS_SMRESULT)
    {
       Result = Message->lResult;
    }
 
    /* Let the sender know the result. */
-   if (Message->Result != NULL)
-   {
-      *Message->Result = Result;
-   }
+   Message->lResult = Result;
 
    if (Message->HasPackedLParam)
    {
@@ -866,14 +989,22 @@ co_MsqDispatchOneSentMessage(
          ExFreePool((PVOID)Message->Msg.lParam);
    }
 
+   // Clear busy signal.
+   Message->flags &= ~SMF_RECEIVERBUSY;
+
    /* Notify the sender. */
-   if (Message->CompletionEvent != NULL)
+   if (Message->pkCompletionEvent != NULL)
    {
-      KeSetEvent(Message->CompletionEvent, IO_NO_INCREMENT, FALSE);
+      KeSetEvent(Message->pkCompletionEvent, IO_NO_INCREMENT, FALSE);
    }
 
    /* free the message */
-   ExFreePoolWithTag(Message, TAG_USRMSG);
+   if (Message->flags & SMF_RECEIVERFREE)
+   {
+      TRACE("Receiver Freeing Message %p\n",Message);
+      FreeUserMessage(Message);
+   }
+
    Ret = TRUE;
 Exit:
    /* do not hangup on the user if this is reentering */
@@ -883,88 +1014,6 @@ Exit:
    return Ret;
 }
 
-VOID APIENTRY
-MsqRemoveWindowMessagesFromQueue(PWND Window)
-{
-   PTHREADINFO pti;
-   PUSER_SENT_MESSAGE SentMessage;
-   PUSER_MESSAGE PostedMessage;
-   PLIST_ENTRY CurrentEntry, ListHead;
-
-   ASSERT(Window);
-
-   pti = Window->head.pti;
-
-   /* remove the posted messages for this window */
-   CurrentEntry = pti->PostedMessagesListHead.Flink;
-   ListHead = &pti->PostedMessagesListHead;
-   while (CurrentEntry != ListHead)
-   {
-      PostedMessage = CONTAINING_RECORD(CurrentEntry, USER_MESSAGE,
-                                        ListEntry);
-      if (PostedMessage->Msg.hwnd == Window->head.h)
-      {
-         if (PostedMessage->Msg.message == WM_QUIT && pti->QuitPosted == 0)
-         {
-            pti->QuitPosted = 1;
-            pti->exitCode = PostedMessage->Msg.wParam;
-         }
-         RemoveEntryList(&PostedMessage->ListEntry);
-         ClearMsgBitsMask(pti, PostedMessage->QS_Flags);
-         MsqDestroyMessage(PostedMessage);
-         CurrentEntry = pti->PostedMessagesListHead.Flink;
-      }
-      else
-      {
-         CurrentEntry = CurrentEntry->Flink;
-      }
-   }
-
-   /* remove the sent messages for this window */
-   CurrentEntry = pti->SentMessagesListHead.Flink;
-   ListHead = &pti->SentMessagesListHead;
-   while (CurrentEntry != ListHead)
-   {
-      SentMessage = CONTAINING_RECORD(CurrentEntry, USER_SENT_MESSAGE, ListEntry);
-
-      if(SentMessage->Msg.hwnd == Window->head.h)
-      {
-         TRACE("Notify the sender and remove a message from the queue that had not been dispatched\n");
-
-         RemoveEntryList(&SentMessage->ListEntry);
-         ClearMsgBitsMask(pti, SentMessage->QS_Flags);
-
-         /* Only if the message has a sender was the queue referenced */
-         if ((SentMessage->ptiSender)
-            && (SentMessage->DispatchingListEntry.Flink != NULL))
-         {
-            RemoveEntryList(&SentMessage->DispatchingListEntry);
-         }
-
-         /* wake the sender's thread */
-         if (SentMessage->CompletionEvent != NULL)
-         {
-            KeSetEvent(SentMessage->CompletionEvent, IO_NO_INCREMENT, FALSE);
-         }
-
-         if (SentMessage->HasPackedLParam)
-         {
-            if (SentMessage->Msg.lParam)
-               ExFreePool((PVOID)SentMessage->Msg.lParam);
-         }
-
-         /* free the message */
-         ExFreePoolWithTag(SentMessage, TAG_USRMSG);
-
-         CurrentEntry = pti->SentMessagesListHead.Flink;
-      }
-      else
-      {
-         CurrentEntry = CurrentEntry->Flink;
-      }
-   }
-}
-
 BOOL FASTCALL
 co_MsqSendMessageAsync(PTHREADINFO ptiReceiver,
                        HWND hwnd,
@@ -980,9 +1029,9 @@ co_MsqSendMessageAsync(PTHREADINFO ptiReceiver,
     PTHREADINFO ptiSender;
     PUSER_SENT_MESSAGE Message;
 
-    if(!(Message = ExAllocatePoolWithTag(NonPagedPool, sizeof(USER_SENT_MESSAGE), TAG_USRMSG)))
+    if(!(Message = AllocateUserMessage(FALSE)))
     {
-        ERR("MsqSendMessage(): Not enough memory to allocate a message");
+        ERR("MsqSendMessageAsync(): Not enough memory to allocate a message");
         return FALSE;
     }
 
@@ -992,18 +1041,15 @@ co_MsqSendMessageAsync(PTHREADINFO ptiReceiver,
     Message->Msg.message = Msg;
     Message->Msg.wParam = wParam;
     Message->Msg.lParam = lParam;
-    Message->CompletionEvent = NULL;
-    Message->Result = 0;
-    Message->lResult = 0;
+    Message->pkCompletionEvent = NULL; // No event needed.
     Message->ptiReceiver = ptiReceiver;
-    Message->ptiSender = NULL;
     Message->ptiCallBackSender = ptiSender;
-    Message->DispatchingListEntry.Flink = NULL;
     Message->CompletionCallback = CompletionCallback;
     Message->CompletionCallbackContext = CompletionCallbackContext;
     Message->HookMessage = HookMessage;
     Message->HasPackedLParam = HasPackedLParam;
     Message->QS_Flags = QS_SENDMESSAGE;
+    Message->flags = SMF_RECEIVERFREE;
 
     InsertTailList(&ptiReceiver->SentMessagesListHead, &Message->ListEntry);
     MsqWakeQueue(ptiReceiver, QS_SENDMESSAGE, TRUE);
@@ -1023,12 +1069,12 @@ co_MsqSendMessage(PTHREADINFO ptirec,
                   ULONG_PTR *uResult)
 {
    PTHREADINFO pti;
-   PUSER_SENT_MESSAGE Message;
-   KEVENT CompletionEvent;
+   PUSER_SENT_MESSAGE SaveMsg, Message;
    NTSTATUS WaitStatus;
    LARGE_INTEGER Timeout;
    PLIST_ENTRY Entry;
    PWND pWnd;
+   BOOLEAN SwapStateEnabled;
    LRESULT Result = 0;   //// Result could be trashed. ////
 
    pti = PsGetCurrentThreadWin32Thread();
@@ -1050,6 +1096,13 @@ co_MsqSendMessage(PTHREADINFO ptirec,
        return STATUS_UNSUCCESSFUL;
    }
 
+   if (IsThreadSuspended(ptirec))
+   {
+      ERR("Sending to Suspended Thread Msg %lx\n",Msg);
+      if (uResult) *uResult = -1;
+      return STATUS_UNSUCCESSFUL;
+   }
+
    // Should we do the same for No Wait?
    if ( HookMessage == MSQ_NORMAL )
    {
@@ -1090,57 +1143,57 @@ co_MsqSendMessage(PTHREADINFO ptirec,
       }
    }
 
-   if(!(Message = ExAllocatePoolWithTag(PagedPool, sizeof(USER_SENT_MESSAGE), TAG_USRMSG)))
+   if(!(Message = AllocateUserMessage(TRUE)))
    {
       ERR("MsqSendMessage(): Not enough memory to allocate a message\n");
+      if (uResult) *uResult = -1;
       return STATUS_INSUFFICIENT_RESOURCES;
    }
 
-   KeInitializeEvent(&CompletionEvent, NotificationEvent, FALSE);
-
    Timeout.QuadPart = Int32x32To64(-10000,uTimeout); // Pass SMTO test with a TO of 0x80000000.
    TRACE("Timeout val %lld\n",Timeout.QuadPart)
 
-   /* FIXME: Increase reference counter of sender's message queue here */
-
    Message->Msg.hwnd = Wnd;
    Message->Msg.message = Msg;
    Message->Msg.wParam = wParam;
    Message->Msg.lParam = lParam;
-   Message->CompletionEvent = &CompletionEvent;
-   Message->Result = &Result;
-   Message->lResult = 0;
-   Message->QS_Flags = 0;
    Message->ptiReceiver = ptirec;
    Message->ptiSender = pti;
-   Message->ptiCallBackSender = NULL;
-   Message->CompletionCallback = NULL;
-   Message->CompletionCallbackContext = 0;
    Message->HookMessage = HookMessage;
-   Message->HasPackedLParam = FALSE;
+   Message->QS_Flags = QS_SENDMESSAGE;
 
-   /* Add it to the list of pending messages */
-   InsertTailList(&pti->DispatchingMessagesHead, &Message->DispatchingListEntry);
+   SaveMsg = pti->pusmSent;
+   pti->pusmSent = Message;
 
    /* Queue it in the destination's message queue */
    InsertTailList(&ptirec->SentMessagesListHead, &Message->ListEntry);
 
-   Message->QS_Flags = QS_SENDMESSAGE;
    MsqWakeQueue(ptirec, QS_SENDMESSAGE, TRUE);
 
-   /* We can't access the Message anymore since it could have already been deleted! */
+   // First time in, turn off swapping of the stack.
+   if (pti->cEnterCount == 0)
+   {
+      SwapStateEnabled = KeSetKernelStackSwapEnable(FALSE);
+   }
+   pti->cEnterCount++;
 
    if (Block)
    {
       PVOID WaitObjects[2];
 
-      WaitObjects[0] = &CompletionEvent;       // Wait 0
-      WaitObjects[1] = ptirec->pEThread;       // Wait 1
+      WaitObjects[0] = Message->pkCompletionEvent; // Wait 0
+      WaitObjects[1] = ptirec->pEThread;           // Wait 1
 
       UserLeaveCo();
 
-      WaitStatus = KeWaitForMultipleObjects(2, WaitObjects, WaitAny, UserRequest,
-                                            UserMode, FALSE, (uTimeout ? &Timeout : NULL), NULL);
+      WaitStatus = KeWaitForMultipleObjects( 2,
+                                             WaitObjects,
+                                             WaitAny,
+                                             UserRequest,
+                                             UserMode,
+                                             FALSE,
+                                            (uTimeout ? &Timeout : NULL),
+                                             NULL );
 
       UserEnterCo();
 
@@ -1153,39 +1206,24 @@ co_MsqSendMessage(PTHREADINFO ptirec,
          {
             if (CONTAINING_RECORD(Entry, USER_SENT_MESSAGE, ListEntry) == Message)
             {
-               /* We can access Message here, it's secure because the message queue is locked
-                  and the message is still hasn't been dispatched */
-               Message->CompletionEvent = NULL;
-               Message->Result = NULL;
+               Message->pkCompletionEvent = NULL;
                RemoveEntryList(&Message->ListEntry);
-               RemoveEntryList(&Message->DispatchingListEntry);
                ClearMsgBitsMask(ptirec, Message->QS_Flags);
-               ExFreePoolWithTag(Message, TAG_USRMSG);
+               InsertTailList(&usmList, &Message->ListEntry);
                break;
             }
             Entry = Entry->Flink;
          }
 
-         TRACE("MsqSendMessage (blocked) timed out 1 Status %lx\n", WaitStatus);
+         ERR("MsqSendMessage (blocked) timed out 1 Status %lx\n", WaitStatus);
       }
       // Receiving thread passed on and left us hanging with issues still pending.
       else if (WaitStatus == STATUS_WAIT_1)
       {
          ERR("Bk Receiving Thread woken up dead!\n");
-         Entry = pti->DispatchingMessagesHead.Flink;
-         while (Entry != &pti->DispatchingMessagesHead)
-         {
-            if (CONTAINING_RECORD(Entry, USER_SENT_MESSAGE, DispatchingListEntry) == Message)
-            {
-               Message->CompletionEvent = NULL;
-               Message->Result = NULL;
-               RemoveEntryList(&Message->DispatchingListEntry);
-               Message->DispatchingListEntry.Flink = NULL;
-               break;
-            }
-            Entry = Entry->Flink;
-         }
+         Message->flags |= SMF_RECEIVERDIED;
       }
+
       while (co_MsqDispatchOneSentMessage(pti))
          ;
    }
@@ -1193,16 +1231,22 @@ co_MsqSendMessage(PTHREADINFO ptirec,
    {
       PVOID WaitObjects[3];
 
-      WaitObjects[0] = &CompletionEvent;       // Wait 0
-      WaitObjects[1] = pti->pEventQueueServer; // Wait 1
-      WaitObjects[2] = ptirec->pEThread;       // Wait 2
+      WaitObjects[0] = Message->pkCompletionEvent; // Wait 0
+      WaitObjects[1] = pti->pEventQueueServer;     // Wait 1
+      WaitObjects[2] = ptirec->pEThread;           // Wait 2
 
       do
       {
          UserLeaveCo();
 
-         WaitStatus = KeWaitForMultipleObjects(3, WaitObjects, WaitAny, UserRequest,
-                                               UserMode, FALSE, (uTimeout ? &Timeout : NULL), NULL);
+         WaitStatus = KeWaitForMultipleObjects( 3,
+                                                WaitObjects,
+                                                WaitAny,
+                                                UserRequest,
+                                                UserMode,
+                                                FALSE,
+                                               (uTimeout ? &Timeout : NULL),
+                                                NULL);
 
          UserEnterCo();
 
@@ -1215,40 +1259,24 @@ co_MsqSendMessage(PTHREADINFO ptirec,
             {
                if (CONTAINING_RECORD(Entry, USER_SENT_MESSAGE, ListEntry) == Message)
                {
-                  /* We can access Message here, it's secure because the message queue is locked
-                     and the message is still hasn't been dispatched */
-                  Message->CompletionEvent = NULL;
-                  Message->Result = NULL;
+                  Message->pkCompletionEvent = NULL;
                   RemoveEntryList(&Message->ListEntry);
-                  RemoveEntryList(&Message->DispatchingListEntry);
                   ClearMsgBitsMask(ptirec, Message->QS_Flags);
-                  ExFreePoolWithTag(Message, TAG_USRMSG);
+                  InsertTailList(&usmList, &Message->ListEntry);
                   break;
                }
                Entry = Entry->Flink;
             }
 
-            TRACE("MsqSendMessage timed out 2 Status %lx\n", WaitStatus);
-
+            ERR("MsqSendMessage timed out 2 Status %lx\n", WaitStatus);
             break;
          }
          // Receiving thread passed on and left us hanging with issues still pending.
          else if (WaitStatus == STATUS_WAIT_2)
          {
             ERR("NB Receiving Thread woken up dead!\n");
-            Entry = pti->DispatchingMessagesHead.Flink;
-            while (Entry != &pti->DispatchingMessagesHead)
-            {
-               if (CONTAINING_RECORD(Entry, USER_SENT_MESSAGE, DispatchingListEntry) == Message)
-               {
-                  Message->CompletionEvent = NULL;
-                  Message->Result = NULL;
-                  RemoveEntryList(&Message->DispatchingListEntry);
-                  Message->DispatchingListEntry.Flink = NULL;
-                  break;
-               }
-               Entry = Entry->Flink;
-            }
+            Message->flags |= SMF_RECEIVERDIED;
+            break;
          }
 
          if (WaitStatus == STATUS_USER_APC) break;
@@ -1258,19 +1286,52 @@ co_MsqSendMessage(PTHREADINFO ptirec,
       } while (WaitStatus == STATUS_WAIT_1);
    }
 
+   // Count is nil, restore swapping of the stack.
+   if (--pti->cEnterCount == 0 )
+   {
+      KeSetKernelStackSwapEnable(SwapStateEnabled);
+   }
+
+   // Handle User APC
    if (WaitStatus == STATUS_USER_APC)
    {
      // The current thread is dying!
      TRACE("User APC\n");
+
+     // The Message will be on the Trouble list until Thread cleanup.
+     Message->flags |= SMF_SENDERDIED;
+
      co_IntDeliverUserAPC();
      ERR("User APC Returned\n"); // Should not see this message.
    }
 
+   // Force this thread to wake up for the next go around.
+   KeSetEvent(pti->pEventQueueServer, IO_NO_INCREMENT, FALSE);
+
+   Result = Message->lResult;
+
+   // Determine whether this message is being processed or not.
+   if ((Message->flags & (SMF_RECEIVERBUSY|SMF_RECEIVEDMESSAGE)) != SMF_RECEIVEDMESSAGE)
+   {
+      Message->flags |= SMF_RECEIVERFREE;
+   }
+
+   if (!(Message->flags & SMF_RECEIVERFREE))
+   {
+      TRACE("Sender Freeing Message %p ptirec %p bit %d list empty %d\n",Message,ptirec,!!(ptirec->pcti->fsChangeBits & QS_SENDMESSAGE),IsListEmpty(&ptirec->SentMessagesListHead));
+      // Make it to this point, the message was received.
+      FreeUserMessage(Message);
+   }
+
+   pti->pusmSent = SaveMsg;
+
+   TRACE("MSM Allocation Count %d Status %lx Result %d\n",SendMsgCount,WaitStatus,Result);
+
    if (WaitStatus != STATUS_TIMEOUT)
    {
       if (uResult)
       {
-         *uResult = (STATUS_WAIT_0 == WaitStatus ? Result : -1);
+         *uResult = (STATUS_WAIT_0 == WaitStatus ? Result : 0);
       }
    }
 
@@ -1316,6 +1377,7 @@ MsqPostMessage(PTHREADINFO pti,
    Message->QS_Flags = MessageBits;
    Message->pti = pti;
    MsqWakeQueue(pti, MessageBits, TRUE);
+   TRACE("Post Message %d\n",PostMsgCount);
 }
 
 VOID FASTCALL
@@ -1410,7 +1472,7 @@ IntTrackMouseMove(PWND pwndTrack, PDESKTOP pDesk, PMSG msg, USHORT hittest)
    }
 }
 
-BOOL co_IntProcessMouseMessage(MSG* msg, BOOL* RemoveMessages, UINT first, UINT last)
+BOOL co_IntProcessMouseMessage(MSG* msg, BOOL* RemoveMessages, BOOL* NotForUs, LONG_PTR ExtraInfo, UINT first, UINT last)
 {
     MSG clk_msg;
     POINT pt;
@@ -1451,15 +1513,25 @@ BOOL co_IntProcessMouseMessage(MSG* msg, BOOL* RemoveMessages, UINT first, UINT
     TRACE("Got mouse message for %p, hittest: 0x%x\n", msg->hwnd, hittest);
 
     // Null window or not the same "Hardware" message queue.
-    if (pwndMsg == NULL || pwndMsg->head.pti->MessageQueue != pti->MessageQueue)
+    if (pwndMsg == NULL || pwndMsg->head.pti->MessageQueue != MessageQueue)
     {
         // Crossing a boundary, so set cursor. See default message queue cursor.
-        UserSetCursor(SYSTEMCUR(ARROW), FALSE);
+        IntSystemSetCursor(SYSTEMCUR(ARROW));
         /* Remove and ignore the message */
         *RemoveMessages = TRUE;
         return FALSE;
     }
 
+    // Check to see if this is attached,
+    if ( pwndMsg->head.pti != pti &&  // window thread is not current,
+         MessageQueue->cThreads > 1 ) // and is attached...
+    {
+        // This is not for us and we should leave so the other thread can check for messages!!!
+        *NotForUs = TRUE;
+        *RemoveMessages = TRUE;
+        return FALSE;
+    }
+
     if ( MessageQueue == gpqCursor ) // Cursor must use the same Queue!
     {
        IntTrackMouseMove(pwndMsg, pDesk, msg, hittest);
@@ -1585,6 +1657,12 @@ BOOL co_IntProcessMouseMessage(MSG* msg, BOOL* RemoveMessages, UINT first, UINT
         }
     }
 
+    if (pti->TIF_flags & TIF_MSGPOSCHANGED)
+    {
+        pti->TIF_flags &= ~TIF_MSGPOSCHANGED;
+        IntNotifyWinEvent(EVENT_OBJECT_LOCATIONCHANGE, NULL, OBJID_CLIENT, CHILDID_SELF, 0);
+    }
+
     /* message is accepted now (but still get dropped) */
 
     event.message = msg->message;
@@ -1597,14 +1675,14 @@ BOOL co_IntProcessMouseMessage(MSG* msg, BOOL* RemoveMessages, UINT first, UINT
     hook.pt           = msg->pt;
     hook.hwnd         = msg->hwnd;
     hook.wHitTestCode = hittest;
-    hook.dwExtraInfo  = 0 /* extra_info */ ;
+    hook.dwExtraInfo  = ExtraInfo;
     if (co_HOOK_CallHooks( WH_MOUSE, *RemoveMessages ? HC_ACTION : HC_NOREMOVE,
                         message, (LPARAM)&hook ))
     {
         hook.pt           = msg->pt;
         hook.hwnd         = msg->hwnd;
         hook.wHitTestCode = hittest;
-        hook.dwExtraInfo  = 0 /* extra_info */ ;
+        hook.dwExtraInfo  = ExtraInfo;
         co_HOOK_CallHooks( WH_CBT, HCBT_CLICKSKIPPED, message, (LPARAM)&hook );
 
         ERR("WH_MOUSE dropped mouse message!\n");
@@ -1695,6 +1773,7 @@ BOOL co_IntProcessKeyboardMessage(MSG* Msg, BOOL* RemoveMessages)
     PWND pWnd;
     UINT ImmRet;
     BOOL Ret = TRUE;
+    WPARAM wParam = Msg->wParam;
     PTHREADINFO pti = PsGetCurrentThreadWin32Thread();
 
     if (Msg->message == VK_PACKET)
@@ -1755,6 +1834,90 @@ BOOL co_IntProcessKeyboardMessage(MSG* Msg, BOOL* RemoveMessages)
         }
     }
 
+    //// Key Down!
+    if ( *RemoveMessages && Msg->message == WM_SYSKEYDOWN )
+    {
+        if ( HIWORD(Msg->lParam) & KF_ALTDOWN )
+        {
+            if ( Msg->wParam == VK_ESCAPE || Msg->wParam == VK_TAB ) // Alt-Tab/ESC Alt-Shift-Tab/ESC
+            {
+                WPARAM wParamTmp;
+
+                wParamTmp = UserGetKeyState(VK_SHIFT) & 0x8000 ? SC_PREVWINDOW : SC_NEXTWINDOW;
+                TRACE("Send WM_SYSCOMMAND Alt-Tab/ESC Alt-Shift-Tab/ESC\n");
+                co_IntSendMessage( Msg->hwnd, WM_SYSCOMMAND, wParamTmp, Msg->wParam );
+
+                //// Keep looping.
+                Ret = FALSE;
+                //// Skip the rest.
+                goto Exit;
+            }
+        }
+    }
+
+    if ( *RemoveMessages && (Msg->message == WM_SYSKEYDOWN || Msg->message == WM_KEYDOWN) )
+    {
+        if (gdwLanguageToggleKey < 3)
+        {
+            if (IS_KEY_DOWN(gafAsyncKeyState, gdwLanguageToggleKey == 1 ? VK_LMENU : VK_CONTROL)) // L Alt 1 or Ctrl 2 .
+            {
+                if ( wParam == VK_LSHIFT ) gLanguageToggleKeyState = INPUTLANGCHANGE_FORWARD;  // Left Alt - Left Shift, Next
+                //// FIXME : It seems to always be VK_LSHIFT.
+                if ( wParam == VK_RSHIFT ) gLanguageToggleKeyState = INPUTLANGCHANGE_BACKWARD; // Left Alt - Right Shift, Previous
+            }
+         }
+    }
+
+    //// Key Up!                             Alt Key                        Ctrl Key
+    if ( *RemoveMessages && (Msg->message == WM_SYSKEYUP || Msg->message == WM_KEYUP) )
+    {
+        // When initializing win32k: Reading from the registry hotkey combination
+        // to switch the keyboard layout and store it to global variable.
+        // Using this combination of hotkeys in this function
+
+        if ( gdwLanguageToggleKey < 3 &&
+             IS_KEY_DOWN(gafAsyncKeyState, gdwLanguageToggleKey == 1 ? VK_LMENU : VK_CONTROL) )
+        {
+            if ( Msg->wParam == VK_SHIFT && !(IS_KEY_DOWN(gafAsyncKeyState, VK_SHIFT)))
+            {
+                WPARAM wParamILR;
+                PKL pkl = pti->KeyboardLayout;
+
+                if (pWnd) UserDerefObjectCo(pWnd);
+
+                //// Seems to override message window.
+                if (!(pWnd = pti->MessageQueue->spwndFocus))
+                {
+                     pWnd = pti->MessageQueue->spwndActive;
+                }
+                if (pWnd) UserRefObjectCo(pWnd, &Ref);
+
+                if (pkl != NULL && gLanguageToggleKeyState)
+                {
+                    TRACE("Posting WM_INPUTLANGCHANGEREQUEST KeyState %d\n", gLanguageToggleKeyState );
+
+                    wParamILR = gLanguageToggleKeyState;
+                    // If system character set and font signature send flag.
+                    if ( gSystemFS & pkl->dwFontSigs )
+                    {
+                       wParamILR |= INPUTLANGCHANGE_SYSCHARSET;
+                    }
+
+                    UserPostMessage( UserHMGetHandle(pWnd),
+                                     WM_INPUTLANGCHANGEREQUEST,
+                                     wParamILR,
+                                    (LPARAM)pkl->hkl );
+
+                    gLanguageToggleKeyState = 0;
+                    //// Keep looping.
+                    Ret = FALSE;
+                    //// Skip the rest.
+                    goto Exit;
+                }
+            }
+        }
+    }
+
     if (co_HOOK_CallHooks( WH_KEYBOARD,
                           *RemoveMessages ? HC_ACTION : HC_NOREMOVE,
                            LOWORD(Msg->wParam),
@@ -1787,16 +1950,16 @@ BOOL co_IntProcessKeyboardMessage(MSG* Msg, BOOL* RemoveMessages)
             }
         }
     }
-
+Exit:
     if (pWnd) UserDerefObjectCo(pWnd);
     return Ret;
 }
 
-BOOL co_IntProcessHardwareMessage(MSG* Msg, BOOL* RemoveMessages, UINT first, UINT last)
+BOOL co_IntProcessHardwareMessage(MSG* Msg, BOOL* RemoveMessages, BOOL* NotForUs, LONG_PTR ExtraInfo, UINT first, UINT last)
 {
     if ( IS_MOUSE_MESSAGE(Msg->message))
     {
-        return co_IntProcessMouseMessage(Msg, RemoveMessages, first, last);
+        return co_IntProcessMouseMessage(Msg, RemoveMessages, NotForUs, ExtraInfo, first, last);
     }
     else if ( IS_KBD_MESSAGE(Msg->message))
     {
@@ -1823,6 +1986,16 @@ filter_contains_hw_range( UINT first, UINT last )
     return 1;
 }
 
+/* check whether message is in the range of mouse messages */
+static inline BOOL is_mouse_message( UINT message )
+{
+    return ( //( message >= WM_NCMOUSEFIRST && message <= WM_NCMOUSELAST )   || This seems to break tests...
+             ( message >= WM_MOUSEFIRST   && message <= WM_MOUSELAST )     ||
+             ( message >= WM_XBUTTONDOWN  && message <= WM_XBUTTONDBLCLK ) ||
+             ( message >= WM_MBUTTONDOWN  && message <= WM_MBUTTONDBLCLK ) ||
+             ( message >= WM_LBUTTONDOWN  && message <= WM_RBUTTONDBLCLK ) );
+}
+
 BOOL APIENTRY
 co_MsqPeekHardwareMessage(IN PTHREADINFO pti,
                          IN BOOL Remove,
@@ -1832,12 +2005,13 @@ co_MsqPeekHardwareMessage(IN PTHREADINFO pti,
                          IN UINT QSflags,
                          OUT MSG* pMsg)
 {
-   BOOL AcceptMessage;
+   BOOL AcceptMessage, NotForUs;
    PUSER_MESSAGE CurrentMessage;
    PLIST_ENTRY ListHead;
    MSG msg;
    ULONG_PTR idSave;
    DWORD QS_Flags;
+   LONG_PTR ExtraInfo;
    BOOL Ret = FALSE;
    PUSER_MESSAGE_QUEUE MessageQueue = pti->MessageQueue;
 
@@ -1855,7 +2029,7 @@ co_MsqPeekHardwareMessage(IN PTHREADINFO pti,
 
    if (MessageQueue->ptiSysLock != pti)
    {
-      ERR("MsqPeekHardwareMessage: Thread Q is locked to another pti!\n");
+      ERR("Thread Q is locked to ptiSysLock 0x%p pti 0x%p\n",MessageQueue->ptiSysLock,pti);
       return FALSE;
    }
 
@@ -1878,7 +2052,7 @@ co_MsqPeekHardwareMessage(IN PTHREADINFO pti,
       if ( ( !Window || // 1
             ( Window == PWND_BOTTOM && CurrentMessage->Msg.hwnd == NULL ) || // 2
             ( Window != PWND_BOTTOM && Window->head.h == CurrentMessage->Msg.hwnd ) || // 3
-            ( CurrentMessage->Msg.message == WM_MOUSEMOVE ) ) && // Null window for mouse moves.
+            ( is_mouse_message(CurrentMessage->Msg.message) ) ) && // Null window for anything mouse.
             ( ( ( MsgFilterLow == 0 && MsgFilterHigh == 0 ) && CurrentMessage->QS_Flags & QSflags ) ||
               ( MsgFilterLow <= CurrentMessage->Msg.message && MsgFilterHigh >= CurrentMessage->Msg.message ) ) )
       {
@@ -1886,16 +2060,18 @@ co_MsqPeekHardwareMessage(IN PTHREADINFO pti,
          MessageQueue->idSysPeek = (ULONG_PTR)CurrentMessage;
 
          msg = CurrentMessage->Msg;
+         ExtraInfo = CurrentMessage->ExtraInfo;
          QS_Flags = CurrentMessage->QS_Flags;
 
+         NotForUs = FALSE;
+
          UpdateKeyStateFromMsg(MessageQueue, &msg);
-         AcceptMessage = co_IntProcessHardwareMessage(&msg, &Remove, MsgFilterLow, MsgFilterHigh);
+         AcceptMessage = co_IntProcessHardwareMessage(&msg, &Remove, &NotForUs, ExtraInfo, MsgFilterLow, MsgFilterHigh);
 
          if (Remove)
          {
-             if (CurrentMessage->pti != NULL)
+             if (CurrentMessage->pti != NULL && (MessageQueue->idSysPeek == (ULONG_PTR)CurrentMessage))
              {
-                RemoveEntryList(&CurrentMessage->ListEntry);
                 MsqDestroyMessage(CurrentMessage);
              }
              ClearMsgBitsMask(pti, QS_Flags);
@@ -1903,9 +2079,23 @@ co_MsqPeekHardwareMessage(IN PTHREADINFO pti,
 
          MessageQueue->idSysPeek = idSave;
 
+         if (NotForUs)
+         {
+            Ret = FALSE;
+            break;
+         }
+
          if (AcceptMessage)
          {
             *pMsg = msg;
+            // Fix all but one wine win:test_GetMessagePos WM_TIMER tests. See PostTimerMessages.
+            if (!RtlEqualMemory(&pti->ptLast, &msg.pt, sizeof(POINT)))
+            {
+               pti->TIF_flags |= TIF_MSGPOSCHANGED;
+            }
+            pti->ptLast   = msg.pt;
+            pti->timeLast = msg.time;
+            MessageQueue->ExtraInfo = ExtraInfo;
             Ret = TRUE;
             break;
          }
@@ -1925,6 +2115,7 @@ MsqPeekMessage(IN PTHREADINFO pti,
                   IN UINT MsgFilterHigh,
                   IN UINT QSflags,
                   OUT LONG_PTR *ExtraInfo,
+                  OUT DWORD *dwQEvent,
                   OUT PMSG Message)
 {
    PUSER_MESSAGE CurrentMessage;
@@ -1955,12 +2146,12 @@ MsqPeekMessage(IN PTHREADINFO pti,
          *Message   = CurrentMessage->Msg;
          *ExtraInfo = CurrentMessage->ExtraInfo;
          QS_Flags   = CurrentMessage->QS_Flags;
+         if (dwQEvent) *dwQEvent = CurrentMessage->dwQEvent;
 
          if (Remove)
          {
              if (CurrentMessage->pti != NULL)
              {
-                RemoveEntryList(&CurrentMessage->ListEntry);
                 MsqDestroyMessage(CurrentMessage);
              }
              ClearMsgBitsMask(pti, QS_Flags);
@@ -1977,8 +2168,18 @@ NTSTATUS FASTCALL
 co_MsqWaitForNewMessages(PTHREADINFO pti, PWND WndFilter,
                          UINT MsgFilterMin, UINT MsgFilterMax)
 {
-   NTSTATUS ret;
+   NTSTATUS ret = STATUS_SUCCESS;
+
+   // Post mouse moves before waiting for messages.
+   if (pti->MessageQueue->QF_flags & QF_MOUSEMOVED)
+   {
+      IntCoalesceMouseMove(pti);
+   }
+
    UserLeaveCo();
+
+   ZwYieldExecution(); // Let someone else run!
+
    ret = KeWaitForSingleObject( pti->pEventQueueServer,
                                 UserRequest,
                                 UserMode,
@@ -1999,7 +2200,26 @@ MsqIsHung(PTHREADINFO pti)
    LARGE_INTEGER LargeTickCount;
 
    KeQueryTickCount(&LargeTickCount);
-   return ((LargeTickCount.u.LowPart - pti->timeLast) > MSQ_HUNG);
+
+   if ((LargeTickCount.u.LowPart - pti->timeLast) > MSQ_HUNG &&
+       !(pti->pcti->fsWakeMask & QS_INPUT) &&
+       !PsGetThreadFreezeCount(pti->pEThread) &&
+       !(pti->ppi->W32PF_flags & W32PF_APPSTARTING))
+       return TRUE;
+
+   return FALSE;
+}
+
+BOOL FASTCALL
+IsThreadSuspended(PTHREADINFO pti)
+{
+   if (pti->pEThread)
+   {
+      BOOL Ret = TRUE;
+      if (!(pti->pEThread->Tcb.SuspendCount) && !PsGetThreadFreezeCount(pti->pEThread)) Ret = FALSE;
+      return Ret;
+   }
+   return FALSE;
 }
 
 VOID
@@ -2014,7 +2234,6 @@ HungAppSysTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
 BOOLEAN FASTCALL
 MsqInitializeMessageQueue(PTHREADINFO pti, PUSER_MESSAGE_QUEUE MessageQueue)
 {
-   MessageQueue->CaretInfo = (PTHRDCARETINFO)(MessageQueue + 1);
    InitializeListHead(&MessageQueue->HardwareMessagesListHead); // Keep here!
    MessageQueue->spwndFocus = NULL;
    MessageQueue->iCursorLevel = 0;
@@ -2039,11 +2258,29 @@ MsqCleanupThreadMsgs(PTHREADINFO pti)
    PUSER_MESSAGE CurrentMessage;
    PUSER_SENT_MESSAGE CurrentSentMessage;
 
+   TRACE("MsqCleanupThreadMsgs %p\n",pti);
+
+   // Clear it all out.
+   if (pti->pcti)
+   {
+       pti->pcti->fsWakeBits = 0;
+       pti->pcti->fsChangeBits = 0;
+   }
+
+   pti->nCntsQBits[QSRosKey] = 0;
+   pti->nCntsQBits[QSRosMouseMove] = 0;
+   pti->nCntsQBits[QSRosMouseButton] = 0;
+   pti->nCntsQBits[QSRosPostMessage] = 0;
+   pti->nCntsQBits[QSRosSendMessage] = 0;
+   pti->nCntsQBits[QSRosHotKey] = 0;
+   pti->nCntsQBits[QSRosEvent] = 0;
+
    /* cleanup posted messages */
    while (!IsListEmpty(&pti->PostedMessagesListHead))
    {
-      CurrentEntry = RemoveHeadList(&pti->PostedMessagesListHead);
+      CurrentEntry = pti->PostedMessagesListHead.Flink;
       CurrentMessage = CONTAINING_RECORD(CurrentEntry, USER_MESSAGE, ListEntry);
+      ERR("Thread Cleanup Post Messages %p\n",CurrentMessage);
       if (CurrentMessage->dwQEvent)
       {
          if (CurrentMessage->dwQEvent == POSTEVENT_NWE)
@@ -2057,21 +2294,15 @@ MsqCleanupThreadMsgs(PTHREADINFO pti)
    /* remove the messages that have not yet been dispatched */
    while (!IsListEmpty(&pti->SentMessagesListHead))
    {
-      CurrentEntry = RemoveHeadList(&pti->SentMessagesListHead);
+      CurrentEntry = pti->SentMessagesListHead.Flink;
       CurrentSentMessage = CONTAINING_RECORD(CurrentEntry, USER_SENT_MESSAGE, ListEntry);
 
-      TRACE("Notify the sender and remove a message from the queue that had not been dispatched\n");
-      /* Only if the message has a sender was the message in the DispatchingList */
-      if ((CurrentSentMessage->ptiSender)
-         && (CurrentSentMessage->DispatchingListEntry.Flink != NULL))
-      {
-         RemoveEntryList(&CurrentSentMessage->DispatchingListEntry);
-      }
+      ERR("Thread Cleanup Sent Messages %p\n",CurrentSentMessage);
 
       /* wake the sender's thread */
-      if (CurrentSentMessage->CompletionEvent != NULL)
+      if (CurrentSentMessage->pkCompletionEvent != NULL)
       {
-         KeSetEvent(CurrentSentMessage->CompletionEvent, IO_NO_INCREMENT, FALSE);
+         KeSetEvent(CurrentSentMessage->pkCompletionEvent, IO_NO_INCREMENT, FALSE);
       }
 
       if (CurrentSentMessage->HasPackedLParam)
@@ -2081,75 +2312,63 @@ MsqCleanupThreadMsgs(PTHREADINFO pti)
       }
 
       /* free the message */
-      ExFreePool(CurrentSentMessage);
+      FreeUserMessage(CurrentSentMessage);
    }
 
-   /* notify senders of dispatching messages. This needs to be cleaned up if e.g.
-      ExitThread() was called in a SendMessage() umode callback */
-   while (!IsListEmpty(&pti->LocalDispatchingMessagesHead))
+   // Process Trouble Message List
+   if (!IsListEmpty(&usmList))
    {
-      CurrentEntry = RemoveHeadList(&pti->LocalDispatchingMessagesHead);
-      CurrentSentMessage = CONTAINING_RECORD(CurrentEntry, USER_SENT_MESSAGE, ListEntry);
-
-      /* remove the message from the dispatching list */
-      if(CurrentSentMessage->DispatchingListEntry.Flink != NULL)
+      CurrentEntry = usmList.Flink;
+      while (CurrentEntry != &usmList)
       {
-         RemoveEntryList(&CurrentSentMessage->DispatchingListEntry);
-      }
+         CurrentSentMessage = CONTAINING_RECORD(CurrentEntry, USER_SENT_MESSAGE, ListEntry);
+         CurrentEntry = CurrentEntry->Flink;
 
-      TRACE("Notify the sender, the thread has been terminated while dispatching a message!\n");
+         TRACE("Found troubled messages %p on the list\n",CurrentSentMessage);
 
-      /* wake the sender's thread */
-      if (CurrentSentMessage->CompletionEvent != NULL)
-      {
-         KeSetEvent(CurrentSentMessage->CompletionEvent, IO_NO_INCREMENT, FALSE);
-      }
-
-      if (CurrentSentMessage->HasPackedLParam)
-      {
-         if (CurrentSentMessage->Msg.lParam)
+         if ( pti == CurrentSentMessage->ptiReceiver )
          {
-            _PRAGMA_WARNING_SUPPRESS(__WARNING_USING_UNINIT_VAR);
-            ExFreePool((PVOID)CurrentSentMessage->Msg.lParam);
-         }
-      }
+            if (CurrentSentMessage->HasPackedLParam)
+            {
+               if (CurrentSentMessage->Msg.lParam)
+                  ExFreePool((PVOID)CurrentSentMessage->Msg.lParam);
+            }
 
-      /* free the message */
-      ExFreePool(CurrentSentMessage);
-   }
+            /* free the message */
+            FreeUserMessage(CurrentSentMessage);
+         }
+         else if ( pti == CurrentSentMessage->ptiSender ||
+                   pti == CurrentSentMessage->ptiCallBackSender )
+         {
+            // Determine whether this message is being processed or not.
+            if ((CurrentSentMessage->flags & (SMF_RECEIVERBUSY|SMF_RECEIVEDMESSAGE)) != SMF_RECEIVEDMESSAGE)
+            {
+               CurrentSentMessage->flags |= SMF_RECEIVERFREE;
+            }
 
-   /* tell other threads not to bother returning any info to us */
-   while (! IsListEmpty(&pti->DispatchingMessagesHead))
-   {
-      CurrentEntry = RemoveHeadList(&pti->DispatchingMessagesHead);
-      CurrentSentMessage = CONTAINING_RECORD(CurrentEntry, USER_SENT_MESSAGE, DispatchingListEntry);
-      CurrentSentMessage->CompletionEvent = NULL;
-      CurrentSentMessage->Result = NULL;
+            if (!(CurrentSentMessage->flags & SMF_RECEIVERFREE))
+            {
 
-      /* do NOT dereference our message queue as it might get attempted to be
-         locked later */
-   }
+               if (CurrentSentMessage->HasPackedLParam)
+               {
+                  if (CurrentSentMessage->Msg.lParam)
+                     ExFreePool((PVOID)CurrentSentMessage->Msg.lParam);
+               }
 
-   // Clear it all out.
-   if (pti->pcti)
-   {
-       pti->pcti->fsWakeBits = 0;
-       pti->pcti->fsChangeBits = 0;
+               /* free the message */
+               FreeUserMessage(CurrentSentMessage);
+            }
+         }
+      }
    }
-
-   pti->nCntsQBits[QSRosKey] = 0;
-   pti->nCntsQBits[QSRosMouseMove] = 0;
-   pti->nCntsQBits[QSRosMouseButton] = 0;
-   pti->nCntsQBits[QSRosPostMessage] = 0;
-   pti->nCntsQBits[QSRosSendMessage] = 0;
-   pti->nCntsQBits[QSRosHotKey] = 0;
-   pti->nCntsQBits[QSRosEvent] = 0;
 }
 
 VOID FASTCALL
 MsqCleanupMessageQueue(PTHREADINFO pti)
 {
    PUSER_MESSAGE_QUEUE MessageQueue;
+   PLIST_ENTRY CurrentEntry;
+   PUSER_MESSAGE CurrentMessage;
 
    MessageQueue = pti->MessageQueue;
    MessageQueue->cThreads--;
@@ -2159,6 +2378,18 @@ MsqCleanupMessageQueue(PTHREADINFO pti)
       if (MessageQueue->ptiSysLock == pti) MessageQueue->ptiSysLock = NULL;
    }
 
+   if (MessageQueue->cThreads == 0) //// Fix a crash related to CORE-10471 testing.
+   {
+      /* cleanup posted messages */
+      while (!IsListEmpty(&MessageQueue->HardwareMessagesListHead))
+      {
+         CurrentEntry = MessageQueue->HardwareMessagesListHead.Flink;
+         CurrentMessage = CONTAINING_RECORD(CurrentEntry, USER_MESSAGE, ListEntry);
+         ERR("MQ Cleanup Post Messages %p\n",CurrentMessage);
+         MsqDestroyMessage(CurrentMessage);
+      }
+   } ////
+
    if (MessageQueue->CursorObject)
    {
        PCURICON_OBJECT pCursor = MessageQueue->CursorObject;
@@ -2200,16 +2431,16 @@ MsqCreateMessageQueue(PTHREADINFO pti)
 {
    PUSER_MESSAGE_QUEUE MessageQueue;
 
-   MessageQueue = (PUSER_MESSAGE_QUEUE)ExAllocatePoolWithTag(NonPagedPool,
-                  sizeof(USER_MESSAGE_QUEUE) + sizeof(THRDCARETINFO),
-                  USERTAG_Q);
+   MessageQueue = ExAllocatePoolWithTag(NonPagedPool,
+                                        sizeof(*MessageQueue),
+                                        USERTAG_Q);
 
    if (!MessageQueue)
    {
       return NULL;
    }
 
-   RtlZeroMemory(MessageQueue, sizeof(USER_MESSAGE_QUEUE) + sizeof(THRDCARETINFO));
+   RtlZeroMemory(MessageQueue, sizeof(*MessageQueue));
    /* hold at least one reference until it'll be destroyed */
    IntReferenceMessageQueue(MessageQueue);
    /* initialize the queue */
@@ -2296,7 +2527,7 @@ co_MsqReplyMessage( LRESULT lResult )
 
    if (Message->QS_Flags & QS_SMRESULT) return FALSE;
 
-   //     SendMessageXxx    || Callback msg and not a notify msg
+   //     SendMessageXxx  || Callback msg and not a notify msg
    if (Message->ptiSender || Message->CompletionCallback)
    {
       Message->lResult = lResult;
@@ -2337,9 +2568,8 @@ MsqSetStateWindow(PTHREADINFO pti, ULONG Type, HWND hWnd)
          MessageQueue->MoveSize = hWnd;
          return Prev;
       case MSQ_STATE_CARET:
-         ASSERT(MessageQueue->CaretInfo);
-         Prev = MessageQueue->CaretInfo->hWnd;
-         MessageQueue->CaretInfo->hWnd = hWnd;
+         Prev = MessageQueue->CaretInfo.hWnd;
+         MessageQueue->CaretInfo.hWnd = hWnd;
          return Prev;
    }