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)
31 #define SIZE_OF_FX_REGISTERS 32
36 IN PKTRAP_FRAME TrapFrame
42 IN FLOATING_SAVE_AREA
*SaveArea
45 extern KIDTENTRY KiIdt
[];
47 /* GLOBALS *****************************************************************/
49 #define FLAG_IF (1<<9)
52 #define STR(x) _STR(x)
55 # define ARRAY_SIZE(x) (sizeof (x) / sizeof (x[0]))
58 extern ULONG init_stack
;
59 extern ULONG init_stack_top
;
61 extern BOOLEAN Ke386NoExecute
;
63 static char *ExceptionTypeStrings
[] =
70 "BOUND range exceeded",
72 "No Math Coprocessor",
76 "Segment Not Present",
77 "Stack Segment Fault",
87 NTSTATUS ExceptionToNtStatus
[] =
89 STATUS_INTEGER_DIVIDE_BY_ZERO
,
91 STATUS_ACCESS_VIOLATION
,
93 STATUS_INTEGER_OVERFLOW
,
94 STATUS_ARRAY_BOUNDS_EXCEEDED
,
95 STATUS_ILLEGAL_INSTRUCTION
,
96 STATUS_FLOAT_INVALID_OPERATION
,
97 STATUS_ACCESS_VIOLATION
,
98 STATUS_ACCESS_VIOLATION
,
99 STATUS_ACCESS_VIOLATION
,
100 STATUS_ACCESS_VIOLATION
,
101 STATUS_STACK_OVERFLOW
,
102 STATUS_ACCESS_VIOLATION
,
103 STATUS_ACCESS_VIOLATION
,
104 STATUS_ACCESS_VIOLATION
, /* RESERVED */
105 STATUS_FLOAT_INVALID_OPERATION
, /* Should not be used, the FPU can give more specific info */
106 STATUS_DATATYPE_MISALIGNMENT
,
107 STATUS_ACCESS_VIOLATION
,
108 STATUS_FLOAT_MULTIPLE_TRAPS
,
111 /* FUNCTIONS ****************************************************************/
114 KiRosPrintAddress(PVOID address
)
116 PLIST_ENTRY current_entry
;
117 PLDR_DATA_TABLE_ENTRY current
;
118 extern LIST_ENTRY ModuleListHead
;
119 ULONG_PTR RelativeAddress
;
124 current_entry
= ModuleListHead
.Flink
;
126 while (current_entry
!= &ModuleListHead
)
129 CONTAINING_RECORD(current_entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
131 if (address
>= (PVOID
)current
->DllBase
&&
132 address
< (PVOID
)((ULONG_PTR
)current
->DllBase
+ current
->SizeOfImage
))
134 RelativeAddress
= (ULONG_PTR
) address
- (ULONG_PTR
) current
->DllBase
;
135 DbgPrint("<%wZ: %x>", ¤t
->FullDllName
, RelativeAddress
);
138 current_entry
= current_entry
->Flink
;
141 address
= (PVOID
)((ULONG_PTR
)address
& ~(ULONG_PTR
)MmSystemRangeStart
);
148 KiKernelTrapHandler(PKTRAP_FRAME Tf
, ULONG ExceptionNr
, PVOID Cr2
)
152 Er
.ExceptionFlags
= 0;
153 Er
.ExceptionRecord
= NULL
;
154 Er
.ExceptionAddress
= (PVOID
)Tf
->Eip
;
156 if (ExceptionNr
== 14)
158 Er
.ExceptionCode
= STATUS_ACCESS_VIOLATION
;
159 Er
.NumberParameters
= 2;
160 Er
.ExceptionInformation
[0] = Tf
->ErrCode
& 0x1;
161 Er
.ExceptionInformation
[1] = (ULONG
)Cr2
;
165 if (ExceptionNr
< ARRAY_SIZE(ExceptionToNtStatus
))
167 Er
.ExceptionCode
= ExceptionToNtStatus
[ExceptionNr
];
171 Er
.ExceptionCode
= STATUS_ACCESS_VIOLATION
;
173 Er
.NumberParameters
= 0;
176 /* FIXME: Which exceptions are noncontinuable? */
177 Er
.ExceptionFlags
= 0;
179 KiDispatchException(&Er
, NULL
, Tf
, KernelMode
, TRUE
);
185 KiDoubleFaultHandler(VOID
)
192 ULONG ExceptionNr
= 8;
198 static PVOID StackTrace
[MM_STACK_SIZE
/ sizeof(PVOID
)];
199 static ULONG StackRepeatCount
[MM_STACK_SIZE
/ sizeof(PVOID
)];
200 static ULONG StackRepeatLength
[MM_STACK_SIZE
/ sizeof(PVOID
)];
205 OldTss
= KeGetCurrentKPCR()->TSS
;
210 if (PsGetCurrentThread() != NULL
&&
211 PsGetCurrentThread()->ThreadsProcess
!= NULL
)
214 PsGetCurrentThread()->ThreadsProcess
->Pcb
.DirectoryTableBase
.QuadPart
;
222 * Check for stack underflow
224 if (PsGetCurrentThread() != NULL
&&
225 Esp0
< (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
)
227 DbgPrint("Stack underflow (tf->esp %x Limit %x)\n",
228 Esp0
, (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
);
233 * Print out the CPU registers
235 if (ExceptionNr
< ARRAY_SIZE(ExceptionTypeStrings
))
237 DbgPrint("%s Exception: %d(%x)\n", ExceptionTypeStrings
[ExceptionNr
],
242 DbgPrint("Exception: %d(%x)\n", ExceptionNr
, 0);
244 DbgPrint("CS:EIP %x:%x ", OldTss
->Cs
, OldTss
->Eip
);
245 KeRosPrintAddress((PVOID
)OldTss
->Eip
);
247 DbgPrint("cr2 %x cr3 %x ", cr2
, OldCr3
);
248 DbgPrint("Proc: %x ",PsGetCurrentProcess());
249 if (PsGetCurrentProcess() != NULL
)
251 DbgPrint("Pid: %x <", PsGetCurrentProcess()->UniqueProcessId
);
252 DbgPrint("%.16s> ", PsGetCurrentProcess()->ImageFileName
);
254 if (PsGetCurrentThread() != NULL
)
256 DbgPrint("Thrd: %x Tid: %x",
257 PsGetCurrentThread(),
258 PsGetCurrentThread()->Cid
.UniqueThread
);
261 DbgPrint("DS %x ES %x FS %x GS %x\n", OldTss
->Ds
, OldTss
->Es
,
262 OldTss
->Fs
, OldTss
->Gs
);
263 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", OldTss
->Eax
, OldTss
->Ebx
,
265 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x\nESP: %.8x ", OldTss
->Edx
,
266 OldTss
->Ebp
, OldTss
->Esi
, Esp0
);
267 DbgPrint("EDI: %.8x EFLAGS: %.8x ", OldTss
->Edi
, OldTss
->Eflags
);
268 if (OldTss
->Cs
== KGDT_R0_CODE
)
270 DbgPrint("kESP %.8x ", Esp0
);
271 if (PsGetCurrentThread() != NULL
)
273 DbgPrint("kernel stack base %x\n",
274 PsGetCurrentThread()->Tcb
.StackLimit
);
280 DbgPrint("User ESP %.8x\n", OldTss
->Esp
);
282 if ((OldTss
->Cs
& 0xffff) == KGDT_R0_CODE
)
284 if (PsGetCurrentThread() != NULL
)
286 StackLimit
= (ULONG
)PsGetCurrentThread()->Tcb
.StackBase
;
287 StackBase
= (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
;
291 StackLimit
= (ULONG
)init_stack_top
;
292 StackBase
= (ULONG
)init_stack
;
296 Change to an #if 0 to reduce the amount of information printed on
297 a recursive stack trace.
300 DbgPrint("Frames: ");
301 Frame
= (PULONG
)OldTss
->Ebp
;
302 while (Frame
!= NULL
&& (ULONG
)Frame
>= StackBase
)
304 KeRosPrintAddress((PVOID
)Frame
[1]);
305 Frame
= (PULONG
)Frame
[0];
309 DbgPrint("Frames: ");
311 Frame
= (PULONG
)OldTss
->Ebp
;
312 while (Frame
!= NULL
&& (ULONG
)Frame
>= StackBase
)
314 StackTrace
[i
] = (PVOID
)Frame
[1];
315 Frame
= (PULONG
)Frame
[0];
321 while (i
< TraceLength
)
323 StackRepeatCount
[i
] = 0;
326 while ((j
- i
) <= (TraceLength
- j
) && FoundRepeat
== FALSE
)
328 if (memcmp(&StackTrace
[i
], &StackTrace
[j
],
329 (j
- i
) * sizeof(PVOID
)) == 0)
331 StackRepeatCount
[i
] = 2;
332 StackRepeatLength
[i
] = j
- i
;
340 if (FoundRepeat
== FALSE
)
345 j
= j
+ StackRepeatLength
[i
];
346 while ((TraceLength
- j
) >= StackRepeatLength
[i
] &&
349 if (memcmp(&StackTrace
[i
], &StackTrace
[j
],
350 StackRepeatLength
[i
] * sizeof(PVOID
)) == 0)
352 StackRepeatCount
[i
]++;
353 j
= j
+ StackRepeatLength
[i
];
364 while (i
< TraceLength
)
366 if (StackRepeatCount
[i
] == 0)
368 KeRosPrintAddress(StackTrace
[i
]);
374 if (StackRepeatLength
[i
] == 0)
378 for (j
= 0; j
< StackRepeatLength
[i
]; j
++)
380 KeRosPrintAddress(StackTrace
[i
+ j
]);
382 DbgPrint("}*%d", StackRepeatCount
[i
]);
383 i
= i
+ StackRepeatLength
[i
] * StackRepeatCount
[i
];
395 KiDumpTrapFrame(PKTRAP_FRAME Tf
, ULONG Parameter1
, ULONG Parameter2
)
400 ULONG ExceptionNr
= (ULONG
)Tf
->DbgArgMark
;
401 ULONG cr2
= (ULONG
)Tf
->DbgArgPointer
;
406 * Print out the CPU registers
408 if (ExceptionNr
< ARRAY_SIZE(ExceptionTypeStrings
))
410 DbgPrint("%s Exception: %d(%x)\n", ExceptionTypeStrings
[ExceptionNr
],
411 ExceptionNr
, Tf
->ErrCode
&0xffff);
415 DbgPrint("Exception: %d(%x)\n", ExceptionNr
, Tf
->ErrCode
&0xffff);
417 DbgPrint("Processor: %d CS:EIP %x:%x ", KeGetCurrentProcessorNumber(),
418 Tf
->SegCs
&0xffff, Tf
->Eip
);
419 KeRosPrintAddress((PVOID
)Tf
->Eip
);
421 Ke386GetPageTableDirectory(cr3_
);
422 DbgPrint("cr2 %x cr3 %x ", cr2
, cr3_
);
423 DbgPrint("Proc: %x ",PsGetCurrentProcess());
424 if (PsGetCurrentProcess() != NULL
)
426 DbgPrint("Pid: %x <", PsGetCurrentProcess()->UniqueProcessId
);
427 DbgPrint("%.16s> ", PsGetCurrentProcess()->ImageFileName
);
429 if (PsGetCurrentThread() != NULL
)
431 DbgPrint("Thrd: %x Tid: %x",
432 PsGetCurrentThread(),
433 PsGetCurrentThread()->Cid
.UniqueThread
);
436 DbgPrint("DS %x ES %x FS %x GS %x\n", Tf
->SegDs
&0xffff, Tf
->SegEs
&0xffff,
437 Tf
->SegFs
&0xffff, Tf
->SegGs
&0xfff);
438 DbgPrint("EAX: %.8x EBX: %.8x ECX: %.8x\n", Tf
->Eax
, Tf
->Ebx
, Tf
->Ecx
);
439 DbgPrint("EDX: %.8x EBP: %.8x ESI: %.8x ESP: %.8x\n", Tf
->Edx
,
440 Tf
->Ebp
, Tf
->Esi
, Esp0
);
441 DbgPrint("EDI: %.8x EFLAGS: %.8x ", Tf
->Edi
, Tf
->EFlags
);
442 if ((Tf
->SegCs
&0xffff) == KGDT_R0_CODE
)
444 DbgPrint("kESP %.8x ", Esp0
);
445 if (PsGetCurrentThread() != NULL
)
447 DbgPrint("kernel stack base %x\n",
448 PsGetCurrentThread()->Tcb
.StackLimit
);
453 if (PsGetCurrentThread() != NULL
)
455 StackLimit
= (ULONG
)PsGetCurrentThread()->Tcb
.StackBase
;
459 StackLimit
= (ULONG
)init_stack_top
;
463 * Dump the stack frames
465 KeDumpStackFrames((PULONG
)Tf
->Ebp
);
469 KiTrapHandler(PKTRAP_FRAME Tf
, ULONG ExceptionNr
)
471 * FUNCTION: Called by the lowlevel execption handlers to print an amusing
472 * message and halt the computer
474 * Complete CPU context
480 ASSERT(ExceptionNr
!= 14);
481 ASSERT((ExceptionNr
!= 7 && ExceptionNr
!= 16 && ExceptionNr
!= 19));
483 /* Use the address of the trap frame as approximation to the ring0 esp */
484 Esp0
= (ULONG
)&Tf
->Eip
;
488 Tf
->DbgArgPointer
= cr2
;
491 * If this was a V86 mode exception then handle it specially
493 if (Tf
->EFlags
& (1 << 17))
495 DPRINT("Tf->Eflags, %x, Tf->Eip %x, ExceptionNr: %d\n", Tf
->EFlags
, Tf
->Eip
, ExceptionNr
);
496 return(KeV86Exception(ExceptionNr
, Tf
, cr2
));
500 * Check for stack underflow, this may be obsolete
502 if (PsGetCurrentThread() != NULL
&&
503 Esp0
< (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
)
505 DPRINT1("Stack underflow (tf->esp %x Limit %x Eip %x)\n",
506 Esp0
, (ULONG
)PsGetCurrentThread()->Tcb
.StackLimit
, Tf
->Eip
);
510 if (ExceptionNr
== 15)
514 * This exception should never occur. The P6 has a bug, which does sometimes deliver
515 * the apic spurious interrupt as exception 15. On an athlon64, I get one exception
516 * in the early boot phase in apic mode (using the smp build). I've looked to the linux
517 * sources. Linux does ignore this exception.
520 DPRINT1("Ignoring P6 Local APIC Spurious Interrupt Bug...\n");
525 * Check for a breakpoint that was only for the attention of the debugger.
527 if (ExceptionNr
== 3 && Tf
->Eip
== ((ULONG
)DbgBreakPointNoBugCheck
) + 1)
530 EIP is already adjusted by the processor to point to the instruction
531 after the breakpoint.
537 * Handle user exceptions differently
539 if ((Tf
->SegCs
& 0xFFFF) == (KGDT_R3_CODE
| RPL_MASK
))
541 return(KiUserTrapHandler(Tf
, ExceptionNr
, (PVOID
)cr2
));
545 return(KiKernelTrapHandler(Tf
, ExceptionNr
, (PVOID
)cr2
));
551 KiEspFromTrapFrame(IN PKTRAP_FRAME TrapFrame
)
553 /* Check if this is user-mode or V86 */
554 if ((TrapFrame
->SegCs
& MODE_MASK
) || (TrapFrame
->EFlags
& X86_EFLAGS_VM
))
556 /* Return it directly */
557 return TrapFrame
->HardwareEsp
;
562 if (!(TrapFrame
->SegCs
& FRAME_EDITED
))
564 /* Return edited value */
565 return TrapFrame
->TempEsp
;
569 /* Virgin frame, calculate */
570 return (ULONG
)&TrapFrame
->HardwareEsp
;
577 KiEspToTrapFrame(IN PKTRAP_FRAME TrapFrame
,
580 ULONG Previous
= KiEspFromTrapFrame(TrapFrame
);
582 /* Check if this is user-mode or V86 */
583 if ((TrapFrame
->SegCs
& MODE_MASK
) || (TrapFrame
->EFlags
& X86_EFLAGS_VM
))
585 /* Write it directly */
586 TrapFrame
->HardwareEsp
= Esp
;
590 /* Don't allow ESP to be lowered, this is illegal */
593 KeBugCheck(SET_OF_INVALID_CONTEXT
);
596 /* Create an edit frame, check if it was alrady */
597 if (!(TrapFrame
->SegCs
& FRAME_EDITED
))
599 /* Update the value */
600 TrapFrame
->TempEsp
= Esp
;
604 /* Check if ESP changed */
608 TrapFrame
->TempSegCs
= TrapFrame
->SegCs
;
609 TrapFrame
->SegCs
&= ~FRAME_EDITED
;
612 TrapFrame
->TempEsp
= Esp
;
620 KiSsFromTrapFrame(IN PKTRAP_FRAME TrapFrame
)
622 /* If this was V86 Mode */
623 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
626 return TrapFrame
->HardwareSegSs
;
628 else if (TrapFrame
->SegCs
& MODE_MASK
)
630 /* Usermode, return the User SS */
631 return TrapFrame
->HardwareSegSs
| RPL_MASK
;
642 KiSsToTrapFrame(IN PKTRAP_FRAME TrapFrame
,
645 /* Remove the high-bits */
648 /* If this was V86 Mode */
649 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
652 TrapFrame
->HardwareSegSs
= Ss
;
654 else if (TrapFrame
->SegCs
& MODE_MASK
)
656 /* Usermode, save the User SS */
657 TrapFrame
->HardwareSegSs
= Ss
| RPL_MASK
;
663 KiTagWordFnsaveToFxsave(USHORT TagWord
)
665 INT FxTagWord
= ~TagWord
;
668 * Empty is now 00, any 2 bits containing 1 mean valid
669 * Now convert the rest (11->0 and the rest to 1)
671 FxTagWord
= (FxTagWord
| (FxTagWord
>> 1)) & 0x5555; /* 0V0V0V0V0V0V0V0V */
672 FxTagWord
= (FxTagWord
| (FxTagWord
>> 1)) & 0x3333; /* 00VV00VV00VV00VV */
673 FxTagWord
= (FxTagWord
| (FxTagWord
>> 2)) & 0x0f0f; /* 0000VVVV0000VVVV */
674 FxTagWord
= (FxTagWord
| (FxTagWord
>> 4)) & 0x00ff; /* 00000000VVVVVVVV */
680 KeContextToTrapFrame(IN PCONTEXT Context
,
681 IN OUT PKEXCEPTION_FRAME ExceptionFrame
,
682 IN OUT PKTRAP_FRAME TrapFrame
,
683 IN ULONG ContextFlags
,
684 IN KPROCESSOR_MODE PreviousMode
)
686 PFX_SAVE_AREA FxSaveArea
;
688 BOOLEAN V86Switch
= FALSE
;
690 /* Start with the basic Registers */
691 if ((ContextFlags
& CONTEXT_CONTROL
) == CONTEXT_CONTROL
)
693 /* Check if we went through a V86 switch */
694 if ((Context
->EFlags
& X86_EFLAGS_VM
) !=
695 (TrapFrame
->EFlags
& X86_EFLAGS_VM
))
697 /* We did, remember this for later */
701 /* Copy EFLAGS. FIXME: Needs to be sanitized */
702 TrapFrame
->EFlags
= Context
->EFlags
;
704 /* Copy EBP and EIP */
705 TrapFrame
->Ebp
= Context
->Ebp
;
706 TrapFrame
->Eip
= Context
->Eip
;
708 /* Check if we were in V86 Mode */
709 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
711 /* Simply copy the CS value */
712 TrapFrame
->SegCs
= Context
->SegCs
;
716 /* We weren't in V86, so sanitize the CS (FIXME!) */
717 TrapFrame
->SegCs
= Context
->SegCs
;
719 /* Don't let it under 8, that's invalid */
720 if ((PreviousMode
!= KernelMode
) && (TrapFrame
->SegCs
< 8))
722 /* Force it to User CS */
723 TrapFrame
->SegCs
= (KGDT_R3_CODE
| RPL_MASK
);
727 /* Handle SS Specially for validation */
728 KiSsToTrapFrame(TrapFrame
, Context
->SegSs
);
730 /* Write ESP back; take into account Edited Trap Frames */
731 KiEspToTrapFrame(TrapFrame
, Context
->Esp
);
733 /* Handle our V86 Bias if we went through a switch */
734 if (V86Switch
) Ki386AdjustEsp0(TrapFrame
);
737 /* Process the Integer Registers */
738 if ((ContextFlags
& CONTEXT_INTEGER
) == CONTEXT_INTEGER
)
740 TrapFrame
->Eax
= Context
->Eax
;
741 TrapFrame
->Ebx
= Context
->Ebx
;
742 TrapFrame
->Ecx
= Context
->Ecx
;
743 TrapFrame
->Edx
= Context
->Edx
;
744 TrapFrame
->Esi
= Context
->Esi
;
745 TrapFrame
->Edi
= Context
->Edi
;
748 /* Process the Context Segments */
749 if ((ContextFlags
& CONTEXT_SEGMENTS
) == CONTEXT_SEGMENTS
)
751 /* Check if we were in V86 Mode */
752 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
754 /* Copy the V86 Segments directlry */
755 TrapFrame
->V86Ds
= Context
->SegDs
;
756 TrapFrame
->V86Es
= Context
->SegEs
;
757 TrapFrame
->V86Fs
= Context
->SegFs
;
758 TrapFrame
->V86Gs
= Context
->SegGs
;
760 else if (!(TrapFrame
->SegCs
& MODE_MASK
))
762 /* For kernel mode, write the standard values */
763 TrapFrame
->SegDs
= KGDT_R3_DATA
| RPL_MASK
;
764 TrapFrame
->SegEs
= KGDT_R3_DATA
| RPL_MASK
;
765 TrapFrame
->SegFs
= Context
->SegFs
;
766 TrapFrame
->SegGs
= 0;
770 /* For user mode, return the values directlry */
771 TrapFrame
->SegDs
= Context
->SegDs
;
772 TrapFrame
->SegEs
= Context
->SegEs
;
773 TrapFrame
->SegFs
= Context
->SegFs
;
775 /* Handle GS specially */
776 if (TrapFrame
->SegCs
== (KGDT_R3_CODE
| RPL_MASK
))
778 /* Don't use it, if user */
779 TrapFrame
->SegGs
= 0;
783 /* Copy it if kernel */
784 TrapFrame
->SegGs
= Context
->SegGs
;
789 /* Handle the extended registers */
790 if (((ContextFlags
& CONTEXT_EXTENDED_REGISTERS
) ==
791 CONTEXT_EXTENDED_REGISTERS
) &&
792 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
794 /* Get the FX Area */
795 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
797 /* Check if NPX is present */
798 if (KeI386NpxPresent
)
800 /* Flush the NPX State */
801 KiFlushNPXState(NULL
);
803 /* Copy the FX State */
804 RtlCopyMemory(&FxSaveArea
->U
.FxArea
,
805 &Context
->ExtendedRegisters
[0],
806 MAXIMUM_SUPPORTED_EXTENSION
);
808 /* Remove reserved bits from MXCSR */
809 FxSaveArea
->U
.FxArea
.MXCsr
&= ~0xFFBF;
811 /* Mask out any invalid flags */
812 FxSaveArea
->Cr0NpxState
&= ~(CR0_EM
| CR0_MP
| CR0_TS
);
814 /* FIXME: Check if this is a VDM app */
818 /* Handle the floating point state */
819 if (((ContextFlags
& CONTEXT_FLOATING_POINT
) ==
820 CONTEXT_FLOATING_POINT
) &&
821 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
823 /* Get the FX Area */
824 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
826 /* Check if NPX is present */
827 if (KeI386NpxPresent
)
829 /* Flush the NPX State */
830 KiFlushNPXState(NULL
);
832 /* Check if we have Fxsr support */
833 if (KeI386FxsrPresent
)
835 /* Convert the Fn Floating Point state to Fx */
836 FxSaveArea
->U
.FxArea
.ControlWord
=
837 (USHORT
)Context
->FloatSave
.ControlWord
;
838 FxSaveArea
->U
.FxArea
.StatusWord
=
839 (USHORT
)Context
->FloatSave
.StatusWord
;
840 FxSaveArea
->U
.FxArea
.TagWord
=
841 KiTagWordFnsaveToFxsave((USHORT
)Context
->FloatSave
.TagWord
);
842 FxSaveArea
->U
.FxArea
.ErrorOpcode
=
843 (USHORT
)(Context
->FloatSave
.ErrorSelector
>> 16);
844 FxSaveArea
->U
.FxArea
.ErrorOffset
=
845 Context
->FloatSave
.ErrorOffset
;
846 FxSaveArea
->U
.FxArea
.ErrorSelector
=
847 Context
->FloatSave
.ErrorSelector
& 0xFFFF;
848 FxSaveArea
->U
.FxArea
.DataOffset
=
849 Context
->FloatSave
.DataOffset
;
850 FxSaveArea
->U
.FxArea
.DataSelector
=
851 Context
->FloatSave
.DataSelector
& 0xFFFF;
853 /* Clear out the Register Area */
854 RtlZeroMemory(&FxSaveArea
->U
.FxArea
.RegisterArea
[0], SIZE_OF_FX_REGISTERS
);
856 /* Loop the 8 floating point registers */
857 for (i
= 0; i
< 8; i
++)
859 /* Copy from Fn to Fx */
860 RtlCopyMemory(FxSaveArea
->U
.FxArea
.RegisterArea
+ (i
* 16),
861 Context
->FloatSave
.RegisterArea
+ (i
* 10),
867 /* Just dump the Fn state in */
868 RtlCopyMemory(&FxSaveArea
->U
.FnArea
,
870 sizeof(FNSAVE_FORMAT
));
873 /* Mask out any invalid flags */
874 FxSaveArea
->Cr0NpxState
&= ~(CR0_EM
| CR0_MP
| CR0_TS
);
876 /* FIXME: Check if this is a VDM app */
880 /* FIXME: Handle FPU Emulation */
884 /* Handle the Debug Registers */
885 if ((ContextFlags
& CONTEXT_DEBUG_REGISTERS
) == CONTEXT_DEBUG_REGISTERS
)
887 /* FIXME: All these should be sanitized */
888 TrapFrame
->Dr0
= Context
->Dr0
;
889 TrapFrame
->Dr1
= Context
->Dr1
;
890 TrapFrame
->Dr2
= Context
->Dr2
;
891 TrapFrame
->Dr3
= Context
->Dr3
;
892 TrapFrame
->Dr6
= Context
->Dr6
;
893 TrapFrame
->Dr7
= Context
->Dr7
;
895 /* Check if usermode */
896 if (PreviousMode
!= KernelMode
)
898 /* Set the Debug Flag */
899 KeGetCurrentThread()->DispatcherHeader
.DebugActive
=
900 (Context
->Dr7
& DR7_ACTIVE
);
907 KeTrapFrameToContext(IN PKTRAP_FRAME TrapFrame
,
908 IN PKEXCEPTION_FRAME ExceptionFrame
,
909 IN OUT PCONTEXT Context
)
911 PFX_SAVE_AREA FxSaveArea
;
915 FLOATING_SAVE_AREA UnalignedArea
;
917 FLOATING_SAVE_AREA
*FloatSaveArea
;
919 /* Start with the Control flags */
920 if ((Context
->ContextFlags
& CONTEXT_CONTROL
) == CONTEXT_CONTROL
)
922 /* EBP, EIP and EFLAGS */
923 Context
->Ebp
= TrapFrame
->Ebp
;
924 Context
->Eip
= TrapFrame
->Eip
;
925 Context
->EFlags
= TrapFrame
->EFlags
;
927 /* Return the correct CS */
928 if (!(TrapFrame
->SegCs
& FRAME_EDITED
) &&
929 !(TrapFrame
->EFlags
& X86_EFLAGS_VM
))
931 /* Get it from the Temp location */
932 Context
->SegCs
= TrapFrame
->TempSegCs
& 0xFFFF;
936 /* Return it directly */
937 Context
->SegCs
= TrapFrame
->SegCs
& 0xFFFF;
940 /* Get the Ss and ESP */
941 Context
->SegSs
= KiSsFromTrapFrame(TrapFrame
);
942 Context
->Esp
= KiEspFromTrapFrame(TrapFrame
);
945 /* Handle the Segments */
946 if ((Context
->ContextFlags
& CONTEXT_SEGMENTS
) == CONTEXT_SEGMENTS
)
948 /* Do V86 Mode first */
949 if (TrapFrame
->EFlags
& X86_EFLAGS_VM
)
951 /* Return from the V86 location */
952 Context
->SegGs
= TrapFrame
->V86Gs
& 0xFFFF;
953 Context
->SegFs
= TrapFrame
->V86Fs
& 0xFFFF;
954 Context
->SegEs
= TrapFrame
->V86Es
& 0xFFFF;
955 Context
->SegDs
= TrapFrame
->V86Ds
& 0xFFFF;
959 /* Check if this was a Kernel Trap */
960 if (TrapFrame
->SegCs
== KGDT_R0_CODE
)
962 /* Set valid selectors */
963 TrapFrame
->SegGs
= 0;
964 TrapFrame
->SegFs
= KGDT_R0_PCR
;
965 TrapFrame
->SegEs
= KGDT_R3_DATA
| RPL_MASK
;
966 TrapFrame
->SegDs
= KGDT_R3_DATA
| RPL_MASK
;
969 /* Return the segments */
970 Context
->SegGs
= TrapFrame
->SegGs
& 0xFFFF;
971 Context
->SegFs
= TrapFrame
->SegFs
& 0xFFFF;
972 Context
->SegEs
= TrapFrame
->SegEs
& 0xFFFF;
973 Context
->SegDs
= TrapFrame
->SegDs
& 0xFFFF;
977 /* Handle the simple registers */
978 if ((Context
->ContextFlags
& CONTEXT_INTEGER
) == CONTEXT_INTEGER
)
980 /* Return them directly */
981 Context
->Eax
= TrapFrame
->Eax
;
982 Context
->Ebx
= TrapFrame
->Ebx
;
983 Context
->Ecx
= TrapFrame
->Ecx
;
984 Context
->Edx
= TrapFrame
->Edx
;
985 Context
->Esi
= TrapFrame
->Esi
;
986 Context
->Edi
= TrapFrame
->Edi
;
989 /* Handle extended registers */
990 if (((Context
->ContextFlags
& CONTEXT_EXTENDED_REGISTERS
) ==
991 CONTEXT_EXTENDED_REGISTERS
) &&
992 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
994 /* Get the FX Save Area */
995 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
997 /* Make sure NPX is present */
998 if (KeI386NpxPresent
)
1000 /* Flush the NPX State */
1001 KiFlushNPXState(NULL
);
1003 /* Copy the registers */
1004 RtlCopyMemory(&Context
->ExtendedRegisters
[0],
1005 &FxSaveArea
->U
.FxArea
,
1006 MAXIMUM_SUPPORTED_EXTENSION
);
1010 /* Handle Floating Point */
1011 if (((Context
->ContextFlags
& CONTEXT_FLOATING_POINT
) ==
1012 CONTEXT_FLOATING_POINT
) &&
1013 ((TrapFrame
->SegCs
& MODE_MASK
) == UserMode
))
1015 /* Get the FX Save Area */
1016 FxSaveArea
= (PFX_SAVE_AREA
)(TrapFrame
+ 1);
1018 /* Make sure we have an NPX */
1019 if (KeI386NpxPresent
)
1021 /* Check if we have Fxsr support */
1022 if (KeI386FxsrPresent
)
1024 /* Align the floating area to 16-bytes */
1025 FloatSaveArea
= (FLOATING_SAVE_AREA
*)
1026 ((ULONG_PTR
)&FloatSaveBuffer
.UnalignedArea
&~ 0xF);
1029 KiFlushNPXState(FloatSaveArea
);
1033 /* We don't, use the FN area and flush the NPX State */
1034 FloatSaveArea
= (FLOATING_SAVE_AREA
*)&FxSaveArea
->U
.FnArea
;
1035 KiFlushNPXState(NULL
);
1038 /* Copy into the Context */
1039 RtlCopyMemory(&Context
->FloatSave
,
1040 &FxSaveArea
->U
.FnArea
,
1041 sizeof(FNSAVE_FORMAT
));
1045 /* FIXME: Handle Emulation */
1046 Context
->ContextFlags
&= (~CONTEXT_FLOATING_POINT
) | CONTEXT_i386
;
1050 /* Handle debug registers */
1051 if ((Context
->ContextFlags
& CONTEXT_DEBUG_REGISTERS
) ==
1052 CONTEXT_DEBUG_REGISTERS
)
1054 /* Copy the debug registers */
1055 Context
->Dr0
= TrapFrame
->Dr0
;
1056 Context
->Dr1
= TrapFrame
->Dr1
;
1057 Context
->Dr2
= TrapFrame
->Dr2
;
1058 Context
->Dr3
= TrapFrame
->Dr3
;
1059 Context
->Dr6
= TrapFrame
->Dr6
;
1061 /* For user-mode, only set DR7 if a debugger is active */
1062 if (((TrapFrame
->SegCs
& MODE_MASK
) ||
1063 (TrapFrame
->EFlags
& EFLAGS_V86_MASK
)) &&
1064 (KeGetCurrentThread()->DispatcherHeader
.DebugActive
))
1067 Context
->Dr7
= TrapFrame
->Dr7
;
1079 KeDumpStackFrames(PULONG Frame
)
1081 PULONG StackBase
, StackEnd
;
1082 MEMORY_BASIC_INFORMATION mbi
;
1083 ULONG ResultLength
= sizeof(mbi
);
1086 DbgPrint("Frames:\n");
1089 Status
= MiQueryVirtualMemory (
1092 MemoryBasicInformation
,
1096 if ( !NT_SUCCESS(Status
) )
1098 DPRINT1("Can't dump stack frames: MiQueryVirtualMemory() failed: %x\n", Status
);
1103 StackEnd
= (PULONG
)((ULONG_PTR
)mbi
.BaseAddress
+ mbi
.RegionSize
);
1105 while ( Frame
>= StackBase
&& Frame
< StackEnd
)
1107 ULONG Addr
= Frame
[1];
1108 if (!KeRosPrintAddress((PVOID
)Addr
))
1109 DbgPrint("<%X>", Addr
);
1110 if ( Addr
== 0 || Addr
== 0xDEADBEEF )
1113 Frame
= (PULONG
)Frame
[0];
1125 KeRosDumpStackFrames ( PULONG Frame
, ULONG FrameCount
)
1128 PULONG StackBase
, StackEnd
;
1129 MEMORY_BASIC_INFORMATION mbi
;
1130 ULONG ResultLength
= sizeof(mbi
);
1133 DbgPrint("Frames: ");
1138 #if defined __GNUC__
1139 __asm__("mov %%ebp, %0" : "=r" (Frame
) : );
1140 #elif defined(_MSC_VER)
1141 __asm mov
[Frame
], ebp
1143 //Frame = (PULONG)Frame[0]; // step out of KeRosDumpStackFrames
1146 Status
= MiQueryVirtualMemory (
1149 MemoryBasicInformation
,
1153 if ( !NT_SUCCESS(Status
) )
1155 DPRINT1("Can't dump stack frames: MiQueryVirtualMemory() failed: %x\n", Status
);
1160 StackEnd
= (PULONG
)((ULONG_PTR
)mbi
.BaseAddress
+ mbi
.RegionSize
);
1162 while ( Frame
>= StackBase
&& Frame
< StackEnd
&& i
++ < FrameCount
)
1164 ULONG Addr
= Frame
[1];
1165 if (!KeRosPrintAddress((PVOID
)Addr
))
1166 DbgPrint("<%X>", Addr
);
1167 if ( Addr
== 0 || Addr
== 0xDEADBEEF )
1170 Frame
= (PULONG
)Frame
[0];
1182 KeRosGetStackFrames ( PULONG Frames
, ULONG FrameCount
)
1185 PULONG StackBase
, StackEnd
, Frame
;
1186 MEMORY_BASIC_INFORMATION mbi
;
1187 ULONG ResultLength
= sizeof(mbi
);
1192 #if defined __GNUC__
1193 __asm__("mov %%ebp, %0" : "=r" (Frame
) : );
1194 #elif defined(_MSC_VER)
1195 __asm mov
[Frame
], ebp
1198 Status
= MiQueryVirtualMemory (
1201 MemoryBasicInformation
,
1205 if ( !NT_SUCCESS(Status
) )
1207 DPRINT1("Can't get stack frames: MiQueryVirtualMemory() failed: %x\n", Status
);
1212 StackEnd
= (PULONG
)((ULONG_PTR
)mbi
.BaseAddress
+ mbi
.RegionSize
);
1214 while ( Count
< FrameCount
&& Frame
>= StackBase
&& Frame
< StackEnd
)
1216 Frames
[Count
++] = Frame
[1];
1218 Frame
= (PULONG
)Frame
[0];
1231 KeInitExceptions(VOID
)
1234 USHORT FlippedSelector
;
1237 for (i
= 0; i
<= MAXIMUM_IDTVECTOR
; i
++)
1239 /* Save the current Selector */
1240 FlippedSelector
= KiIdt
[i
].Selector
;
1242 /* Flip Selector and Extended Offset */
1243 KiIdt
[i
].Selector
= KiIdt
[i
].ExtendedOffset
;
1244 KiIdt
[i
].ExtendedOffset
= FlippedSelector
;
1250 KiDispatchException(PEXCEPTION_RECORD ExceptionRecord
,
1251 PKEXCEPTION_FRAME ExceptionFrame
,
1252 PKTRAP_FRAME TrapFrame
,
1253 KPROCESSOR_MODE PreviousMode
,
1254 BOOLEAN FirstChance
)
1257 KD_CONTINUE_TYPE Action
;
1258 ULONG_PTR Stack
, NewStack
;
1260 BOOLEAN UserDispatch
= FALSE
;
1261 DPRINT("KiDispatchException() called\n");
1263 /* Increase number of Exception Dispatches */
1264 KeGetCurrentPrcb()->KeExceptionDispatchCount
++;
1266 /* Set the context flags */
1267 Context
.ContextFlags
= CONTEXT_FULL
| CONTEXT_DEBUG_REGISTERS
;
1269 /* Check if User Mode */
1270 if (PreviousMode
== UserMode
)
1272 /* Add the FPU Flag */
1273 Context
.ContextFlags
|= CONTEXT_FLOATING_POINT
;
1274 if (KeI386FxsrPresent
) Context
.ContextFlags
|= CONTEXT_EXTENDED_REGISTERS
;
1278 KeTrapFrameToContext(TrapFrame
, ExceptionFrame
, &Context
);
1280 /* Handle kernel-mode first, it's simpler */
1281 if (PreviousMode
== KernelMode
)
1283 /* Check if this is a first-chance exception */
1284 if (FirstChance
== TRUE
)
1286 /* Break into the debugger for the first time */
1287 Action
= KdpEnterDebuggerException(ExceptionRecord
,
1294 /* If the debugger said continue, then continue */
1295 if (Action
== kdContinue
) goto Handled
;
1297 /* If the Debugger couldn't handle it, dispatch the exception */
1298 if (RtlDispatchException(ExceptionRecord
, &Context
))
1300 /* It was handled by an exception handler, continue */
1305 /* This is a second-chance exception, only for the debugger */
1306 Action
= KdpEnterDebuggerException(ExceptionRecord
,
1313 /* If the debugger said continue, then continue */
1314 if (Action
== kdContinue
) goto Handled
;
1316 /* Third strike; you're out */
1317 KEBUGCHECKWITHTF(KMODE_EXCEPTION_NOT_HANDLED
,
1318 ExceptionRecord
->ExceptionCode
,
1319 (ULONG_PTR
)ExceptionRecord
->ExceptionAddress
,
1320 ExceptionRecord
->ExceptionInformation
[0],
1321 ExceptionRecord
->ExceptionInformation
[1],
1326 /* User mode exception, was it first-chance? */
1329 /* Enter Debugger if available */
1330 Action
= KdpEnterDebuggerException(ExceptionRecord
,
1337 /* Exit if we're continuing */
1338 if (Action
== kdContinue
) goto Handled
;
1340 /* FIXME: Forward exception to user mode debugger */
1342 /* Set up the user-stack */
1345 /* Align context size and get stack pointer */
1346 Size
= (sizeof(CONTEXT
) + 3) & ~3;
1347 Stack
= (Context
.Esp
& ~3) - Size
;
1348 DPRINT("Stack: %lx\n", Stack
);
1350 /* Probe stack and copy Context */
1351 ProbeForWrite((PVOID
)Stack
, Size
, sizeof(ULONG
));
1352 RtlCopyMemory((PVOID
)Stack
, &Context
, sizeof(CONTEXT
));
1354 /* Align exception record size and get stack pointer */
1355 Size
= (sizeof(EXCEPTION_RECORD
) -
1356 (EXCEPTION_MAXIMUM_PARAMETERS
- ExceptionRecord
->NumberParameters
) *
1357 sizeof(ULONG
) + 3) & ~3;
1358 NewStack
= Stack
- Size
;
1359 DPRINT("NewStack: %lx\n", NewStack
);
1361 /* Probe stack and copy exception record. Don't forget to add the two params */
1362 ProbeForWrite((PVOID
)(NewStack
- 2 * sizeof(ULONG_PTR
)),
1363 Size
+ 2 * sizeof(ULONG_PTR
),
1365 RtlCopyMemory((PVOID
)NewStack
, ExceptionRecord
, Size
);
1367 /* Now write the two params for the user-mode dispatcher */
1368 *(PULONG_PTR
)(NewStack
- 1 * sizeof(ULONG_PTR
)) = Stack
;
1369 *(PULONG_PTR
)(NewStack
- 2 * sizeof(ULONG_PTR
)) = NewStack
;
1371 /* Set new Stack Pointer */
1372 KiEspToTrapFrame(TrapFrame
, NewStack
- 2 * sizeof(ULONG_PTR
));
1374 /* Set EIP to the User-mode Dispathcer */
1375 TrapFrame
->Eip
= (ULONG
)KeUserExceptionDispatcher
;
1376 UserDispatch
= TRUE
;
1381 /* Do second-chance */
1386 /* If we dispatch to user, return now */
1387 if (UserDispatch
) return;
1389 /* FIXME: Forward the exception to the debugger for 2nd chance */
1391 /* 3rd strike, kill the thread */
1392 DPRINT1("Unhandled UserMode exception, terminating thread\n");
1393 ZwTerminateThread(NtCurrentThread(), ExceptionRecord
->ExceptionCode
);
1394 KEBUGCHECKWITHTF(KMODE_EXCEPTION_NOT_HANDLED
,
1395 ExceptionRecord
->ExceptionCode
,
1396 (ULONG_PTR
)ExceptionRecord
->ExceptionAddress
,
1397 ExceptionRecord
->ExceptionInformation
[0],
1398 ExceptionRecord
->ExceptionInformation
[1],
1403 /* Convert the context back into Trap/Exception Frames */
1404 KeContextToTrapFrame(&Context
,
1407 Context
.ContextFlags
,
1417 KeRaiseUserException(IN NTSTATUS ExceptionCode
)
1420 PKTHREAD Thread
= KeGetCurrentThread();
1422 /* Make sure we can access the TEB */
1425 Thread
->Teb
->ExceptionCode
= ExceptionCode
;
1429 return(ExceptionCode
);
1433 /* Get the old EIP */
1434 OldEip
= Thread
->TrapFrame
->Eip
;
1436 /* Change it to the user-mode dispatcher */
1437 Thread
->TrapFrame
->Eip
= (ULONG_PTR
)KeRaiseUserExceptionDispatcher
;
1439 /* Return the old EIP */
1440 return((NTSTATUS
)OldEip
);