MiQueryVirtualMemory(): created because ZwQueryVirtualMemory() didn't work for me...
[reactos.git] / reactos / ntoskrnl / ke / i386 / exp.c
index 532340e..ac21c66 100644 (file)
  * PROJECT:              ReactOS kernel
  * FILE:                 ntoskrnl/ke/i386/exp.c
  * PURPOSE:              Handling exceptions
- * PROGRAMMER:           David Welch (welch@cwcom.net)
+ * PROGRAMMERS:          David Welch (welch@cwcom.net)
+ *                       Skywing (skywing@valhallalegends.com)
  * REVISION HISTORY:
  *              ??/??/??: Created
+ *              09/12/03: KeRaiseUserException added (Skywing).
  */
 
 /* INCLUDES *****************************************************************/
 
-#include <ddk/ntddk.h>
-#include <internal/ntoskrnl.h>
-#include <internal/ke.h>
-#include <internal/i386/segment.h>
-#include <internal/i386/mm.h>
-#include <internal/module.h>
-#include <internal/mm.h>
-#include <internal/ps.h>
-#include <internal/trap.h>
-
+#include <ntoskrnl.h>
+#include <pseh.h>
 #define NDEBUG
 #include <internal/debug.h>
 
 /* GLOBALS *****************************************************************/
 
+#define FLAG_IF (1<<9)
+
 #define _STR(x) #x
 #define STR(x) _STR(x)
 
+#ifndef ARRAY_SIZE
+# define ARRAY_SIZE(x) (sizeof (x) / sizeof (x[0]))
+#endif
+
 extern void interrupt_handler2e(void);
 extern void interrupt_handler2d(void);
 
@@ -65,97 +65,137 @@ extern VOID KiTrap13(VOID);
 extern VOID KiTrap14(VOID);
 extern VOID KiTrap15(VOID);
 extern VOID KiTrap16(VOID);
+extern VOID KiTrap17(VOID);
+extern VOID KiTrap18(VOID);
+extern VOID KiTrap19(VOID);
 extern VOID KiTrapUnknown(VOID);
 
 extern ULONG init_stack;
 extern ULONG init_stack_top;
 
-static char KiNullLdt[8] = {0,};
+extern BOOLEAN Ke386NoExecute;
 
-/* FUNCTIONS ****************************************************************/
+static char *ExceptionTypeStrings[] =
+  {
+    "Divide Error",
+    "Debug Trap",
+    "NMI",
+    "Breakpoint",
+    "Overflow",
+    "BOUND range exceeded",
+    "Invalid Opcode",
+    "No Math Coprocessor",
+    "Double Fault",
+    "Unknown(9)",
+    "Invalid TSS",
+    "Segment Not Present",
+    "Stack Segment Fault",
+    "General Protection",
+    "Page Fault",
+    "Reserved(15)",
+    "Math Fault",
+    "Alignment Check",
+    "Machine Check",
+    "SIMD Fault"
+  };
 
-extern unsigned int _text_start__, _text_end__;
+static NTSTATUS ExceptionToNtStatus[] =
+  {
+    STATUS_INTEGER_DIVIDE_BY_ZERO,
+    STATUS_SINGLE_STEP,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_BREAKPOINT,
+    STATUS_INTEGER_OVERFLOW,
+    STATUS_ARRAY_BOUNDS_EXCEEDED,
+    STATUS_ILLEGAL_INSTRUCTION,
+    STATUS_ACCESS_VIOLATION, /* STATUS_FLT_INVALID_OPERATION */
+    STATUS_ACCESS_VIOLATION,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_STACK_OVERFLOW,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_ACCESS_VIOLATION, /* RESERVED */
+    STATUS_ACCESS_VIOLATION, /* STATUS_FLT_INVALID_OPERATION */
+    STATUS_DATATYPE_MISALIGNMENT,
+    STATUS_ACCESS_VIOLATION,
+    STATUS_ACCESS_VIOLATION  /* STATUS_FLT_MULTIPLE_TRAPS? */
+  };
 
-STATIC BOOLEAN 
-print_address(PVOID address)
+/* FUNCTIONS ****************************************************************/
+
+#if defined(DBG) || defined(KDBG)
+BOOLEAN STDCALL
+KeRosPrintAddress(PVOID address)
+{
+  return KdbSymPrintAddress(address);
+}
+#else /* KDBG */
+BOOLEAN STDCALL
+KeRosPrintAddress(PVOID address)
 {
    PLIST_ENTRY current_entry;
    MODULE_TEXT_SECTION* current;
    extern LIST_ENTRY ModuleTextListHead;
-   
+   ULONG_PTR RelativeAddress;
+
    current_entry = ModuleTextListHead.Flink;
-   
+
    while (current_entry != &ModuleTextListHead &&
          current_entry != NULL)
      {
-       current = 
+       current =
          CONTAINING_RECORD(current_entry, MODULE_TEXT_SECTION, ListEntry);
-       
+
        if (address >= (PVOID)current->Base &&
            address < (PVOID)(current->Base + current->Length))
          {
-            DbgPrint("<%ws: %x>", current->Name, 
-                     address - current->Base);
-            return(TRUE);
+            RelativeAddress = (ULONG_PTR) address - current->Base;
+           DbgPrint("<%ws: %x>", current->Name, RelativeAddress);
+           return(TRUE);
          }
-
        current_entry = current_entry->Flink;
      }
-#if 0
-   DbgPrint("<%x>", address);
-#endif
    return(FALSE);
 }
+#endif /* KDBG */
 
 ULONG
