2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS Kernel
4 * FILE: ntoskrnl/ke/i386/exp.c
5 * PURPOSE: Exception Support Code
6 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
8 * David Welch (welch@cwcom.net)
9 * Skywing (skywing@valhallalegends.com)
14 * - Clean up file (remove all stack functions and use RtlWalkFrameChain/RtlCaptureStackBacktrace)
15 * - Sanitize some context fields.
16 * - Add PSEH handler when an exception occurs in an exception (KiCopyExceptionRecord).
17 * - Forward exceptions to user-mode debugger.
20 /* INCLUDES *****************************************************************/
25 #include <internal/debug.h>
27 #if defined (ALLOC_PRAGMA)
28 #pragma alloc_text(INIT, KeInitExceptions)
34 IN PKTRAP_FRAME TrapFrame
37 extern KIDTENTRY KiIdt
[];
39 /* GLOBALS *****************************************************************/
41 #define FLAG_IF (1<<9)
44 #define STR(x) _STR(x)
47 # define ARRAY_SIZE(x) (sizeof (x) / sizeof (x[0]))
50 extern ULONG init_stack
;
51 extern ULONG init_stack_top
;
53 extern BOOLEAN Ke386NoExecute
;
55 static char *ExceptionTypeStrings
[] =
62 "BOUND range exceeded",
64 "No Math Coprocessor",
68 "Segment Not Present",
69 "Stack Segment Fault",
79 NTSTATUS ExceptionToNtStatus
[] =
81 STATUS_INTEGER_DIVIDE_BY_ZERO
,
83 STATUS_ACCESS_VIOLATION
,
85 STATUS_INTEGER_OVERFLOW
,
86 STATUS_ARRAY_BOUNDS_EXCEEDED
,
87 STATUS_ILLEGAL_INSTRUCTION
,
88 STATUS_FLOAT_INVALID_OPERATION
,
89 STATUS_ACCESS_VIOLATION
,
90 STATUS_ACCESS_VIOLATION
,
91 STATUS_ACCESS_VIOLATION
,
92 STATUS_ACCESS_VIOLATION
,
93 STATUS_STACK_OVERFLOW
,
94 STATUS_ACCESS_VIOLATION
,
95 STATUS_ACCESS_VIOLATION
,
96 STATUS_ACCESS_VIOLATION
, /* RESERVED */
97 STATUS_FLOAT_INVALID_OPERATION
, /* Should not be used, the FPU can give more specific info */
98 STATUS_DATATYPE_MISALIGNMENT
,
99 STATUS_ACCESS_VIOLATION
,
100 STATUS_FLOAT_MULTIPLE_TRAPS
,
103 /* FUNCTIONS ****************************************************************/
106 KiRosPrintAddress(PVOID address
)
108 PLIST_ENTRY current_entry
;
109 PLDR_DATA_TABLE_ENTRY current
;
110 extern LIST_ENTRY ModuleListHead
;
111 ULONG_PTR RelativeAddress
;
116 current_entry
= ModuleListHead
.Flink
;
118 while (current_entry
!= &ModuleListHead
)
121 CONTAINING_RECORD(current_entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
123 if (address
>= (PVOID
)current
->DllBase
&&
124 address
< (PVOID
)((ULONG_PTR
)current
->DllBase
+ current
->SizeOfImage
))
126 RelativeAddress
= (ULONG_PTR
) address
- (ULONG_PTR
) current
->DllBase
;
127 DbgPrint("<%wZ: %x>", ¤t
->FullDllName
, RelativeAddress
);
130 current_entry
= current_entry
->Flink
;
133 address
= (PVOID
)((ULONG_PTR
)address
& ~(ULONG_PTR
)MmSystemRangeStart
);
140 KiKernelTrapHandler(PKTRAP_FRAME Tf
, ULONG ExceptionNr
, PVOID Cr2
)
144 Er
.ExceptionFlags
= 0;
145 Er
.ExceptionRecord
= NULL
;
146 Er
.ExceptionAddress
= (PVOID
)Tf
->Eip
;
148 if (ExceptionNr
== 14)
150 Er
.ExceptionCode
= STATUS_ACCESS_VIOLATION
;
151 Er
.NumberParameters
= 2;
152 Er
.ExceptionInformation
[0] = Tf
->ErrCode
& 0x1;
153 Er
.ExceptionInformation
[1] = (ULONG
)Cr2
;
157 if (ExceptionNr
< ARRAY_SIZE(ExceptionToNtStatus
))
159 Er
.ExceptionCode
= ExceptionToNtStatus
[ExceptionNr
];
163 Er
.ExceptionCode
= STATUS_ACCESS_VIOLATION
;
165 Er
.NumberParameters
= 0;
168 /* FIXME: Which exceptions are noncontinuable? */
169 Er
.ExceptionFlags
= 0;
171 KiDispatchException(&Er
, NULL
, Tf
, KernelMode
, TRUE
);
177 KiDoubleFaultHandler(VOID
)
184 ULONG ExceptionNr
= 8;
190 static PVOID StackTrace
[MM_STACK_SIZE
/ sizeof(PVOID
)];
191 static ULONG StackRepeatCount
[MM_STACK_SIZE
/ sizeof(PVOID
)];
192 static ULONG StackRepeatLength
[MM_STACK_SIZE
/ sizeof(PVOID
)];
197 OldTss
= KeGetCurrentKPCR()->TSS
;
202 if (PsGetCurrentThread() != NULL
&&
203 PsGetCurrentThread()->ThreadsProcess
!= NULL
)
206 PsGetCurrentThread()->ThreadsProcess
->Pcb
.DirectoryTableBase
.QuadPart
;
214 * Check for stack underflow
216 if (PsGetCurrentThread() != NULL
&&
217 Esp0
< (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
)
219 DbgPrint("Stack underflow (tf->esp %x Limit %x)\n",
220 Esp0
, (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
);
225 * Print out the CPU registers
227 if (ExceptionNr
< ARRAY_SIZE(ExceptionTypeStrings
))
229 DbgPrint("%s Exception: %d(%x)\n", ExceptionTypeStrings
[ExceptionNr
],
234 DbgPrint("Exception: %d(%x)\n", ExceptionNr
, 0);
236 DbgPrint("CS:EIP %x:%x ", OldTss
->Cs
, OldTss
->Eip
);
237 KeRosPrintAddress((PVOID
)OldTss
->Eip
);
239 DbgPrint("cr2 %x cr3 %x ", cr2
, OldCr3
);
240 DbgPrint("Proc: %x ",PsGetCurrentProcess());
241 if (PsGetCurrentProcess() != NULL
)
243 DbgPrint("Pid: %x <", PsGetCurrentProcess()->UniqueProcessId
);
244 DbgPrint("%.16s> ", PsGetCurrentProcess()->ImageFileName
);
246 if (PsGetCurrentThread() != NULL
)
248 DbgPrint("Thrd: %x Tid: %x",
249 PsGetCurrentThread(),
250 PsGetCurrentThread()->Cid
.UniqueThread
);
253 DbgPrint("DS %x ES %x FS %x GS %x\n", OldTss
->Ds
, OldTss
->Es
,
254 OldTss
->Fs
, OldTss
->Gs
);
255 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", OldTss
->Eax
, OldTss
->Ebx
,
257 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x\nESP: %.8x ", OldTss
->Edx
,
258 OldTss
->Ebp
, OldTss
->Esi
, Esp0
);
259 DbgPrint("EDI: %.8x EFLAGS: %.8x ", OldTss
->Edi
, OldTss
->Eflags
);
260 if (OldTss
->Cs
== KGDT_R0_CODE
)
262 DbgPrint("kESP %.8x ", Esp0
);
263 if (PsGetCurrentThread() != NULL
)
265 DbgPrint("kernel stack base %x\n",
266 PsGetCurrentThread()->Tcb
.StackLimit
);
272 DbgPrint("User ESP %.8x\n", OldTss
->Esp
);
274 if ((OldTss
->Cs
& 0xffff) == KGDT_R0_CODE
)
276 if (PsGetCurrentThread() != NULL
)
278 StackLimit
= (ULONG
)PsGetCurrentThread()->Tcb
.StackBase
;
279 StackBase
= (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
;
283 StackLimit
= (ULONG
)init_stack_top
;
284 StackBase
= (ULONG
)init_stack
;
288 Change to an #if 0 to reduce the amount of information printed on
289 a recursive stack trace.
292 DbgPrint("Frames: ");
293 Frame
= (PULONG
)OldTss
->Ebp
;
294 while (Frame
!= NULL
&& (ULONG
)Frame
>= StackBase
)
296 KeRosPrintAddress((PVOID
)Frame
[1]);
297 Frame
= (PULONG
)Frame
[0];
301 DbgPrint("Frames: ");
303 Frame
= (PULONG
)OldTss
->Ebp
;
304 while (Frame
!= NULL
&& (ULONG
)Frame
>= StackBase
)
306 StackTrace
[i
] = (PVOID
)Frame
[1];
307 Frame
= (PULONG
)Frame
[0];
313 while (i
< TraceLength
)
315 StackRepeatCount
[i
] = 0;
318 while ((j
- i
) <= (TraceLength
- j
) && FoundRepeat
== FALSE
)
320 if (memcmp(&StackTrace
[i
], &StackTrace
[j
],
321 (j
- i
) * sizeof(PVOID
)) == 0)
323 StackRepeatCount
[i
] = 2;
324 StackRepeatLength
[i
] = j
- i
;
332 if (FoundRepeat
== FALSE
)
337 j
= j
+ StackRepeatLength
[i
];
338 while ((TraceLength
- j
) >= StackRepeatLength
[i
] &&
341 if (memcmp(&StackTrace
[i
], &StackTrace
[j
],
342 StackRepeatLength
[i
] * sizeof(PVOID
)) == 0)
344 StackRepeatCount
[i
]++;
345 j
= j
+ StackRepeatLength
[i
];
356 while (i
< TraceLength
)
358 if (StackRepeatCount
[i
] == 0)
360 KeRosPrintAddress(StackTrace
[i
]);
366 if (StackRepeatLength
[i
] == 0)
370 for (j
= 0; j
< StackRepeatLength
[i
]; j
++)
372 KeRosPrintAddress(StackTrace
[i
+ j
]);
374 DbgPrint("}*%d", StackRepeatCount
[i
]);
375 i
= i
+ StackRepeatLength
[i
] * StackRepeatCount
[i
];
387 KiDumpTrapFrame(PKTRAP_FRAME Tf
, ULONG Parameter1
, ULONG Parameter2
)
392 ULONG ExceptionNr
= (ULONG
)Tf
->DbgArgMark
;
393 ULONG cr2
= (ULONG
)Tf
->DbgArgPointer
;
398 * Print out the CPU registers
400 if (ExceptionNr
< ARRAY_SIZE(ExceptionTypeStrings
))
402 DbgPrint("%s Exception: %d(%x)\n", ExceptionTypeStrings
[ExceptionNr
],
403 ExceptionNr
, Tf
->ErrCode
&0xffff);
407 DbgPrint("Exception: %d(%x)\n", ExceptionNr
, Tf
->ErrCode
&0xffff);
409 DbgPrint("Processor: %d CS:EIP %x:%x ", KeGetCurrentProcessorNumber(),
410 Tf
->SegCs
&0xffff, Tf
->Eip
);
411 KeRosPrintAddress((PVOID
)Tf
->Eip
);
413 Ke386GetPageTableDirectory(cr3_
);
414 DbgPrint("cr2 %x cr3 %x ", cr2
, cr3_
);
415 DbgPrint("Proc: %x ",PsGetCurrentProcess());
416 if (PsGetCurrentProcess() != NULL
)
418 DbgPrint("Pid: %x <", PsGetCurrentProcess()->UniqueProcessId
);
419 DbgPrint("%.16s> ", PsGetCurrentProcess()->ImageFileName
);
421 if (PsGetCurrentThread() != NULL
)
423 DbgPrint("Thrd: %x Tid: %x",
424 PsGetCurrentThread(),
425 PsGetCurrentThread()->Cid
.UniqueThread
);
428 DbgPrint("DS %x ES %x FS %x GS %x\n", Tf
->SegDs
&0xffff, Tf
->SegEs
&0xffff,
429 Tf
->SegFs
&0xffff, Tf
->SegGs
&0xfff);
430 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", Tf
->Eax
, Tf
->Ebx
, Tf
->Ecx
);
431 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x ESP: %.8x\n", Tf
->Edx
,
432 Tf
->Ebp
, Tf
->Esi
, Esp0
);
433 DbgPrint("EDI: %.8x EFLAGS: %.8x ", Tf
->Edi
, Tf
->EFlags
);
434 if ((Tf
->SegCs
&0xffff) == KGDT_R0_CODE
)
436 DbgPrint("kESP %.8x ", Esp0
);
437 if (PsGetCurrentThread() != NULL
)
439 DbgPrint("kernel stack base %x\n",
440 PsGetCurrentThread()->Tcb
.StackLimit
);
445 if (PsGetCurrentThread() != NULL
)
447 StackLimit
= (ULONG
)PsGetCurrentThread()->Tcb
.StackBase
;
451 StackLimit
= (ULONG
)init_stack_top
;
455 * Dump the stack frames
457 KeDumpStackFrames((PULONG
)Tf
->Ebp
);
461 KiTrapHandler(PKTRAP_FRAME Tf
, ULONG ExceptionNr
)
463 * FUNCTION: Called by the lowlevel execption handlers to print an amusing
464 * message and halt the computer
466 * Complete CPU context
473 ASSERT(ExceptionNr
!= 14);
475 /* Use the address of the trap frame as approximation to the ring0 esp */
476 Esp0
= (ULONG
)&Tf
->Eip
;
480 Tf
->DbgArgPointer
= cr2
;
483 * If this was a V86 mode exception then handle it specially
485 if (Tf
->EFlags
& (1 << 17))
487 DPRINT("Tf->Eflags, %x, Tf->Eip %x, ExceptionNr: %d\n", Tf
->EFlags
, Tf
->Eip
, ExceptionNr
);
488 return(KeV86Exception(ExceptionNr
, Tf
, cr2
));
492 * Check for stack underflow, this may be obsolete
494 if (PsGetCurrentThread() != NULL
&&
495 Esp0
< (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
)
497 DPRINT1("Stack underflow (tf->esp %x Limit %x Eip %x)\n",
498 Esp0
, (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
, Tf
->Eip
);
502 if (ExceptionNr
== 15)
506 * This exception should never occur. The P6 has a bug, which does sometimes deliver
507 * the apic spurious interrupt as exception 15. On an athlon64, I get one exception
508 * in the early boot phase in apic mode (using the smp build). I've looked to the linux
509 * sources. Linux does ignore this exception.
512 DPRINT1("Ignoring P6 Local APIC Spurious Interrupt Bug...\n");
517 * Check for a breakpoint that was only for the attention of the debugger.
519 if (ExceptionNr
== 3 && Tf
->Eip
== ((ULONG
)DbgBreakPointNoBugCheck
) + 1)
522 EIP is already adjusted by the processor to point to the instruction
523 after the breakpoint.
529 * Try to handle device-not-present, math-fault and xmm-fault exceptions.
531 if (ExceptionNr
== 7 || ExceptionNr
== 16 || ExceptionNr
== 19)
533 Status
= KiHandleFpuFault(Tf
, ExceptionNr
);
534 if (NT_SUCCESS(Status
))
541 * Handle user exceptions differently
543 if ((Tf
->SegCs
& 0xFFFF) == (KGDT_R3_CODE
| RPL_MASK
))
545 return(KiUserTrapHandler(Tf
, ExceptionNr
, (PVOID
)cr2
));
549 return(KiKernelTrapHandler(Tf
, ExceptionNr
, (PVOID
)cr2
));
555 KiEspFromTrapFrame(IN PKTRAP_FRAME TrapFrame
)
557 /* Check if this is user-mode or V86 */
558 if ((TrapFrame
->SegCs
& MODE_MASK
) || (TrapFrame
->EFlags
& X86_EFLAGS_VM
))
560 /* Return it directly */
561 return TrapFrame
->HardwareEsp
;
566 if (!(TrapFrame
->SegCs
& FRAME_EDITED
))
568 /* Return edited value */
569 return TrapFrame
->TempEsp
;
573 /* Virgin frame, calculate */
574 return (ULONG
)&TrapFrame
->HardwareEsp
;
581 KiEspToTrapFrame(IN PKTRAP_FRAME TrapFrame
,
584 ULONG Previous
= KiEspFromTrapFrame(TrapFrame
);
586 /* Check if this is user-mode or V86 */
587 if ((TrapFrame
->SegCs
& MODE_MASK
) || (TrapFrame
->EFlags
& X86_EFLAGS_VM
))
589 /* Write it directly */
590 TrapFrame
->HardwareEsp
= Esp
;
594 /* Don't allow ESP to be lowered, this is illegal */
597 KeBugCheck(SET_OF_INVALID_CONTEXT
);
600 /* Create an edit frame, check if it was alrady */
601 if (!(TrapFrame
->SegCs
& FRAME_EDITED
))
603 /* Update the value */
604 TrapFrame
->TempEsp
= Esp
;
608 /* Check if ESP changed */
612 TrapFrame
->TempSegCs
= TrapFrame
->SegCs
;
613 TrapFrame
->SegCs
&= ~FRAME_EDITED
;
616 TrapFrame
->TempEsp
= Esp
;
624 KiSsFromTrapFrame(IN PKTRAP_FRAME TrapFrame
)
626 /* If this was V86 Mode */
627 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
630 return TrapFrame
->HardwareSegSs
;
632 else if (TrapFrame
->SegCs
& MODE_MASK
)
634 /* Usermode, return the User SS */
635 return TrapFrame
->HardwareSegSs
| RPL_MASK
;
646 KiSsToTrapFrame(IN PKTRAP_FRAME TrapFrame
,
649 /* Remove the high-bits */
652 /* If this was V86 Mode */
653 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
656 TrapFrame
->HardwareSegSs
= Ss
;
658 else if (TrapFrame
->SegCs
& MODE_MASK
)
660 /* Usermode, save the User SS */
661 TrapFrame
->HardwareSegSs
= Ss
| RPL_MASK
;
667 KeContextToTrapFrame(IN PCONTEXT Context
,
668 IN OUT PKEXCEPTION_FRAME ExceptionFrame
,
669 IN OUT PKTRAP_FRAME TrapFrame
,
670 IN ULONG ContextFlags
,
671 IN KPROCESSOR_MODE PreviousMode
)
673 PFX_SAVE_AREA FxSaveArea
;
674 //ULONG i; Future Use
675 BOOLEAN V86Switch
= FALSE
;
677 /* Start with the basic Registers */
678 if ((ContextFlags
& CONTEXT_CONTROL
) == CONTEXT_CONTROL
)
680 /* Check if we went through a V86 switch */
681 if ((Context
->EFlags
& X86_EFLAGS_VM
) !=
682 (TrapFrame
->EFlags
& X86_EFLAGS_VM
))
684 /* We did, remember this for later */
688 /* Copy EFLAGS. FIXME: Needs to be sanitized */
689 TrapFrame
->EFlags
= Context
->EFlags
;
691 /* Copy EBP and EIP */
692 TrapFrame
->Ebp
= Context
->Ebp
;
693 TrapFrame
->Eip
= Context
->Eip
;
695 /* Check if we were in V86 Mode */
696 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
698 /* Simply copy the CS value */
699 TrapFrame
->SegCs
= Context
->SegCs
;
703 /* We weren't in V86, so sanitize the CS (FIXME!) */
704 TrapFrame
->SegCs
= Context
->SegCs
;
706 /* Don't let it under 8, that's invalid */
707 if ((PreviousMode
!= KernelMode
) && (TrapFrame
->SegCs
< 8))
709 /* Force it to User CS */
710 TrapFrame
->SegCs
= (KGDT_R3_CODE
| RPL_MASK
);
714 /* Handle SS Specially for validation */
715 KiSsToTrapFrame(TrapFrame
, Context
->SegSs
);
717 /* Write ESP back; take into account Edited Trap Frames */
718 KiEspToTrapFrame(TrapFrame
, Context
->Esp
);
720 /* Handle our V86 Bias if we went through a switch */
721 if (V86Switch
) Ki386AdjustEsp0(TrapFrame
);
724 /* Process the Integer Registers */
725 if ((ContextFlags
& CONTEXT_INTEGER
) == CONTEXT_INTEGER
)
727 TrapFrame
->Eax
= Context
->Eax
;
728 TrapFrame
->Ebx
= Context
->Ebx
;
729 TrapFrame
->Ecx
= Context
->Ecx
;
730 TrapFrame
->Edx
= Context
->Edx
;
731 TrapFrame
->Esi
= Context
->Esi
;
732 TrapFrame
->Edi
= Context
->Edi
;
735 /* Process the Context Segments */
736 if ((ContextFlags
& CONTEXT_SEGMENTS
) == CONTEXT_SEGMENTS
)
738 /* Check if we were in V86 Mode */
739 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
741 /* Copy the V86 Segments directlry */
742 TrapFrame
->V86Ds
= Context
->SegDs
;
743 TrapFrame
->V86Es
= Context
->SegEs
;
744 TrapFrame
->V86Fs
= Context
->SegFs
;
745 TrapFrame
->V86Gs
= Context
->SegGs
;
747 else if (!(TrapFrame
->SegCs
& MODE_MASK
))
749 /* For kernel mode, write the standard values */
750 TrapFrame
->SegDs
= KGDT_R3_DATA
| RPL_MASK
;
751 TrapFrame
->SegEs
= KGDT_R3_DATA
| RPL_MASK
;
752 TrapFrame
->SegFs
= Context
->SegFs
;
753 TrapFrame
->SegGs
= 0;
757 /* For user mode, return the values directlry */
758 TrapFrame
->SegDs
= Context
->SegDs
;
759 TrapFrame
->SegEs
= Context
->SegEs
;
760 TrapFrame
->SegFs
= Context
->SegFs
;
762 /* Handle GS specially */
763 if (TrapFrame
->SegCs
== (KGDT_R3_CODE
| RPL_MASK
))
765 /* Don't use it, if user */
766 TrapFrame
->SegGs
= 0;
770 /* Copy it if kernel */
771 TrapFrame
->SegGs
= Context
->SegGs
;
776 /* Handle the extended registers */
777 if (((ContextFlags
& CONTEXT_EXTENDED_REGISTERS
) ==
778 CONTEXT_EXTENDED_REGISTERS
) &&
779 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
781 /* Get the FX Area */
782 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
784 /* Check if NPX is present */
785 if (KeI386NpxPresent
)
791 /* Handle the floating point state */
792 if (((ContextFlags
& CONTEXT_FLOATING_POINT
) ==
793 CONTEXT_FLOATING_POINT
) &&
794 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
796 /* Get the FX Area */
797 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
799 /* Check if NPX is present */
800 if (KeI386NpxPresent
)
810 /* Handle the Debug Registers */
811 if ((ContextFlags
& CONTEXT_DEBUG_REGISTERS
) == CONTEXT_DEBUG_REGISTERS
)
813 /* FIXME: All these should be sanitized */
814 TrapFrame
->Dr0
= Context
->Dr0
;
815 TrapFrame
->Dr1
= Context
->Dr1
;
816 TrapFrame
->Dr2
= Context
->Dr2
;
817 TrapFrame
->Dr3
= Context
->Dr3
;
818 TrapFrame
->Dr6
= Context
->Dr6
;
819 TrapFrame
->Dr7
= Context
->Dr7
;
821 /* Check if usermode */
822 if (PreviousMode
!= KernelMode
)
824 /* Set the Debug Flag */
825 KeGetCurrentThread()->DispatcherHeader
.DebugActive
=
826 (Context
->Dr7
& DR7_ACTIVE
);
830 /* Handle FPU and Extended Registers */
831 KiContextToFxSaveArea((PFX_SAVE_AREA
)(TrapFrame
+ 1), Context
);
836 KeTrapFrameToContext(IN PKTRAP_FRAME TrapFrame
,
837 IN PKEXCEPTION_FRAME ExceptionFrame
,
838 IN OUT PCONTEXT Context
)
840 PFX_SAVE_AREA FxSaveArea
= NULL
;
842 /* Start with the Control flags */
843 if ((Context
->ContextFlags
& CONTEXT_CONTROL
) == CONTEXT_CONTROL
)
845 /* EBP, EIP and EFLAGS */
846 Context
->Ebp
= TrapFrame
->Ebp
;
847 Context
->Eip
= TrapFrame
->Eip
;
848 Context
->EFlags
= TrapFrame
->EFlags
;
850 /* Return the correct CS */
851 if (!(TrapFrame
->SegCs
& FRAME_EDITED
) &&
852 !(TrapFrame
->EFlags
& X86_EFLAGS_VM
))
854 /* Get it from the Temp location */
855 Context
->SegCs
= TrapFrame
->TempSegCs
& 0xFFFF;
859 /* Return it directly */
860 Context
->SegCs
= TrapFrame
->SegCs
& 0xFFFF;
863 /* Get the Ss and ESP */
864 Context
->SegSs
= KiSsFromTrapFrame(TrapFrame
);
865 Context
->Esp
= KiEspFromTrapFrame(TrapFrame
);
868 /* Handle the Segments */
869 if ((Context
->ContextFlags
& CONTEXT_SEGMENTS
) == CONTEXT_SEGMENTS
)
871 /* Do V86 Mode first */
872 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
874 /* Return from the V86 location */
875 Context
->SegGs
= TrapFrame
->V86Gs
& 0xFFFF;
876 Context
->SegFs
= TrapFrame
->V86Fs
& 0xFFFF;
877 Context
->SegEs
= TrapFrame
->V86Es
& 0xFFFF;
878 Context
->SegDs
= TrapFrame
->V86Ds
& 0xFFFF;
882 /* Check if this was a Kernel Trap */
883 if (TrapFrame
->SegCs
== KGDT_R0_CODE
)
885 /* Set valid selectors */
886 TrapFrame
->SegGs
= 0;
887 TrapFrame
->SegFs
= KGDT_R0_PCR
;
888 TrapFrame
->SegEs
= KGDT_R3_DATA
| RPL_MASK
;
889 TrapFrame
->SegDs
= KGDT_R3_DATA
| RPL_MASK
;
892 /* Return the segments */
893 Context
->SegGs
= TrapFrame
->SegGs
& 0xFFFF;
894 Context
->SegFs
= TrapFrame
->SegFs
& 0xFFFF;
895 Context
->SegEs
= TrapFrame
->SegEs
& 0xFFFF;
896 Context
->SegDs
= TrapFrame
->SegDs
& 0xFFFF;
900 /* Handle the simple registers */
901 if ((Context
->ContextFlags
& CONTEXT_INTEGER
) == CONTEXT_INTEGER
)
903 /* Return them directly */
904 Context
->Eax
= TrapFrame
->Eax
;
905 Context
->Ebx
= TrapFrame
->Ebx
;
906 Context
->Ecx
= TrapFrame
->Ecx
;
907 Context
->Edx
= TrapFrame
->Edx
;
908 Context
->Esi
= TrapFrame
->Esi
;
909 Context
->Edi
= TrapFrame
->Edi
;
912 /* Handle extended registers */
913 if (((Context
->ContextFlags
& CONTEXT_EXTENDED_REGISTERS
) ==
914 CONTEXT_EXTENDED_REGISTERS
) &&
915 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
917 /* Get the FX Save Area */
918 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
920 /* Make sure NPX is present */
921 if (KeI386NpxPresent
)
927 FxSaveArea
= KiGetFpuState(KeGetCurrentThread());
928 if (FxSaveArea
!= NULL
)
930 memcpy(Context
->ExtendedRegisters
, &FxSaveArea
->U
.FxArea
,
931 min(sizeof (Context
->ExtendedRegisters
), sizeof (FxSaveArea
->U
.FxArea
)) );
935 Context
->ContextFlags
&= (~CONTEXT_EXTENDED_REGISTERS
) | CONTEXT_i386
;
939 /* Handle Floating Point */
940 if (((Context
->ContextFlags
& CONTEXT_FLOATING_POINT
) ==
941 CONTEXT_FLOATING_POINT
) &&
942 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
944 /* Get the FX Save Area */
945 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
947 /* Make sure we have an NPX */
948 if (KeI386NpxPresent
)
958 FxSaveArea
= KiGetFpuState(KeGetCurrentThread());
959 if (FxSaveArea
!= NULL
)
961 KiFxSaveAreaToFloatingSaveArea(&Context
->FloatSave
, FxSaveArea
);
965 Context
->ContextFlags
&= (~CONTEXT_FLOATING_POINT
) | CONTEXT_i386
;
969 /* Handle debug registers */
970 if ((Context
->ContextFlags
& CONTEXT_DEBUG_REGISTERS
) ==
971 CONTEXT_DEBUG_REGISTERS
)
973 /* Copy the debug registers */
974 Context
->Dr0
= TrapFrame
->Dr0
;
975 Context
->Dr1
= TrapFrame
->Dr1
;
976 Context
->Dr2
= TrapFrame
->Dr2
;
977 Context
->Dr3
= TrapFrame
->Dr3
;
978 Context
->Dr6
= TrapFrame
->Dr6
;
980 /* For user-mode, only set DR7 if a debugger is active */
981 if (((TrapFrame
->SegCs
& MODE_MASK
) ||
982 (TrapFrame
->EFlags
& EFLAGS_V86_MASK
)) &&
983 (KeGetCurrentThread()->DispatcherHeader
.DebugActive
))
986 Context
->Dr7
= TrapFrame
->Dr7
;
998 KeDumpStackFrames(PULONG Frame
)
1000 PULONG StackBase
, StackEnd
;
1001 MEMORY_BASIC_INFORMATION mbi
;
1002 ULONG ResultLength
= sizeof(mbi
);
1005 DbgPrint("Frames:\n");
1008 Status
= MiQueryVirtualMemory (
1011 MemoryBasicInformation
,
1015 if ( !NT_SUCCESS(Status
) )
1017 DPRINT1("Can't dump stack frames: MiQueryVirtualMemory() failed: %x\n", Status
);
1022 StackEnd
= (PULONG
)((ULONG_PTR
)mbi
.BaseAddress
+ mbi
.RegionSize
);
1024 while ( Frame
>= StackBase
&& Frame
< StackEnd
)
1026 ULONG Addr
= Frame
[1];
1027 if (!KeRosPrintAddress((PVOID
)Addr
))
1028 DbgPrint("<%X>", Addr
);
1029 if ( Addr
== 0 || Addr
== 0xDEADBEEF )
1032 Frame
= (PULONG
)Frame
[0];
1044 KeRosDumpStackFrames ( PULONG Frame
, ULONG FrameCount
)
1047 PULONG StackBase
, StackEnd
;
1048 MEMORY_BASIC_INFORMATION mbi
;
1049 ULONG ResultLength
= sizeof(mbi
);
1052 DbgPrint("Frames: ");
1057 #if defined __GNUC__
1058 __asm__("mov %%ebp, %0" : "=r" (Frame
) : );
1059 #elif defined(_MSC_VER)
1060 __asm mov
[Frame
], ebp
1062 //Frame = (PULONG)Frame[0]; // step out of KeRosDumpStackFrames
1065 Status
= MiQueryVirtualMemory (
1068 MemoryBasicInformation
,
1072 if ( !NT_SUCCESS(Status
) )
1074 DPRINT1("Can't dump stack frames: MiQueryVirtualMemory() failed: %x\n", Status
);
1079 StackEnd
= (PULONG
)((ULONG_PTR
)mbi
.BaseAddress
+ mbi
.RegionSize
);
1081 while ( Frame
>= StackBase
&& Frame
< StackEnd
&& i
++ < FrameCount
)
1083 ULONG Addr
= Frame
[1];
1084 if (!KeRosPrintAddress((PVOID
)Addr
))
1085 DbgPrint("<%X>", Addr
);
1086 if ( Addr
== 0 || Addr
== 0xDEADBEEF )
1089 Frame
= (PULONG
)Frame
[0];
1101 KeRosGetStackFrames ( PULONG Frames
, ULONG FrameCount
)
1104 PULONG StackBase
, StackEnd
, Frame
;
1105 MEMORY_BASIC_INFORMATION mbi
;
1106 ULONG ResultLength
= sizeof(mbi
);
1111 #if defined __GNUC__
1112 __asm__("mov %%ebp, %0" : "=r" (Frame
) : );
1113 #elif defined(_MSC_VER)
1114 __asm mov
[Frame
], ebp
1117 Status
= MiQueryVirtualMemory (
1120 MemoryBasicInformation
,
1124 if ( !NT_SUCCESS(Status
) )
1126 DPRINT1("Can't get stack frames: MiQueryVirtualMemory() failed: %x\n", Status
);
1131 StackEnd
= (PULONG
)((ULONG_PTR
)mbi
.BaseAddress
+ mbi
.RegionSize
);
1133 while ( Count
< FrameCount
&& Frame
>= StackBase
&& Frame
< StackEnd
)
1135 Frames
[Count
++] = Frame
[1];
1137 Frame
= (PULONG
)Frame
[0];
1150 KeInitExceptions(VOID
)
1153 USHORT FlippedSelector
;
1156 for (i
= 0; i
<= MAXIMUM_IDTVECTOR
; i
++)
1158 /* Save the current Selector */
1159 FlippedSelector
= KiIdt
[i
].Selector
;
1161 /* Flip Selector and Extended Offset */
1162 KiIdt
[i
].Selector
= KiIdt
[i
].ExtendedOffset
;
1163 KiIdt
[i
].ExtendedOffset
= FlippedSelector
;
1169 KiDispatchException(PEXCEPTION_RECORD ExceptionRecord
,
1170 PKEXCEPTION_FRAME ExceptionFrame
,
1171 PKTRAP_FRAME TrapFrame
,
1172 KPROCESSOR_MODE PreviousMode
,
1173 BOOLEAN FirstChance
)
1176 KD_CONTINUE_TYPE Action
;
1177 ULONG_PTR Stack
, NewStack
;
1179 BOOLEAN UserDispatch
= FALSE
;
1180 DPRINT("KiDispatchException() called\n");
1182 /* Increase number of Exception Dispatches */
1183 KeGetCurrentPrcb()->KeExceptionDispatchCount
++;
1185 /* Set the context flags */
1186 Context
.ContextFlags
= CONTEXT_FULL
| CONTEXT_DEBUG_REGISTERS
;
1188 /* Check if User Mode */
1189 if (PreviousMode
== UserMode
)
1191 /* Add the FPU Flag */
1192 Context
.ContextFlags
|= CONTEXT_FLOATING_POINT
;
1193 if (KeI386FxsrPresent
) Context
.ContextFlags
|= CONTEXT_EXTENDED_REGISTERS
;
1197 KeTrapFrameToContext(TrapFrame
, ExceptionFrame
, &Context
);
1199 /* Handle kernel-mode first, it's simpler */
1200 if (PreviousMode
== KernelMode
)
1202 /* Check if this is a first-chance exception */
1203 if (FirstChance
== TRUE
)
1205 /* Break into the debugger for the first time */
1206 Action
= KdpEnterDebuggerException(ExceptionRecord
,
1213 /* If the debugger said continue, then continue */
1214 if (Action
== kdContinue
) goto Handled
;
1216 /* If the Debugger couldn't handle it, dispatch the exception */
1217 if (RtlDispatchException(ExceptionRecord
, &Context
))
1219 /* It was handled by an exception handler, continue */
1224 /* This is a second-chance exception, only for the debugger */
1225 Action
= KdpEnterDebuggerException(ExceptionRecord
,
1232 /* If the debugger said continue, then continue */
1233 if (Action
== kdContinue
) goto Handled
;
1235 /* Third strike; you're out */
1236 KEBUGCHECKWITHTF(KMODE_EXCEPTION_NOT_HANDLED
,
1237 ExceptionRecord
->ExceptionCode
,
1238 (ULONG_PTR
)ExceptionRecord
->ExceptionAddress
,
1239 ExceptionRecord
->ExceptionInformation
[0],
1240 ExceptionRecord
->ExceptionInformation
[1],
1245 /* User mode exception, was it first-chance? */
1248 /* Enter Debugger if available */
1249 Action
= KdpEnterDebuggerException(ExceptionRecord
,
1256 /* Exit if we're continuing */
1257 if (Action
== kdContinue
) goto Handled
;
1259 /* FIXME: Forward exception to user mode debugger */
1261 /* Set up the user-stack */
1264 /* Align context size and get stack pointer */
1265 Size
= (sizeof(CONTEXT
) + 3) & ~3;
1266 Stack
= (Context
.Esp
& ~3) - Size
;
1267 DPRINT("Stack: %lx\n", Stack
);
1269 /* Probe stack and copy Context */
1270 ProbeForWrite((PVOID
)Stack
, Size
, sizeof(ULONG
));
1271 RtlCopyMemory((PVOID
)Stack
, &Context
, sizeof(CONTEXT
));
1273 /* Align exception record size and get stack pointer */
1274 Size
= (sizeof(EXCEPTION_RECORD
) -
1275 (EXCEPTION_MAXIMUM_PARAMETERS
- ExceptionRecord
->NumberParameters
) *
1276 sizeof(ULONG
) + 3) & ~3;
1277 NewStack
= Stack
- Size
;
1278 DPRINT("NewStack: %lx\n", NewStack
);
1280 /* Probe stack and copy exception record. Don't forget to add the two params */
1281 ProbeForWrite((PVOID
)(NewStack
- 2 * sizeof(ULONG_PTR
)),
1282 Size
+ 2 * sizeof(ULONG_PTR
),
1284 RtlCopyMemory((PVOID
)NewStack
, ExceptionRecord
, Size
);
1286 /* Now write the two params for the user-mode dispatcher */
1287 *(PULONG_PTR
)(NewStack
- 1 * sizeof(ULONG_PTR
)) = Stack
;
1288 *(PULONG_PTR
)(NewStack
- 2 * sizeof(ULONG_PTR
)) = NewStack
;
1290 /* Set new Stack Pointer */
1291 KiEspToTrapFrame(TrapFrame
, NewStack
- 2 * sizeof(ULONG_PTR
));
1293 /* Set EIP to the User-mode Dispathcer */
1294 TrapFrame
->Eip
= (ULONG
)KeUserExceptionDispatcher
;
1295 UserDispatch
= TRUE
;
1300 /* Do second-chance */
1305 /* If we dispatch to user, return now */
1306 if (UserDispatch
) return;
1308 /* FIXME: Forward the exception to the debugger for 2nd chance */
1310 /* 3rd strike, kill the thread */
1311 DPRINT1("Unhandled UserMode exception, terminating thread\n");
1312 ZwTerminateThread(NtCurrentThread(), ExceptionRecord
->ExceptionCode
);
1313 KEBUGCHECKWITHTF(KMODE_EXCEPTION_NOT_HANDLED
,
1314 ExceptionRecord
->ExceptionCode
,
1315 (ULONG_PTR
)ExceptionRecord
->ExceptionAddress
,
1316 ExceptionRecord
->ExceptionInformation
[0],
1317 ExceptionRecord
->ExceptionInformation
[1],
1322 /* Convert the context back into Trap/Exception Frames */
1323 KeContextToTrapFrame(&Context
,
1326 Context
.ContextFlags
,
1336 KeRaiseUserException(IN NTSTATUS ExceptionCode
)
1339 PKTHREAD Thread
= KeGetCurrentThread();
1341 /* Make sure we can access the TEB */
1344 Thread
->Teb
->ExceptionCode
= ExceptionCode
;
1348 return(ExceptionCode
);
1352 /* Get the old EIP */
1353 OldEip
= Thread
->TrapFrame
->Eip
;
1355 /* Change it to the user-mode dispatcher */
1356 Thread
->TrapFrame
->Eip
= (ULONG_PTR
)KeRaiseUserExceptionDispatcher
;
1358 /* Return the old EIP */
1359 return((NTSTATUS
)OldEip
);