-KiUserTrapHandler(PKTRAP_FRAME Tf, ULONG ExceptionNr, PVOID Cr2)
+KiKernelTrapHandler(PKTRAP_FRAME Tf, ULONG ExceptionNr, PVOID Cr2)
 {
   EXCEPTION_RECORD Er;
 
-  if (ExceptionNr == 0)
-    {
-      Er.ExceptionCode = STATUS_INTEGER_DIVIDE_BY_ZERO;
-    }
-  else if (ExceptionNr == 1)
-    {
-      Er.ExceptionCode = STATUS_SINGLE_STEP;
-    }
-  else if (ExceptionNr == 3)
-    {
-      Er.ExceptionCode = STATUS_BREAKPOINT;
-    }
-  else if (ExceptionNr == 4)
-    {
-      Er.ExceptionCode = STATUS_INTEGER_OVERFLOW;
-    }
-  else if (ExceptionNr == 5)
-    {
-      Er.ExceptionCode = STATUS_ARRAY_BOUNDS_EXCEEDED;
-    }
-  else if (ExceptionNr == 6)
-    {
-      Er.ExceptionCode = STATUS_ILLEGAL_INSTRUCTION;
-    }
-  else
-    {
-      Er.ExceptionCode = STATUS_ACCESS_VIOLATION;
-    }
   Er.ExceptionFlags = 0;
   Er.ExceptionRecord = NULL;
   Er.ExceptionAddress = (PVOID)Tf->Eip;
+
   if (ExceptionNr == 14)
     {
+      Er.ExceptionCode = STATUS_ACCESS_VIOLATION;
       Er.NumberParameters = 2;
       Er.ExceptionInformation[0] = Tf->ErrorCode & 0x1;
       Er.ExceptionInformation[1] = (ULONG)Cr2;
     }
   else
     {
+      if (ExceptionNr < ARRAY_SIZE(ExceptionToNtStatus))
+       {
+         Er.ExceptionCode = ExceptionToNtStatus[ExceptionNr];
+       }
+      else
+       {
+         Er.ExceptionCode = STATUS_ACCESS_VIOLATION;
+       }
       Er.NumberParameters = 0;
     }
-  
 
-  KiDispatchException(&Er, 0, Tf, UserMode, TRUE);
+  Er.ExceptionFlags = ((NTSTATUS) STATUS_SINGLE_STEP == (NTSTATUS) Er.ExceptionCode
+    || (NTSTATUS) STATUS_BREAKPOINT == (NTSTATUS) Er.ExceptionCode) ?
+    EXCEPTION_NONCONTINUABLE : 0;
+
+  KiDispatchException(&Er, 0, Tf, KernelMode, TRUE);
+
   return(0);
 }
 
@@ -163,40 +203,38 @@ ULONG
 KiDoubleFaultHandler(VOID)
 {
   unsigned int cr2;
-  unsigned int i;
-  PULONG stack;
   ULONG StackLimit;
+  ULONG StackBase;
   ULONG Esp0;
   ULONG ExceptionNr = 8;
-  extern KTSS KiTss;
-  static char *TypeStrings[] = 
-  {
-    "Divide Error",
-    "Debug Trap",
-    "NMI",
-    "Breakpoint",
-    "Overflow",
-    "BOUND range exceeded",
-    "Invalid Opcode",
-    "No Math Coprocessor",
-    "Double Fault",
-    "Unknown(9)",
-    "Invalid TSS",
-    "Segment Not Present",
-    "Stack Segment Fault",
-    "General Protection",
-    "Page Fault",
-    "Math Fault",
-    "Alignment Check",
-    "Machine Check"
-  };
-  
-  /* Use the address of the trap frame as approximation to the ring0 esp */
-  Esp0 = KiTss.Esp0;
-  
-   /* Get CR2 */
-   __asm__("movl %%cr2,%0\n\t" : "=d" (cr2));
-   
+  KTSS* OldTss;
+  PULONG Frame;
+  ULONG OldCr3;
+#if 0
+  ULONG i, j;
+  static PVOID StackTrace[MM_STACK_SIZE / sizeof(PVOID)];
+  static ULONG StackRepeatCount[MM_STACK_SIZE / sizeof(PVOID)];
+  static ULONG StackRepeatLength[MM_STACK_SIZE / sizeof(PVOID)];
+  ULONG TraceLength;
+  BOOLEAN FoundRepeat;
+#endif
+
+  OldTss = KeGetCurrentKPCR()->TSS;
+  Esp0 = OldTss->Esp;
+
+  /* Get CR2 */
+  cr2 = Ke386GetCr2();
+  if (PsGetCurrentThread() != NULL &&
+      PsGetCurrentThread()->ThreadsProcess != NULL)
+    {
+      OldCr3 = (ULONG)
+       PsGetCurrentThread()->ThreadsProcess->Pcb.DirectoryTableBase.QuadPart;
+    }
+  else
+    {
+      OldCr3 = 0xBEADF0AL;
+    }
+
    /*
     * Check for stack underflow
     */
@@ -207,23 +245,23 @@ KiDoubleFaultHandler(VOID)
                 Esp0, (ULONG)PsGetCurrentThread()->Tcb.StackLimit);
        ExceptionNr = 12;
      }
-   
+
    /*
     * Print out the CPU registers
     */
-   if (ExceptionNr < 19)
+   if (ExceptionNr < ARRAY_SIZE(ExceptionTypeStrings))
      {
-       DbgPrint("%s Exception: %d(%x)\n",TypeStrings[ExceptionNr],
+       DbgPrint("%s Exception: %d(%x)\n", ExceptionTypeStrings[ExceptionNr],
                ExceptionNr, 0);
      }
    else
      {
        DbgPrint("Exception: %d(%x)\n", ExceptionNr, 0);
      }
-   DbgPrint("CS:EIP %x:%x ", KiTss.Cs, KiTss.Eip);
-   print_address((PVOID)KiTss.Eip);
+   DbgPrint("CS:EIP %x:%x ", OldTss->Cs, OldTss->Eip);
+   KeRosPrintAddress((PVOID)OldTss->Eip);
    DbgPrint("\n");
-   DbgPrint("cr2 %x cr3 %x ", cr2, KiTss.Cr3);
+   DbgPrint("cr2 %x cr3 %x ", cr2, OldCr3);
    DbgPrint("Proc: %x ",PsGetCurrentProcess());
    if (PsGetCurrentProcess() != NULL)
      {
@@ -237,168 +275,170 @@ KiDoubleFaultHandler(VOID)
                 PsGetCurrentThread()->Cid.UniqueThread);
      }
    DbgPrint("\n");
-   DbgPrint("DS %x ES %x FS %x GS %x\n", KiTss.Ds, KiTss.Es,
-           KiTss.Fs, KiTss.Gs);
-   DbgPrint("EAX: %.8x   EBX: %.8x   ECX: %.8x\n", KiTss.Eax, KiTss.Ebx, 
-           KiTss.Ecx);
-   DbgPrint("EDX: %.8x   EBP: %.8x   ESI: %.8x\n", KiTss.Edx, KiTss.Ebp, 
-           KiTss.Esi);
-   DbgPrint("EDI: %.8x   EFLAGS: %.8x ", KiTss.Edi, KiTss.Eflags);
-   if (KiTss.Cs == KERNEL_CS)
+   DbgPrint("DS %x ES %x FS %x GS %x\n", OldTss->Ds, OldTss->Es,
+           OldTss->Fs, OldTss->Gs);
+   DbgPrint("EAX: %.8x   EBX: %.8x   ECX: %.8x\n", OldTss->Eax, OldTss->Ebx,
+           OldTss->Ecx);
+   DbgPrint("EDX: %.8x   EBP: %.8x   ESI: %.8x\n   ESP: %.8x", OldTss->Edx,
+           OldTss->Ebp, OldTss->Esi, Esp0);
+   DbgPrint("EDI: %.8x   EFLAGS: %.8x ", OldTss->Edi, OldTss->Eflags);
+   if (OldTss->Cs == KERNEL_CS)
      {
        DbgPrint("kESP %.8x ", Esp0);
        if (PsGetCurrentThread() != NULL)
          {
             DbgPrint("kernel stack base %x\n",
                      PsGetCurrentThread()->Tcb.StackLimit);
-                            
+
          }
      }
    else
      {
-       DbgPrint("User ESP %.8x\n", KiTss.Esp);
+       DbgPrint("User ESP %.8x\n", OldTss->Esp);
      }
-  if ((KiTss.Cs & 0xffff) == KERNEL_CS)
+  if ((OldTss->Cs & 0xffff) == KERNEL_CS)
     {
-       DbgPrint("ESP %x\n", Esp0);
-       stack = (PULONG) (Esp0 + 24);
-       stack = (PULONG)(((ULONG)stack) & (~0x3));
-       if (PsGetCurrentThread() != NULL)
-        {
-          StackLimit = (ULONG)PsGetCurrentThread()->Tcb.StackBase;
-        }
-       else
-        {
-          StackLimit = (ULONG)&init_stack_top;
-        }
-       
-       DbgPrint("stack<%p>: ", stack);
-        
-       for (i = 0; i < 18 && (((ULONG)&stack[i+5]) < StackLimit); i = i + 6)
-        {
-           DbgPrint("%.8x %.8x %.8x %.8x\n", 
-                    stack[i], stack[i+1], 
-                    stack[i+2], stack[i+3], 
-                    stack[i+4], stack[i+5]);
-        }
-       DbgPrint("Frames:\n");
-       for (i = 0; i < 32 && (((ULONG)&stack[i]) < StackLimit); i++)
-        {
-           if (stack[i] > ((unsigned int) &_text_start__) &&
-             !(stack[i] >= ((ULONG)&init_stack) &&
-               stack[i] <= ((ULONG)&init_stack_top)))
-             {
-                print_address((PVOID)stack[i]);
-                DbgPrint(" ");
-             }
-        }
+      if (PsGetCurrentThread() != NULL)
+       {
+         StackLimit = (ULONG)PsGetCurrentThread()->Tcb.StackBase;
+         StackBase = (ULONG)PsGetCurrentThread()->Tcb.StackLimit;
+       }
+      else
+       {
+         StackLimit = (ULONG)&init_stack_top;
+         StackBase = (ULONG)&init_stack;
+       }
+
+      /*
+        Change to an #if 0 to reduce the amount of information printed on
+        a recursive stack trace.
+      */
+#if 1
+      DbgPrint("Frames: ");
+      Frame = (PULONG)OldTss->Ebp;
+      while (Frame != NULL && (ULONG)Frame >= StackBase)
+       {
+         KeRosPrintAddress((PVOID)Frame[1]);
+         Frame = (PULONG)Frame[0];
+          DbgPrint(" ");
+       }
+#else
+      DbgPrint("Frames: ");
+      i = 0;
+      Frame = (PULONG)OldTss->Ebp;
+      while (Frame != NULL && (ULONG)Frame >= StackBase)
+       {
+         StackTrace[i] = (PVOID)Frame[1];
+         Frame = (PULONG)Frame[0];
+         i++;
+       }
+      TraceLength = i;
+
+      i = 0;
+      while (i < TraceLength)
+       {
+         StackRepeatCount[i] = 0;
+         j = i + 1;
+         FoundRepeat = FALSE;
+         while ((j - i) <= (TraceLength - j) && FoundRepeat == FALSE)
+           {
+             if (memcmp(&StackTrace[i], &StackTrace[j],
+                        (j - i) * sizeof(PVOID)) == 0)
+               {
+                 StackRepeatCount[i] = 2;
+                 StackRepeatLength[i] = j - i;
+                 FoundRepeat = TRUE;
+               }
+             else
+               {
+                 j++;
+               }
+           }
+         if (FoundRepeat == FALSE)
+           {
+             i++;
+             continue;
+           }
+         j = j + StackRepeatLength[i];
+         while ((TraceLength - j) >= StackRepeatLength[i] &&
+                FoundRepeat == TRUE)
+           {
+             if (memcmp(&StackTrace[i], &StackTrace[j],
+                        StackRepeatLength[i] * sizeof(PVOID)) == 0)
+               {
+                 StackRepeatCount[i]++;
+                 j = j + StackRepeatLength[i];
+               }
+             else
+               {
+                 FoundRepeat = FALSE;
+               }
+           }
+         i = j;
+       }
+
+      i = 0;
+      while (i < TraceLength)
+       {
+         if (StackRepeatCount[i] == 0)
+           {
+             KeRosPrintAddress(StackTrace[i]);
+             i++;
+           }
+         else
+           {
+             DbgPrint("{");
+             if (StackRepeatLength[i] == 0)
+               {
+                 for(;;);
+               }
+             for (j = 0; j < StackRepeatLength[i]; j++)
+               {
+                 KeRosPrintAddress(StackTrace[i + j]);
+               }
+             DbgPrint("}*%d", StackRepeatCount[i]);
+             i = i + StackRepeatLength[i] * StackRepeatCount[i];
+           }
+       }
+#endif
     }
-   
+
    DbgPrint("\n");
    for(;;);
+   return 0;
 }
 
-ULONG
-KiTrapHandler(PKTRAP_FRAME Tf, ULONG ExceptionNr)
-/*
- * FUNCTION: Called by the lowlevel execption handlers to print an amusing 
- * message and halt the computer
- * ARGUMENTS:
- *        Complete CPU context
- */
+VOID
+KiDumpTrapFrame(PKTRAP_FRAME Tf, ULONG Parameter1, ULONG Parameter2)
 {
-   unsigned int cr2, cr3;
-   unsigned int i;
-//   unsigned int j, sym;
-   PULONG stack;
-   NTSTATUS Status;
-   ULONG Esp0;
-   ULONG StackLimit;
-   static char *TypeStrings[] = 
-     {
-       "Divide Error",
-       "Debug Trap",
-       "NMI",
-       "Breakpoint",
-       "Overflow",
-       "BOUND range exceeded",
-       "Invalid Opcode",
-       "No Math Coprocessor",
-       "Double Fault",
-       "Unknown(9)",
-       "Invalid TSS",
-       "Segment Not Present",
-       "Stack Segment Fault",
-       "General Protection",
-       "Page Fault",
-       "Math Fault",
-       "Alignment Check",
-       "Machine Check"
-     };
-
-   /* Use the address of the trap frame as approximation to the ring0 esp */
-   Esp0 = (ULONG)&Tf->Eip;
-   
-   /* Get CR2 */
-   __asm__("movl %%cr2,%0\n\t" : "=d" (cr2));
-   
-   /*
-    * If this was a V86 mode exception then handle it specially
-    */
-   if (Tf->Eflags & (1 << 17))
-     {
-       return(KeV86Exception(ExceptionNr, Tf, cr2));
-     }
-
-   /*
-    * Check for stack underflow
-    */
-   if (PsGetCurrentThread() != NULL &&
-       Esp0 < (ULONG)PsGetCurrentThread()->Tcb.StackLimit)
-     {
-       DbgPrint("Stack underflow (tf->esp %x Limit %x)\n",
-                Esp0, (ULONG)PsGetCurrentThread()->Tcb.StackLimit);
-       ExceptionNr = 12;
-     }
-   
-   if (ExceptionNr == 14)
-     {
-       __asm__("sti\n\t");
-       Status = MmPageFault(Tf->Cs&0xffff,
-                            &Tf->Eip,
-                            &Tf->Eax,
-                            cr2,
-                            Tf->ErrorCode);
-       if (NT_SUCCESS(Status))
-         {
-            return(0);
-         }
-     }
+  ULONG cr3_;
+  ULONG i;
+  ULONG StackLimit;
+  PULONG Frame;
+  ULONG Esp0;
+  ULONG ExceptionNr = (ULONG)Tf->DebugArgMark;
+  ULONG cr2 = (ULONG)Tf->DebugPointer;
 
-#if 0
-   if ((Tf->Cs & 0xFFFF) == USER_CS)
-     {
-       return(KiUserTrapHandler(Tf, ExceptionNr, (PVOID)cr2));
-     }
-#endif   
+  Esp0 = (ULONG)Tf;
 
    /*
     * Print out the CPU registers
     */
-   if (ExceptionNr < 19)
+   if (ExceptionNr < ARRAY_SIZE(ExceptionTypeStrings))
      {
-       DbgPrint("%s Exception: %d(%x)\n",TypeStrings[ExceptionNr],
+       DbgPrint("%s Exception: %d(%x)\n", ExceptionTypeStrings[ExceptionNr],
                 ExceptionNr, Tf->ErrorCode&0xffff);
      }
    else
      {
        DbgPrint("Exception: %d(%x)\n", ExceptionNr, Tf->ErrorCode&0xffff);
      }
-   DbgPrint("CS:EIP %x:%x ", Tf->Cs&0xffff, Tf->Eip);
-   print_address((PVOID)Tf->Eip);
+   DbgPrint("Processor: %d CS:EIP %x:%x ", KeGetCurrentProcessorNumber(),
+           Tf->Cs&0xffff, Tf->Eip);
+   KeRosPrintAddress((PVOID)Tf->Eip);
    DbgPrint("\n");
-   __asm__("movl %%cr3,%0\n\t" : "=d" (cr3));
-   DbgPrint("cr2 %x cr3 %x ", cr2, cr3);
+   Ke386GetPageTableDirectory(cr3_);
+   DbgPrint("cr2 %x cr3 %x ", cr2, cr3_);
    DbgPrint("Proc: %x ",PsGetCurrentProcess());
    if (PsGetCurrentProcess() != NULL)
      {
@@ -415,7 +455,8 @@ KiTrapHandler(PKTRAP_FRAME Tf, ULONG ExceptionNr)
    DbgPrint("DS %x ES %x FS %x GS %x\n", Tf->Ds&0xffff, Tf->Es&0xffff,
            Tf->Fs&0xffff, Tf->Gs&0xfff);
    DbgPrint("EAX: %.8x   EBX: %.8x   ECX: %.8x\n", Tf->Eax, Tf->Ebx, Tf->Ecx);
-   DbgPrint("EDX: %.8x   EBP: %.8x   ESI: %.8x\n", Tf->Edx, Tf->Ebp, Tf->Esi);
+   DbgPrint("EDX: %.8x   EBP: %.8x   ESI: %.8x   ESP: %.8x\n", Tf->Edx,
+           Tf->Ebp, Tf->Esi, Esp0);
    DbgPrint("EDI: %.8x   EFLAGS: %.8x ", Tf->Edi, Tf->Eflags);
    if ((Tf->Cs&0xffff) == KERNEL_CS)
      {
@@ -424,141 +465,320 @@ KiTrapHandler(PKTRAP_FRAME Tf, ULONG ExceptionNr)
          {
             DbgPrint("kernel stack base %x\n",
                      PsGetCurrentThread()->Tcb.StackLimit);
-                            
+
          }
      }
+
+   if (PsGetCurrentThread() != NULL)
+     {
+       StackLimit = (ULONG)PsGetCurrentThread()->Tcb.StackBase;
+     }
    else
      {
-       DbgPrint("User ESP %.8x\n", Tf->Esp);
+       StackLimit = (ULONG)&init_stack_top;
      }
-  if ((Tf->Cs & 0xffff) == KERNEL_CS)
-    {
-       DbgPrint("ESP %x\n", Esp0);
-       stack = (PULONG) (Esp0 + 24);
-       stack = (PULONG)(((ULONG)stack) & (~0x3));
-       
-       DbgPrint("stack<%p>: ", stack);
 
-       if (PsGetCurrentThread() != NULL)
-        {
-          StackLimit = (ULONG)PsGetCurrentThread()->Tcb.StackBase;
-        }
-       else
+   /*
+    * Dump the stack frames
+    */
+   DbgPrint("Frames: ");
+   /* Change to an #if 0 if no frames are printed because of fpo. */
+#if 1
+   i = 1;
+   Frame = (PULONG)Tf->Ebp;
+   while (Frame != NULL)
+     {
+       NTSTATUS Status;
+       PVOID Eip;
+       Status = MmSafeCopyFromUser(&Eip, Frame + 1, sizeof(Eip));
+       if (!NT_SUCCESS(Status))
         {
-          StackLimit = (ULONG)&init_stack_top;
+          DbgPrint("<INVALID>");
+          break;
         }
-        
-       for (i = 0; i < 18; i = i + 6)
+       if (!KeRosPrintAddress(Eip))
         {
-           DbgPrint("%.8x %.8x %.8x %.8x\n", 
-                    stack[i], stack[i+1], 
-                    stack[i+2], stack[i+3], 
-                    stack[i+4], stack[i+5]);
+          DbgPrint("<%X>", Eip);
         }
-       DbgPrint("Frames:\n");
-       for (i = 0; i < 32 && ((ULONG)&stack[i] < StackLimit); i++)
+       Status = MmSafeCopyFromUser(&Frame, Frame, sizeof(Frame));
+       if (!NT_SUCCESS(Status))
         {
-           if (stack[i] > ((unsigned int) &_text_start__) &&
-             !(stack[i] >= ((ULONG)&init_stack) &&
-               stack[i] <= ((ULONG)&init_stack_top)))
-             {
-                //              DbgPrint("  %.8x", stack[i]);
-                print_address((PVOID)stack[i]);
-                DbgPrint(" ");
-             }
+          break;
         }
-    }
-   else
-     {
-#if 1
-       DbgPrint("SS:ESP %x:%x\n", Tf->Ss, Tf->Esp);
-        stack=(PULONG)(Tf->Esp);
-       
-        DbgPrint("Stack:\n");
-        for (i=0; i<64; i++)
-        {
-          if (MmIsPagePresent(NULL,&stack[i]))
-            {
-               DbgPrint("%.8x ",stack[i]);
-               if (((i+1)%8) == 0)
-                 {
-                    DbgPrint("\n");
-                 }
-            }
-        }
-       
-       if (MmIsPagePresent(NULL, (PVOID)Tf->Eip))
-         {
-            unsigned char instrs[512];
-            
-            memcpy(instrs, (PVOID)Tf->Eip, 512);
-            
-            DbgPrint("Instrs: ");
-            
-            for (i=0; i<10; i++)
-              {
-                 DbgPrint("%x ", instrs[i]);
-              }
-         }
-#endif
+       i++;
+       DbgPrint(" ");
      }
-   
-   DbgPrint("\n");
-   if ((Tf->Cs&0xffff) == USER_CS &&
-       Tf->Eip < KERNEL_BASE)
+#else
+   i = 1;
+   Frame = (PULONG)((ULONG_PTR)Esp0 + KTRAP_FRAME_EFLAGS);
+   while (Frame < (PULONG)PsGetCurrentThread()->Tcb.StackBase && i < 50)
      {
-       DbgPrint("Killing current task\n");
-       KeLowerIrql(PASSIVE_LEVEL);
-       if ((Tf->Cs&0xffff) == USER_CS)
-         {
-            ZwTerminateProcess(NtCurrentProcess(),
-                               STATUS_NONCONTINUABLE_EXCEPTION);
-         }
-     }   
-   for(;;);
+        ULONG Address = *Frame;
+        if (KeRosPrintAddress((PVOID)Address))
+          {
+            i++;
+          }
+        Frame++;
+     }
+#endif
 }
 
-VOID 
-KeDumpStackFrames(PVOID _Stack, ULONG NrFrames)
+ULONG
+KiTrapHandler(PKTRAP_FRAME Tf, ULONG ExceptionNr)
+/*
+ * FUNCTION: Called by the lowlevel execption handlers to print an amusing
+ * message and halt the computer
+ * ARGUMENTS:
+ *        Complete CPU context
+ */
 {
-   PULONG Stack = (PULONG)_Stack;
-   ULONG i;
-   ULONG StackLimit;
-   
-   Stack = (PVOID)(((ULONG)Stack) & (~0x3));
-   DbgPrint("Stack: %x\n", Stack);
-   if (PsGetCurrentThread() != NULL)
-     {
-       DbgPrint("kernel stack base %x\n",
-                PsGetCurrentThread()->Tcb.StackLimit);
-     }
+   unsigned int cr2;
+   NTSTATUS Status;
+   ULONG Esp0;
 
-   if (PsGetCurrentThread() != NULL)
+   /* Store the exception number in an unused field in the trap frame. */
+   Tf->DebugArgMark = (PVOID)ExceptionNr;
+
+   /* Use the address of the trap frame as approximation to the ring0 esp */
+   Esp0 = (ULONG)&Tf->Eip;
+
+   /* Get CR2 */
+   cr2 = Ke386GetCr2();
+   Tf->DebugPointer = (PVOID)cr2;
+
+   if (ExceptionNr == 14 && Tf->Eflags & FLAG_IF)
+   {
+     Ke386EnableInterrupts();
+   }
+
+   /*
+    * If this was a V86 mode exception then handle it specially
+    */
+   if (Tf->Eflags & (1 << 17))
      {
-       StackLimit = (ULONG)PsGetCurrentThread()->Tcb.StackBase;
+       return(KeV86Exception(ExceptionNr, Tf, cr2));
      }
-   else
+
+   /*
+    * Check for stack underflow, this may be obsolete
+    */
+   if (PsGetCurrentThread() != NULL &&
+       Esp0 < (ULONG)PsGetCurrentThread()->Tcb.StackLimit)
      {
-       StackLimit = (ULONG)&init_stack_top;
+       DbgPrint("Stack underflow (tf->esp %x Limit %x)\n",
+                Esp0, (ULONG)PsGetCurrentThread()->Tcb.StackLimit);
+       ExceptionNr = 12;
      }
-   
-   DbgPrint("Frames:\n");
-   for (i=0; i<NrFrames && ((ULONG)&Stack[i] < StackLimit); i++)
+
+   /*
+    * Maybe handle the page fault and return
+    */
+   if (ExceptionNr == 14)
      {
-       if (Stack[i] > KERNEL_BASE)
-         {
-            print_address((PVOID)Stack[i]);
-            DbgPrint(" ");
-         }
-       if (Stack[i] == 0xceafbeef)
+        if (Ke386NoExecute && Tf->ErrorCode & 0x10 && cr2 >= KERNEL_BASE)
+       {
+           KEBUGCHECKWITHTF(ATTEMPTED_EXECUTE_OF_NOEXECUTE_MEMORY, 0, 0, 0, 0, Tf);
+       }
+       Status = MmPageFault(Tf->Cs&0xffff,
+                            &Tf->Eip,
+                            &Tf->Eax,
+                            cr2,
+                            Tf->ErrorCode);
+       if (NT_SUCCESS(Status))
          {
-            DbgPrint("IRQ ");
+            return(0);
          }
      }
-   DbgPrint("\n");
+
+   /*
+    * Check for a breakpoint that was only for the attention of the debugger.
+    */
+   if (ExceptionNr == 3 && Tf->Eip == ((ULONG)DbgBreakPointNoBugCheck) + 1)
+     {
+       /*
+         EIP is already adjusted by the processor to point to the instruction
+         after the breakpoint.
+       */
+       return(0);
+     }
+
+   /*
+    * Try to handle device-not-present, math-fault and xmm-fault exceptions.
+    */
+   if (ExceptionNr == 7 || ExceptionNr == 16 || ExceptionNr == 19)
+     {
+       Status = KiHandleFpuFault(Tf, ExceptionNr);
+       if (NT_SUCCESS(Status))
+         {
+           return(0);
+         }
+     }
+
+   /*
+    * Handle user exceptions differently
+    */
+   if ((Tf->Cs & 0xFFFF) == USER_CS)
+     {
+       return(KiUserTrapHandler(Tf, ExceptionNr, (PVOID)cr2));
+     }
+   else
+    {
+      return(KiKernelTrapHandler(Tf, ExceptionNr, (PVOID)cr2));
+    }
+}
+
+VOID
+KeDumpStackFrames(PULONG Frame)
+{
+       PULONG StackBase, StackEnd;
+       MEMORY_BASIC_INFORMATION mbi;
+       ULONG ResultLength = sizeof(mbi);
+       NTSTATUS Status;
+
+       DbgPrint("Frames: ");
+       _SEH_TRY
+       {
+               Status = MiQueryVirtualMemory (
+                       (HANDLE)-1,
+                       Frame,
+                       MemoryBasicInformation,
+                       &mbi,
+                       sizeof(mbi),
+                       &ResultLength );
+               if ( !NT_SUCCESS(Status) )
+               {
+                       DPRINT1("Can't dump stack frames: NtQueryVirtualMemory() failed: %x\n", Status );
+                       return;
+               }
+
+               StackBase = Frame;
+               StackEnd = mbi.BaseAddress + mbi.RegionSize;
+
+               while ( Frame >= StackBase && Frame < StackEnd )
+               {
+                       ULONG Addr = Frame[1];
+                       if (!KeRosPrintAddress((PVOID)Addr))
+                               DbgPrint("<%X>", Addr);
+                       if ( Addr == 0 || Addr == 0xDEADBEEF )
+                               break;
+                       StackBase = Frame;
+                       Frame = (PULONG)Frame[0];
+                       DbgPrint(" ");
+               }
+       }
+       _SEH_HANDLE
+       {
+       }
+       _SEH_END;
+       DbgPrint("\n");
+}
+
+VOID STDCALL
+KeRosDumpStackFrames ( PULONG Frame, ULONG FrameCount )
+{
+       ULONG i=0;
+       PULONG StackBase, StackEnd;
+       MEMORY_BASIC_INFORMATION mbi;
+       ULONG ResultLength = sizeof(mbi);
+       NTSTATUS Status;
+
+       DbgPrint("Frames: ");
+       _SEH_TRY
+       {
+               if ( !Frame )
+               {
+#if defined __GNUC__
+                       __asm__("mov %%ebp, %%ebx" : "=b" (Frame) : );
+#elif defined(_MSC_VER)
+                       __asm mov [Frame], ebp
+#endif
+                       //Frame = (PULONG)Frame[0]; // step out of KeRosDumpStackFrames
+               }
+
+               Status = MiQueryVirtualMemory (
+                       (HANDLE)-1,
+                       Frame,
+                       MemoryBasicInformation,
+                       &mbi,
+                       sizeof(mbi),
+                       &ResultLength );
+               if ( !NT_SUCCESS(Status) )
+               {
+                       DPRINT1("Can't dump stack frames: NtQueryVirtualMemory() failed: %x\n", Status );
+                       return;
+               }
+
+               StackBase = Frame;
+               StackEnd = mbi.BaseAddress + mbi.RegionSize;
+
+               while ( Frame >= StackBase && Frame < StackEnd && i++ < FrameCount )
+               {
+                       ULONG Addr = Frame[1];
+                       if (!KeRosPrintAddress((PVOID)Addr))
+                               DbgPrint("<%X>", Addr);
+                       if ( Addr == 0 || Addr == 0xDEADBEEF )
+                               break;
+                       StackBase = Frame;
+                       Frame = (PULONG)Frame[0];
+                       DbgPrint(" ");
+               }
+       }
+       _SEH_HANDLE
+       {
+       }
+       _SEH_END;
+       DbgPrint("\n");
 }
 
-static void set_system_call_gate(unsigned int sel, unsigned int func)
+ULONG STDCALL
+KeRosGetStackFrames ( PULONG Frames, ULONG FrameCount )
+{
+       ULONG Count = 0;
+       PULONG StackBase, StackEnd, Frame;
+       MEMORY_BASIC_INFORMATION mbi;
+       ULONG ResultLength = sizeof(mbi);
+       NTSTATUS Status;
+
+       _SEH_TRY
+       {
+#if defined __GNUC__
+               __asm__("mov %%ebp, %%ebx" : "=b" (Frame) : );
+#elif defined(_MSC_VER)
+               __asm mov [Frame], ebp
+#endif
+
+               Status = MiQueryVirtualMemory (
+                       (HANDLE)-1,
+                       Frame,
+                       MemoryBasicInformation,
+                       &mbi,
+                       sizeof(mbi),
+                       &ResultLength );
+               if ( !NT_SUCCESS(Status) )
+               {
+                       DPRINT1("Can't get stack frames: NtQueryVirtualMemory() failed: %x\n", Status );
+                       return 0;
+               }
+
+               StackBase = Frame;
+               StackEnd = mbi.BaseAddress + mbi.RegionSize;
+
+               while ( Count < FrameCount && Frame >= StackBase && Frame < StackEnd )
+               {
+                       Frames[Count++] = Frame[1];
+                       StackBase = Frame;
+                       Frame = (PULONG)Frame[0];
+               }
+       }
+       _SEH_HANDLE
+       {
+       }
+       _SEH_END;
+       return Count;
+}
+
+static void
+set_system_call_gate(unsigned int sel, unsigned int func)
 {
    DPRINT("sel %x %d\n",sel,sel);
    KiIdt[sel].a = (((int)func)&0xffff) +
@@ -572,7 +792,16 @@ static void set_interrupt_gate(unsigned int sel, unsigned int func)
    DPRINT("set_interrupt_gate(sel %d, func %x)\n",sel,func);
    KiIdt[sel].a = (((int)func)&0xffff) +
      (KERNEL_CS << 16);
-   KiIdt[sel].b = 0x8f00 + (((int)func)&0xffff0000);         
+   KiIdt[sel].b = 0x8e00 + (((int)func)&0xffff0000);
+}
+
+static void set_trap_gate(unsigned int sel, unsigned int func, unsigned int dpl)
+{
+   DPRINT("set_trap_gate(sel %d, func %x, dpl %d)\n",sel, func, dpl);
+   ASSERT(dpl <= 3);
+   KiIdt[sel].a = (((int)func)&0xffff) +
+     (KERNEL_CS << 16);
+   KiIdt[sel].b = 0x8f00 + (dpl << 13) + (((int)func)&0xffff0000);
 }
 
 static void
@@ -582,120 +811,91 @@ set_task_gate(unsigned int sel, unsigned task_sel)
   KiIdt[sel].b = 0x8500;
 }
 
-void KeInitExceptions(void)
+VOID INIT_FUNCTION
+KeInitExceptions(VOID)
 /*
  * FUNCTION: Initalize CPU exception handling
  */
 {
    int i;
-   ULONG base, length;
-   extern USHORT KiGdt[];
-   extern unsigned int trap_stack_top;   
-   extern KTSS KiTss;
-   extern KTSS KiTrapTss;
-   ULONG cr3;
-
-   DPRINT("KeInitExceptions()\n",0);
 
-   __asm__("movl %%cr3,%0\n\t" : "=d" (cr3));
-
-   /*
-    * Set up an a descriptor for the LDT
-    */
-   memset(KiNullLdt, 0, sizeof(KiNullLdt));
-   base = (unsigned int)&KiNullLdt;
-   length = sizeof(KiNullLdt) - 1;
-   
-   KiGdt[(LDT_SELECTOR / 2) + 0] = (length & 0xFFFF);
-   KiGdt[(LDT_SELECTOR / 2) + 1] = (base & 0xFFFF);
-   KiGdt[(LDT_SELECTOR / 2) + 2] = ((base & 0xFF0000) >> 16) | 0x8200;
-   KiGdt[(LDT_SELECTOR / 2) + 3] = ((length & 0xF0000) >> 16) |
-     ((base & 0xFF000000) >> 16);
-
-   /*
-    * Set up a descriptor for the TSS
-    */
-   memset(&KiTss, 0, sizeof(KiTss));
-   base = (unsigned int)&KiTss;
-   length = sizeof(KiTss) - 1;
-         
-   KiGdt[(TSS_SELECTOR / 2) + 0] = (length & 0xFFFF);
-   KiGdt[(TSS_SELECTOR / 2) + 1] = (base & 0xFFFF);
-   KiGdt[(TSS_SELECTOR / 2) + 2] = ((base & 0xFF0000) >> 16) | 0x8900;
-   KiGdt[(TSS_SELECTOR / 2) + 3] = ((length & 0xF0000) >> 16) |
-     ((base & 0xFF000000) >> 16);
-   
-   /*
-    * Initialize the TSS
-    */
-   KiTss.Esp0 = (ULONG)&init_stack_top;
-   KiTss.Ss0 = KERNEL_DS;
-   //   KiTss.IoMapBase = FIELD_OFFSET(KTSS, IoBitmap);
-   KiTss.IoMapBase = 0xFFFF; /* No i/o bitmap */
-   KiTss.IoBitmap[0] = 0xFF;   
-   KiTss.Ldt = LDT_SELECTOR;
-  
-   /*
-    * Load the task register
-    */
-   __asm__("ltr %%ax" 
-          : /* no output */
-           : "a" (TSS_SELECTOR));
-
-   /*
-    * Set up the TSS for handling double faults
-    */
-   memset(&KiTrapTss, 0, sizeof(KiTrapTss));
-   base = (unsigned int)&KiTrapTss;
-   length = sizeof(KiTrapTss) - 1;
-         
-   KiGdt[(TRAP_TSS_SELECTOR / 2) + 0] = (length & 0xFFFF);
-   KiGdt[(TRAP_TSS_SELECTOR / 2) + 1] = (base & 0xFFFF);
-   KiGdt[(TRAP_TSS_SELECTOR / 2) + 2] = ((base & 0xFF0000) >> 16) | 0x8900;
-   KiGdt[(TRAP_TSS_SELECTOR / 2) + 3] = ((length & 0xF0000) >> 16) |
-     ((base & 0xFF000000) >> 16);
-
-   KiTrapTss.Eflags = 0;
-   KiTrapTss.Esp0 = (ULONG)&trap_stack_top;
-   KiTrapTss.Ss0 = KERNEL_DS;
-   KiTrapTss.Esp = (ULONG)&trap_stack_top;
-   KiTrapTss.Cs = KERNEL_CS;
-   KiTrapTss.Eip = (ULONG)KiTrap8;
-   KiTrapTss.Ss = KERNEL_DS;
-   KiTrapTss.Ds = KERNEL_DS;
-   KiTrapTss.Es = KERNEL_DS;
-   KiTrapTss.Fs = PCR_SELECTOR;
-   KiTrapTss.IoMapBase = 0xFFFF; /* No i/o bitmap */
-   KiTrapTss.IoBitmap[0] = 0xFF;   
-   KiTrapTss.Ldt = LDT_SELECTOR;
-   KiTrapTss.Cr3 = cr3;
+   DPRINT("KeInitExceptions()\n");
 
    /*
     * Set up the other gates
     */
-   set_interrupt_gate(0, (ULONG)KiTrap0);
-   set_interrupt_gate(1, (ULONG)KiTrap1);
-   set_interrupt_gate(2, (ULONG)KiTrap2);
-   set_interrupt_gate(3, (ULONG)KiTrap3);
-   set_interrupt_gate(4, (ULONG)KiTrap4);
-   set_interrupt_gate(5, (ULONG)KiTrap5);
-   set_interrupt_gate(6, (ULONG)KiTrap6);
-   set_interrupt_gate(7, (ULONG)KiTrap7);
+   set_trap_gate(0, (ULONG)KiTrap0, 0);
+   set_trap_gate(1, (ULONG)KiTrap1, 0);
+   set_trap_gate(2, (ULONG)KiTrap2, 0);
+   set_trap_gate(3, (ULONG)KiTrap3, 3);
+   set_trap_gate(4, (ULONG)KiTrap4, 0);
+   set_trap_gate(5, (ULONG)KiTrap5, 0);
+   set_trap_gate(6, (ULONG)KiTrap6, 0);
+   set_trap_gate(7, (ULONG)KiTrap7, 0);
    set_task_gate(8, TRAP_TSS_SELECTOR);
-   set_interrupt_gate(9, (ULONG)KiTrap9);
-   set_interrupt_gate(10, (ULONG)KiTrap10);
-   set_interrupt_gate(11, (ULONG)KiTrap11);
-   set_interrupt_gate(12, (ULONG)KiTrap12);
-   set_interrupt_gate(13, (ULONG)KiTrap13);
+   set_trap_gate(9, (ULONG)KiTrap9, 0);
+   set_trap_gate(10, (ULONG)KiTrap10, 0);
+   set_trap_gate(11, (ULONG)KiTrap11, 0);
+   set_trap_gate(12, (ULONG)KiTrap12, 0);
+   set_trap_gate(13, (ULONG)KiTrap13, 0);
    set_interrupt_gate(14, (ULONG)KiTrap14);
-   set_interrupt_gate(15, (ULONG)KiTrap15);
-   set_interrupt_gate(16, (ULONG)KiTrap16);
-   
-   for (i=17;i<256;i++)
-        {
-          set_interrupt_gate(i,(int)KiTrapUnknown);
-        }
-   
+   set_trap_gate(15, (ULONG)KiTrap15, 0);
+   set_trap_gate(16, (ULONG)KiTrap16, 0);
+   set_trap_gate(17, (ULONG)KiTrap17, 0);
+   set_trap_gate(18, (ULONG)KiTrap18, 0);
+   set_trap_gate(19, (ULONG)KiTrap19, 0);
+
+   for (i = 20; i < 256; i++)
+     {
+        set_trap_gate(i,(int)KiTrapUnknown, 0);
+     }
+
    set_system_call_gate(0x2d,(int)interrupt_handler2d);
    set_system_call_gate(0x2e,(int)interrupt_handler2e);
 }
+
+/*
+ * @implemented
+ */
+
+NTSTATUS STDCALL
+KeRaiseUserException(IN NTSTATUS ExceptionCode)
+{
+   /* FIXME: This needs SEH */
+   ULONG OldEip;
+   PKTHREAD Thread = KeGetCurrentThread();
+
+   ProbeForWrite(&Thread->Teb->ExceptionCode, sizeof(NTSTATUS), sizeof(NTSTATUS)); /* NT doesn't check this -- bad? */
+   OldEip = Thread->TrapFrame->Eip;
+   Thread->TrapFrame->Eip = (ULONG_PTR)LdrpGetSystemDllRaiseExceptionDispatcher();
+   Thread->Teb->ExceptionCode = ExceptionCode;
+   return((NTSTATUS)OldEip);
+}
+
+VOID
+FASTCALL
+KeRosTrapReturn ( PKTRAP_FRAME TrapFrame, PKTRAP_FRAME PrevTrapFrame );
+
+/*
+ * @implemented
+ */
+NTSTATUS STDCALL
+NtRaiseException (
+       IN PEXCEPTION_RECORD ExceptionRecord,
+       IN PCONTEXT Context,
+       IN BOOLEAN SearchFrames)
+{
+       PKTRAP_FRAME TrapFrame = KeGetCurrentThread()->TrapFrame;
+       PKTRAP_FRAME PrevTrapFrame = (PKTRAP_FRAME)TrapFrame->Edx;
+
+       KeGetCurrentKPCR()->Tib.ExceptionList = TrapFrame->ExceptionList;
+
+       KiDispatchException(ExceptionRecord,
+               Context,
+               PsGetCurrentThread()->Tcb.TrapFrame,
+               (KPROCESSOR_MODE)ExGetPreviousMode(),
+               SearchFrames);
+
+       KeRosTrapReturn ( TrapFrame, PrevTrapFrame );
+       return(STATUS_SUCCESS);
+}