2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/ke/i386/traphdlr.c
5 * PURPOSE: Kernel Trap Handlers
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
15 /* GLOBALS ********************************************************************/
17 UCHAR KiTrapPrefixTable
[] =
20 0xF3, /* REP INS/OUTS */
32 UCHAR KiTrapIoTable
[] =
48 PFAST_SYSTEM_CALL_EXIT KiFastCallExitHandler
;
49 #if DBG && !defined(_WINKD_)
50 PKDBG_PRESERVICEHOOK KeWin32PreServiceHook
= NULL
;
51 PKDBG_POSTSERVICEHOOK KeWin32PostServiceHook
= NULL
;
54 BOOLEAN StopChecking
= FALSE
;
58 /* TRAP EXIT CODE *************************************************************/
62 KiVdmTrap(IN PKTRAP_FRAME TrapFrame
)
64 /* Either the V8086 flag is on, or this is user-mode with a VDM */
65 return ((TrapFrame
->EFlags
& EFLAGS_V86_MASK
) ||
66 ((KiUserTrap(TrapFrame
)) && (PsGetCurrentProcess()->VdmObjects
)));
71 KiV86Trap(IN PKTRAP_FRAME TrapFrame
)
73 /* Check if the V8086 flag is on */
74 return ((TrapFrame
->EFlags
& EFLAGS_V86_MASK
) != 0);
79 KiIsFrameEdited(IN PKTRAP_FRAME TrapFrame
)
81 /* An edited frame changes esp. It is marked by clearing the bits
82 defined by FRAME_EDITED in the SegCs field of the trap frame */
83 return ((TrapFrame
->SegCs
& FRAME_EDITED
) == 0);
88 KiCommonExit(IN PKTRAP_FRAME TrapFrame
, BOOLEAN SkipPreviousMode
)
90 /* Disable interrupts until we return */
93 /* Check for APC delivery */
94 KiCheckForApcDelivery(TrapFrame
);
96 /* Restore the SEH handler chain */
97 KeGetPcr()->NtTib
.ExceptionList
= TrapFrame
->ExceptionList
;
99 /* Check if there are active debug registers */
100 if (__builtin_expect(TrapFrame
->Dr7
& ~DR7_RESERVED_MASK
, 0))
102 /* Check if the frame was from user mode or v86 mode */
103 if ((TrapFrame
->SegCs
& MODE_MASK
) ||
104 (TrapFrame
->EFlags
& EFLAGS_V86_MASK
))
106 /* Handle debug registers */
107 KiHandleDebugRegistersOnTrapExit(TrapFrame
);
111 /* Debugging checks */
112 KiExitTrapDebugChecks(TrapFrame
, SkipPreviousMode
);
118 KiEoiHelper(IN PKTRAP_FRAME TrapFrame
)
120 /* Common trap exit code */
121 KiCommonExit(TrapFrame
, TRUE
);
123 /* Check if this was a V8086 trap */
124 if (TrapFrame
->EFlags
& EFLAGS_V86_MASK
) KiTrapReturnNoSegments(TrapFrame
);
126 /* Check for user mode exit */
127 if (TrapFrame
->SegCs
& MODE_MASK
) KiTrapReturn(TrapFrame
);
129 /* Check for edited frame */
130 if (KiIsFrameEdited(TrapFrame
)) KiEditedTrapReturn(TrapFrame
);
132 /* Exit the trap to kernel mode */
133 KiTrapReturnNoSegments(TrapFrame
);
139 KiServiceExit(IN PKTRAP_FRAME TrapFrame
,
142 ASSERT((TrapFrame
->EFlags
& EFLAGS_V86_MASK
) == 0);
143 ASSERT(!KiIsFrameEdited(TrapFrame
));
145 /* Copy the status into EAX */
146 TrapFrame
->Eax
= Status
;
148 /* Common trap exit code */
149 KiCommonExit(TrapFrame
, FALSE
);
151 /* Restore previous mode */
152 KeGetCurrentThread()->PreviousMode
= (CCHAR
)TrapFrame
->PreviousPreviousMode
;
154 /* Check for user mode exit */
155 if (TrapFrame
->SegCs
& MODE_MASK
)
157 /* Check if we were single stepping */
158 if (TrapFrame
->EFlags
& EFLAGS_TF
)
160 /* Must use the IRET handler */
161 KiSystemCallTrapReturn(TrapFrame
);
165 /* We can use the sysexit handler */
166 KiFastCallExitHandler(TrapFrame
);
170 /* Exit to kernel mode */
171 KiSystemCallReturn(TrapFrame
);
177 KiServiceExit2(IN PKTRAP_FRAME TrapFrame
)
179 /* Common trap exit code */
180 KiCommonExit(TrapFrame
, FALSE
);
182 /* Restore previous mode */
183 KeGetCurrentThread()->PreviousMode
= (CCHAR
)TrapFrame
->PreviousPreviousMode
;
185 /* Check if this was a V8086 trap */
186 if (TrapFrame
->EFlags
& EFLAGS_V86_MASK
) KiTrapReturnNoSegments(TrapFrame
);
188 /* Check for user mode exit */
189 if (TrapFrame
->SegCs
& MODE_MASK
) KiTrapReturn(TrapFrame
);
191 /* Check for edited frame */
192 if (KiIsFrameEdited(TrapFrame
)) KiEditedTrapReturn(TrapFrame
);
194 /* Exit the trap to kernel mode */
195 KiTrapReturnNoSegments(TrapFrame
);
199 /* TRAP HANDLERS **************************************************************/
204 KiDebugHandler(IN PKTRAP_FRAME TrapFrame
,
209 /* Check for VDM trap */
210 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
212 /* Enable interrupts if the trap came from user-mode */
213 if (KiUserTrap(TrapFrame
)) _enable();
215 /* Dispatch the exception */
216 KiDispatchExceptionFromTrapFrame(STATUS_BREAKPOINT
,
228 KiNpxHandler(IN PKTRAP_FRAME TrapFrame
,
230 IN PFX_SAVE_AREA SaveArea
)
232 ULONG Cr0
, Mask
, Error
, ErrorOffset
, DataOffset
;
234 /* Check for VDM trap */
235 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
237 /* Check for kernel trap */
238 if (!KiUserTrap(TrapFrame
))
240 /* Kernel might've tripped a delayed error */
241 SaveArea
->Cr0NpxState
|= CR0_TS
;
243 /* Only valid if it happened during a restore */
244 //if ((PVOID)TrapFrame->Eip == FrRestore)
246 /* It did, so just skip the instruction */
247 //TrapFrame->Eip += 3; /* sizeof(FRSTOR) */
248 //KiEoiHelper(TrapFrame);
252 /* User or kernel trap -- get ready to issue an exception */
253 //if (Thread->NpxState == NPX_STATE_NOT_LOADED)
257 Cr0
&= ~(CR0_MP
| CR0_EM
| CR0_TS
);
261 Ke386SaveFpuState(SaveArea
);
263 /* Mark CR0 state dirty */
264 Cr0
|= NPX_STATE_NOT_LOADED
;
265 Cr0
|= SaveArea
->Cr0NpxState
;
268 /* Update NPX state */
269 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
270 KeGetCurrentPrcb()->NpxThread
= NULL
;
273 /* Clear the TS bit and re-enable interrupts */
274 SaveArea
->Cr0NpxState
&= ~CR0_TS
;
277 /* Check if we should get the FN or FX error */
278 if (KeI386FxsrPresent
)
281 Mask
= SaveArea
->U
.FxArea
.ControlWord
;
282 Error
= SaveArea
->U
.FxArea
.StatusWord
;
284 /* Get the FPU exception address too */
285 ErrorOffset
= SaveArea
->U
.FxArea
.ErrorOffset
;
286 DataOffset
= SaveArea
->U
.FxArea
.DataOffset
;
291 Mask
= SaveArea
->U
.FnArea
.ControlWord
;
292 Error
= SaveArea
->U
.FnArea
.StatusWord
;
294 /* Get the FPU exception address too */
295 ErrorOffset
= SaveArea
->U
.FnArea
.ErrorOffset
;
296 DataOffset
= SaveArea
->U
.FnArea
.DataOffset
;
299 /* Get legal exceptions that software should handle */
300 /* We do this by first masking off from the Mask the bits we need, */
301 /* This is done so we can keep the FSW_STACK_FAULT bit in Error. */
302 Mask
&= (FSW_INVALID_OPERATION
|
310 /* Check for invalid operation */
311 if (Error
& FSW_INVALID_OPERATION
)
313 /* NOTE: Stack fault is handled differently than any other case. */
314 /* 1. It's only raised for invalid operation. */
315 /* 2. It's only raised if invalid operation is not masked. */
316 if (Error
& FSW_STACK_FAULT
)
318 /* Issue stack check fault */
319 KiDispatchException2Args(STATUS_FLOAT_STACK_CHECK
,
327 KiDispatchException1Args(STATUS_FLOAT_INVALID_OPERATION
,
333 /* Check for divide by zero */
334 if (Error
& FSW_ZERO_DIVIDE
)
337 KiDispatchException1Args(STATUS_FLOAT_DIVIDE_BY_ZERO
,
343 /* Check for denormal */
344 if (Error
& FSW_DENORMAL
)
347 KiDispatchException1Args(STATUS_FLOAT_INVALID_OPERATION
,
353 /* Check for overflow */
354 if (Error
& FSW_OVERFLOW
)
357 KiDispatchException1Args(STATUS_FLOAT_OVERFLOW
,
363 /* Check for underflow */
364 if (Error
& FSW_UNDERFLOW
)
367 KiDispatchException1Args(STATUS_FLOAT_UNDERFLOW
,
373 /* Check for precision fault */
374 if (Error
& FSW_PRECISION
)
377 KiDispatchException1Args(STATUS_FLOAT_INEXACT_RESULT
,
383 /* Unknown FPU fault */
384 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 1, Error
, 0, 0, TrapFrame
);
390 KiTrap00Handler(IN PKTRAP_FRAME TrapFrame
)
392 /* Save trap frame */
393 KiEnterTrap(TrapFrame
);
395 /* Check for VDM trap */
396 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
398 /* Enable interrupts */
401 /* Dispatch the exception */
402 KiDispatchException0Args(STATUS_INTEGER_DIVIDE_BY_ZERO
,
410 KiTrap01Handler(IN PKTRAP_FRAME TrapFrame
)
412 /* Save trap frame */
413 KiEnterTrap(TrapFrame
);
415 /* Check for VDM trap */
416 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
418 /* Enable interrupts if the trap came from user-mode */
419 if (KiUserTrap(TrapFrame
)) _enable();
421 /* Mask out trap flag and dispatch the exception */
422 TrapFrame
->EFlags
&= ~EFLAGS_TF
;
423 KiDispatchException0Args(STATUS_SINGLE_STEP
,
437 KTRAP_FRAME TrapFrame
;
441 // In some sort of strange recursion case, we might end up here with the IF
442 // flag incorrectly on the interrupt frame -- during a normal NMI this would
443 // normally already be set.
445 // For sanity's sake, make sure interrupts are disabled for sure.
446 // NMIs will already be since the CPU does it for us.
451 // Get the current TSS, thread, and process
454 Thread
= ((PKIPCR
)PCR
)->PrcbData
.CurrentThread
;
455 Process
= Thread
->ApcState
.Process
;
458 // Save data usually not in the TSS
460 Tss
->CR3
= Process
->DirectoryTableBase
[0];
461 Tss
->IoMapBase
= Process
->IopmOffset
;
462 Tss
->LDT
= Process
->LdtDescriptor
.LimitLow
? KGDT_LDT
: 0;
465 // Now get the base address of the NMI TSS
467 TssGdt
= &((PKIPCR
)KeGetPcr())->GDT
[KGDT_NMI_TSS
/ sizeof(KGDTENTRY
)];
468 NmiTss
= (PKTSS
)(ULONG_PTR
)(TssGdt
->BaseLow
|
469 TssGdt
->HighWord
.Bytes
.BaseMid
<< 16 |
470 TssGdt
->HighWord
.Bytes
.BaseHi
<< 24);
473 // Switch to it and activate it, masking off the nested flag
475 // Note that in reality, we are already on the NMI tss -- we just need to
476 // update the PCR to reflect this
479 __writeeflags(__readeflags() &~ EFLAGS_NESTED_TASK
);
480 TssGdt
->HighWord
.Bits
.Dpl
= 0;
481 TssGdt
->HighWord
.Bits
.Pres
= 1;
482 TssGdt
->HighWord
.Bits
.Type
= I386_TSS
;
485 // Now build the trap frame based on the original TSS
487 // The CPU does a hardware "Context switch" / task switch of sorts and so it
488 // takes care of saving our context in the normal TSS.
490 // We just have to go get the values...
492 RtlZeroMemory(&TrapFrame
, sizeof(KTRAP_FRAME
));
493 TrapFrame
.HardwareSegSs
= Tss
->Ss0
;
494 TrapFrame
.HardwareEsp
= Tss
->Esp0
;
495 TrapFrame
.EFlags
= Tss
->EFlags
;
496 TrapFrame
.SegCs
= Tss
->Cs
;
497 TrapFrame
.Eip
= Tss
->Eip
;
498 TrapFrame
.Ebp
= Tss
->Ebp
;
499 TrapFrame
.Ebx
= Tss
->Ebx
;
500 TrapFrame
.Esi
= Tss
->Esi
;
501 TrapFrame
.Edi
= Tss
->Edi
;
502 TrapFrame
.SegFs
= Tss
->Fs
;
503 TrapFrame
.ExceptionList
= PCR
->NtTib
.ExceptionList
;
504 TrapFrame
.PreviousPreviousMode
= -1;
505 TrapFrame
.Eax
= Tss
->Eax
;
506 TrapFrame
.Ecx
= Tss
->Ecx
;
507 TrapFrame
.Edx
= Tss
->Edx
;
508 TrapFrame
.SegDs
= Tss
->Ds
;
509 TrapFrame
.SegEs
= Tss
->Es
;
510 TrapFrame
.SegGs
= Tss
->Gs
;
511 TrapFrame
.DbgEip
= Tss
->Eip
;
512 TrapFrame
.DbgEbp
= Tss
->Ebp
;
515 // Store the trap frame in the KPRCB
517 KiSaveProcessorState(&TrapFrame
, NULL
);
520 // Call any registered NMI handlers and see if they handled it or not
525 // They did not, so call the platform HAL routine to bugcheck the system
527 // Make sure the HAL believes it's running at HIGH IRQL... we can't use
528 // the normal APIs here as playing with the IRQL could change the system
532 PCR
->Irql
= HIGH_LEVEL
;
538 // Although the CPU disabled NMIs, we just did a BIOS Call, which could've
539 // totally changed things.
541 // We have to make sure we're still in our original NMI -- a nested NMI
542 // will point back to the NMI TSS, and in that case we're hosed.
544 if (PCR
->TSS
->Backlink
!= KGDT_NMI_TSS
)
547 // Restore original TSS
552 // Set it back to busy
554 TssGdt
->HighWord
.Bits
.Dpl
= 0;
555 TssGdt
->HighWord
.Bits
.Pres
= 1;
556 TssGdt
->HighWord
.Bits
.Type
= I386_ACTIVE_TSS
;
559 // Restore nested flag
561 __writeeflags(__readeflags() | EFLAGS_NESTED_TASK
);
564 // Handled, return from interrupt
570 // Unhandled: crash the system
572 KiSystemFatalException(EXCEPTION_NMI
, NULL
);
578 KiTrap03Handler(IN PKTRAP_FRAME TrapFrame
)
580 /* Save trap frame */
581 KiEnterTrap(TrapFrame
);
583 /* Continue with the common handler */
584 KiDebugHandler(TrapFrame
, BREAKPOINT_BREAK
, 0, 0);
590 KiTrap04Handler(IN PKTRAP_FRAME TrapFrame
)
592 /* Save trap frame */
593 KiEnterTrap(TrapFrame
);
595 /* Check for VDM trap */
596 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
598 /* Enable interrupts */
601 /* Dispatch the exception */
602 KiDispatchException0Args(STATUS_INTEGER_OVERFLOW
,
610 KiTrap05Handler(IN PKTRAP_FRAME TrapFrame
)
612 /* Save trap frame */
613 KiEnterTrap(TrapFrame
);
615 /* Check for VDM trap */
616 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
618 /* Check for kernel-mode fault */
619 if (!KiUserTrap(TrapFrame
)) KiSystemFatalException(EXCEPTION_BOUND_CHECK
, TrapFrame
);
621 /* Enable interrupts */
624 /* Dispatch the exception */
625 KiDispatchException0Args(STATUS_ARRAY_BOUNDS_EXCEEDED
,
633 KiTrap06Handler(IN PKTRAP_FRAME TrapFrame
)
639 /* Check for V86 GPF */
640 if (__builtin_expect(KiV86Trap(TrapFrame
), 1))
643 KiEnterV86Trap(TrapFrame
);
645 /* Must be a VDM process */
646 if (__builtin_expect(!PsGetCurrentProcess()->VdmObjects
, 0))
648 /* Enable interrupts */
651 /* Setup illegal instruction fault */
652 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
657 /* Go to APC level */
658 OldIrql
= KfRaiseIrql(APC_LEVEL
);
662 if (!VdmDispatchBop(TrapFrame
))
664 /* Should only happen in VDM mode */
665 UNIMPLEMENTED_FATAL();
668 /* Bring IRQL back */
669 KfLowerIrql(OldIrql
);
672 /* Do a quick V86 exit if possible */
673 KiExitV86Trap(TrapFrame
);
676 /* Save trap frame */
677 KiEnterTrap(TrapFrame
);
679 /* Enable interrupts */
680 Instruction
= (PUCHAR
)TrapFrame
->Eip
;
683 /* Check for user trap */
684 if (KiUserTrap(TrapFrame
))
688 /* Scan next 4 opcodes */
689 for (i
= 0; i
< 4; i
++)
691 /* Check for LOCK instruction */
692 if (Instruction
[i
] == 0xF0)
694 /* Send invalid lock sequence exception */
695 KiDispatchException0Args(STATUS_INVALID_LOCK_SEQUENCE
,
701 /* FIXME: SEH ends here */
704 /* Kernel-mode or user-mode fault (but not LOCK) */
705 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
714 KiTrap07Handler(IN PKTRAP_FRAME TrapFrame
)
716 PKTHREAD Thread
, NpxThread
;
717 PFX_SAVE_AREA SaveArea
, NpxSaveArea
;
720 /* Save trap frame */
721 KiEnterTrap(TrapFrame
);
723 /* Try to handle NPX delay load */
726 /* Get the current thread */
727 Thread
= KeGetCurrentThread();
729 /* Get the NPX frame */
730 SaveArea
= KiGetThreadNpxArea(Thread
);
732 /* Check if emulation is enabled */
733 if (SaveArea
->Cr0NpxState
& CR0_EM
)
735 /* Not implemented */
736 UNIMPLEMENTED_FATAL();
739 /* Save CR0 and check NPX state */
741 if (Thread
->NpxState
!= NPX_STATE_LOADED
)
744 Cr0
&= ~(CR0_MP
| CR0_EM
| CR0_TS
);
747 /* Get the NPX thread */
748 NpxThread
= KeGetCurrentPrcb()->NpxThread
;
751 /* Get the NPX frame */
752 NpxSaveArea
= KiGetThreadNpxArea(NpxThread
);
755 DPRINT("FIXME: Save FPU state: %p\n", NpxSaveArea
);
756 //Ke386SaveFpuState(NpxSaveArea);
758 /* Update NPX state */
759 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
763 //Ke386LoadFpuState(SaveArea);
765 /* Update NPX state */
766 Thread
->NpxState
= NPX_STATE_LOADED
;
767 KeGetCurrentPrcb()->NpxThread
= Thread
;
769 /* Enable interrupts */
772 /* Check if CR0 needs to be reloaded due to context switch */
773 if (!SaveArea
->Cr0NpxState
) KiEoiHelper(TrapFrame
);
775 /* Otherwise, we need to reload CR0, disable interrupts */
780 Cr0
|= SaveArea
->Cr0NpxState
;
783 /* Now restore interrupts and check for TS */
785 if (Cr0
& CR0_TS
) KiEoiHelper(TrapFrame
);
787 /* We're still here -- clear TS and try again */
788 __writecr0(__readcr0() &~ CR0_TS
);
793 /* This is an actual fault, not a lack of FPU state */
798 /* TS should not be set */
802 * If it's incorrectly set, then maybe the state is actually still valid
803 * but we could've lock track of that due to a BIOS call.
804 * Make sure MP is still set, which should verify the theory.
808 /* Indeed, the state is actually still valid, so clear TS */
809 __writecr0(__readcr0() &~ CR0_TS
);
810 KiEoiHelper(TrapFrame
);
813 /* Otherwise, something strange is going on */
814 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 2, Cr0
, 0, 0, TrapFrame
);
817 /* It's not a delayed load, so process this trap as an NPX fault */
818 KiNpxHandler(TrapFrame
, Thread
, SaveArea
);
824 KiTrap08Handler(IN PKTRAP_FRAME TrapFrame
)
826 /* FIXME: Not handled */
827 KiSystemFatalException(EXCEPTION_DOUBLE_FAULT
, TrapFrame
);
833 KiTrap09Handler(IN PKTRAP_FRAME TrapFrame
)
835 /* Save trap frame */
836 KiEnterTrap(TrapFrame
);
838 /* Enable interrupts and kill the system */
840 KiSystemFatalException(EXCEPTION_NPX_OVERRUN
, TrapFrame
);
846 KiTrap0AHandler(IN PKTRAP_FRAME TrapFrame
)
848 /* Save trap frame */
849 KiEnterTrap(TrapFrame
);
851 /* Check for VDM trap */
852 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
854 /* Kill the system */
855 KiSystemFatalException(EXCEPTION_INVALID_TSS
, TrapFrame
);
861 KiTrap0BHandler(IN PKTRAP_FRAME TrapFrame
)
863 /* Save trap frame */
864 KiEnterTrap(TrapFrame
);
866 /* FIXME: Kill the system */
868 KiSystemFatalException(EXCEPTION_SEGMENT_NOT_PRESENT
, TrapFrame
);
874 KiTrap0CHandler(IN PKTRAP_FRAME TrapFrame
)
876 /* Save trap frame */
877 KiEnterTrap(TrapFrame
);
879 /* FIXME: Kill the system */
881 KiSystemFatalException(EXCEPTION_STACK_FAULT
, TrapFrame
);
887 KiTrap0DHandler(IN PKTRAP_FRAME TrapFrame
)
890 BOOLEAN Privileged
= FALSE
;
892 UCHAR Instruction
= 0;
895 /* Check for V86 GPF */
896 if (__builtin_expect(KiV86Trap(TrapFrame
), 1))
899 KiEnterV86Trap(TrapFrame
);
901 /* Must be a VDM process */
902 if (__builtin_expect(!PsGetCurrentProcess()->VdmObjects
, 0))
904 /* Enable interrupts */
907 /* Setup illegal instruction fault */
908 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
913 /* Go to APC level */
914 OldIrql
= KfRaiseIrql(APC_LEVEL
);
917 /* Handle the V86 opcode */
918 if (__builtin_expect(Ki386HandleOpcodeV86(TrapFrame
) == 0xFF, 0))
920 /* Should only happen in VDM mode */
921 UNIMPLEMENTED_FATAL();
924 /* Bring IRQL back */
925 KfLowerIrql(OldIrql
);
928 /* Do a quick V86 exit if possible */
929 KiExitV86Trap(TrapFrame
);
932 /* Save trap frame */
933 KiEnterTrap(TrapFrame
);
935 /* Check for user-mode GPF */
936 if (KiUserTrap(TrapFrame
))
938 /* Should not be VDM */
939 ASSERT(KiVdmTrap(TrapFrame
) == FALSE
);
941 /* Enable interrupts and check error code */
943 if (!TrapFrame
->ErrCode
)
946 Instructions
= (PUCHAR
)TrapFrame
->Eip
;
948 /* Scan next 15 bytes */
949 for (i
= 0; i
< 15; i
++)
951 /* Skip prefix instructions */
952 for (j
= 0; j
< sizeof(KiTrapPrefixTable
); j
++)
954 /* Is this a prefix instruction? */
955 if (Instructions
[i
] == KiTrapPrefixTable
[j
])
962 /* Is this NOT any prefix instruction? */
963 if (j
== sizeof(KiTrapPrefixTable
))
965 /* We can go ahead and handle the fault now */
966 Instruction
= Instructions
[i
];
971 /* If all we found was prefixes, then this instruction is too long */
974 /* Setup illegal instruction fault */
975 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
980 /* Check for privileged instructions */
981 DPRINT("Instruction (%d) at fault: %lx %lx %lx %lx\n",
986 Instructions
[i
+ 3]);
987 if (Instruction
== 0xF4) // HLT
989 /* HLT is privileged */
992 else if (Instruction
== 0x0F)
994 /* Test if it's any of the privileged two-byte opcodes */
995 if (((Instructions
[i
+ 1] == 0x00) && // LLDT or LTR
996 (((Instructions
[i
+ 2] & 0x38) == 0x10) || // LLDT
997 (Instructions
[i
+ 2] == 0x18))) || // LTR
998 ((Instructions
[i
+ 1] == 0x01) && // LGDT or LIDT or LMSW
999 (((Instructions
[i
+ 2] & 0x38) == 0x10) || // LGDT
1000 (Instructions
[i
+ 2] == 0x18) || // LIDT
1001 (Instructions
[i
+ 2] == 0x30))) || // LMSW
1002 (Instructions
[i
+ 1] == 0x08) || // INVD
1003 (Instructions
[i
+ 1] == 0x09) || // WBINVD
1004 (Instructions
[i
+ 1] == 0x35) || // SYSEXIT
1005 (Instructions
[i
+ 1] == 0x21) || // MOV DR, XXX
1006 (Instructions
[i
+ 1] == 0x06) || // CLTS
1007 (Instructions
[i
+ 1] == 0x20) || // MOV CR, XXX
1008 (Instructions
[i
+ 1] == 0x22) || // MOV XXX, CR
1009 (Instructions
[i
+ 1] == 0x23) || // MOV YYY, DR
1010 (Instructions
[i
+ 1] == 0x30) || // WRMSR
1011 (Instructions
[i
+ 1] == 0x33)) // RDPMC
1012 // INVLPG, INVLPGA, SYSRET
1014 /* These are all privileged */
1020 /* Get the IOPL and compare with the RPL mask */
1021 Iopl
= (TrapFrame
->EFlags
& EFLAGS_IOPL
) >> 12;
1022 if ((TrapFrame
->SegCs
& RPL_MASK
) > Iopl
)
1024 /* I/O privilege error -- check for known instructions */
1025 if ((Instruction
== 0xFA) || (Instruction
== 0xFB)) // CLI or STI
1027 /* These are privileged */
1032 /* Last hope: an IN/OUT instruction */
1033 for (j
= 0; j
< sizeof(KiTrapIoTable
); j
++)
1035 /* Is this an I/O instruction? */
1036 if (Instruction
== KiTrapIoTable
[j
])
1038 /* Then it's privileged */
1047 /* So now... was the instruction privileged or not? */
1050 /* Whew! We have a privileged instruction, so dispatch the fault */
1051 KiDispatchException0Args(STATUS_PRIVILEGED_INSTRUCTION
,
1057 /* If we got here, send an access violation */
1058 KiDispatchException2Args(STATUS_ACCESS_VIOLATION
,
1066 * Check for a fault during checking of the user instruction.
1068 * Note that the SEH handler will catch invalid EIP, but we could be dealing
1069 * with an invalid CS, which will generate another GPF instead.
1072 if (((PVOID
)TrapFrame
->Eip
>= (PVOID
)KiTrap0DHandler
) &&
1073 ((PVOID
)TrapFrame
->Eip
< (PVOID
)KiTrap0DHandler
))
1075 /* Not implemented */
1076 UNIMPLEMENTED_FATAL();
1080 * NOTE: The ASM trap exit code would restore segment registers by doing
1081 * a POP <SEG>, which could cause an invalid segment if someone had messed
1082 * with the segment values.
1084 * Another case is a bogus SS, which would hit a GPF when doing the iret.
1085 * This could only be done through a buggy or malicious driver, or perhaps
1086 * the kernel debugger.
1088 * The kernel normally restores the "true" segment if this happens.
1090 * However, since we're restoring in C, not ASM, we can't detect
1091 * POP <SEG> since the actual instructions will be different.
1093 * A better technique would be to check the EIP and somehow edit the
1094 * trap frame before restarting the instruction -- but we would need to
1095 * know the extract instruction that was used first.
1097 * We could force a special instrinsic to use stack instructions, or write
1098 * a simple instruction length checker.
1100 * Nevertheless, this is a lot of work for the purpose of avoiding a crash
1101 * when the user is purposedly trying to create one from kernel-mode, so
1102 * we should probably table this for now since it's not a "real" issue.
1106 * NOTE2: Another scenario is the IRET during a V8086 restore (BIOS Call)
1107 * which will cause a GPF since the trap frame is a total mess (on purpose)
1108 * as built in KiEnterV86Mode.
1110 * The idea is to scan for IRET, scan for the known EIP adress, validate CS
1111 * and then manually issue a jump to the V8086 return EIP.
1113 Instructions
= (PUCHAR
)TrapFrame
->Eip
;
1114 if (Instructions
[0] == 0xCF)
1117 * Some evil shit is going on here -- this is not the SS:ESP you're
1118 * looking for! Instead, this is actually CS:EIP you're looking at!
1119 * Why? Because part of the trap frame actually corresponds to the IRET
1120 * stack during the trap exit!
1122 if ((TrapFrame
->HardwareEsp
== (ULONG
)Ki386BiosCallReturnAddress
) &&
1123 (TrapFrame
->HardwareSegSs
== (KGDT_R0_CODE
| RPL_MASK
)))
1125 /* Exit the V86 trap! */
1126 Ki386BiosCallReturnAddress(TrapFrame
);
1130 /* Otherwise, this is another kind of IRET fault */
1131 UNIMPLEMENTED_FATAL();
1135 /* So since we're not dealing with the above case, check for RDMSR/WRMSR */
1136 if ((Instructions
[0] == 0xF) && // 2-byte opcode
1137 ((Instructions
[1] == 0x32) || // RDMSR
1138 (Instructions
[1] == 0x30))) // WRMSR
1140 /* Unknown CPU MSR, so raise an access violation */
1141 KiDispatchException0Args(STATUS_ACCESS_VIOLATION
,
1146 /* Check for lazy segment load */
1147 if (TrapFrame
->SegDs
!= (KGDT_R3_DATA
| RPL_MASK
))
1150 TrapFrame
->SegDs
= (KGDT_R3_DATA
| RPL_MASK
);
1152 else if (TrapFrame
->SegEs
!= (KGDT_R3_DATA
| RPL_MASK
))
1155 TrapFrame
->SegEs
= (KGDT_R3_DATA
| RPL_MASK
);
1159 /* Whatever it is, we can't handle it */
1160 KiSystemFatalException(EXCEPTION_GP_FAULT
, TrapFrame
);
1163 /* Return to where we came from */
1164 KiTrapReturn(TrapFrame
);
1170 KiTrap0EHandler(IN PKTRAP_FRAME TrapFrame
)
1176 /* Save trap frame */
1177 KiEnterTrap(TrapFrame
);
1179 /* Check if this is the base frame */
1180 Thread
= KeGetCurrentThread();
1181 if (KeGetTrapFrame(Thread
) != TrapFrame
)
1183 /* It isn't, check if this is a second nested frame */
1184 if (((ULONG_PTR
)KeGetTrapFrame(Thread
) - (ULONG_PTR
)TrapFrame
) <=
1185 FIELD_OFFSET(KTRAP_FRAME
, EFlags
))
1187 /* The stack is somewhere in between frames, we need to fix it */
1188 UNIMPLEMENTED_FATAL();
1195 /* Enable interupts */
1198 /* Check if we came in with interrupts disabled */
1199 if (!(TrapFrame
->EFlags
& EFLAGS_INTERRUPT_MASK
))
1201 /* This is completely illegal, bugcheck the system */
1202 KeBugCheckWithTf(IRQL_NOT_LESS_OR_EQUAL
,
1205 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1210 /* Check for S-LIST fault in kernel mode */
1211 if (TrapFrame
->Eip
== (ULONG_PTR
)ExpInterlockedPopEntrySListFault
)
1213 PSLIST_HEADER SListHeader
;
1215 /* Sanity check that the assembly is correct:
1216 This must be mov ebx, [eax]
1217 Followed by cmpxchg8b [ebp] */
1218 ASSERT((((UCHAR
*)TrapFrame
->Eip
)[0] == 0x8B) &&
1219 (((UCHAR
*)TrapFrame
->Eip
)[1] == 0x18) &&
1220 (((UCHAR
*)TrapFrame
->Eip
)[2] == 0x0F) &&
1221 (((UCHAR
*)TrapFrame
->Eip
)[3] == 0xC7) &&
1222 (((UCHAR
*)TrapFrame
->Eip
)[4] == 0x4D) &&
1223 (((UCHAR
*)TrapFrame
->Eip
)[5] == 0x00));
1225 /* Get the pointer to the SLIST_HEADER */
1226 SListHeader
= (PSLIST_HEADER
)TrapFrame
->Ebp
;
1228 /* Check if the Next member of the SLIST_HEADER was changed */
1229 if (SListHeader
->Next
.Next
!= (PSLIST_ENTRY
)TrapFrame
->Eax
)
1231 /* Restart the operation */
1232 TrapFrame
->Eip
= (ULONG_PTR
)ExpInterlockedPopEntrySListResume
;
1234 /* Continue execution */
1235 KiEoiHelper(TrapFrame
);
1239 /* Call the access fault handler */
1240 Status
= MmAccessFault(TrapFrame
->ErrCode
& 1,
1242 TrapFrame
->SegCs
& MODE_MASK
,
1244 if (NT_SUCCESS(Status
)) KiEoiHelper(TrapFrame
);
1246 /* Check for syscall fault */
1248 if ((TrapFrame
->Eip
== (ULONG_PTR
)CopyParams
) ||
1249 (TrapFrame
->Eip
== (ULONG_PTR
)ReadBatch
))
1251 /* Not yet implemented */
1252 UNIMPLEMENTED_FATAL();
1255 /* Check for VDM trap */
1256 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
1258 /* Either kernel or user trap (non VDM) so dispatch exception */
1259 if (Status
== STATUS_ACCESS_VIOLATION
)
1261 /* This status code is repurposed so we can recognize it later */
1262 KiDispatchException2Args(KI_EXCEPTION_ACCESS_VIOLATION
,
1264 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1268 else if ((Status
== STATUS_GUARD_PAGE_VIOLATION
) ||
1269 (Status
== STATUS_STACK_OVERFLOW
))
1271 /* These faults only have two parameters */
1272 KiDispatchException2Args(Status
,
1274 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1279 /* Only other choice is an in-page error, with 3 parameters */
1280 KiDispatchExceptionFromTrapFrame(STATUS_IN_PAGE_ERROR
,
1283 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1292 KiTrap0FHandler(IN PKTRAP_FRAME TrapFrame
)
1294 /* Save trap frame */
1295 KiEnterTrap(TrapFrame
);
1297 /* FIXME: Kill the system */
1299 KiSystemFatalException(EXCEPTION_RESERVED_TRAP
, TrapFrame
);
1305 KiTrap10Handler(IN PKTRAP_FRAME TrapFrame
)
1308 PFX_SAVE_AREA SaveArea
;
1310 /* Save trap frame */
1311 KiEnterTrap(TrapFrame
);
1313 /* Check if this is the NPX thrad */
1314 Thread
= KeGetCurrentThread();
1315 SaveArea
= KiGetThreadNpxArea(Thread
);
1316 if (Thread
!= KeGetCurrentPrcb()->NpxThread
)
1318 /* It isn't, enable interrupts and set delayed error */
1320 SaveArea
->Cr0NpxState
|= CR0_TS
;
1323 KiEoiHelper(TrapFrame
);
1326 /* Otherwise, proceed with NPX fault handling */
1327 KiNpxHandler(TrapFrame
, Thread
, SaveArea
);
1333 KiTrap11Handler(IN PKTRAP_FRAME TrapFrame
)
1335 /* Save trap frame */
1336 KiEnterTrap(TrapFrame
);
1338 /* Enable interrupts and kill the system */
1340 KiSystemFatalException(EXCEPTION_ALIGNMENT_CHECK
, TrapFrame
);
1346 KiTrap13Handler(IN PKTRAP_FRAME TrapFrame
)
1349 PFX_SAVE_AREA SaveArea
;
1350 ULONG Cr0
, MxCsrMask
, Error
;
1352 /* Save trap frame */
1353 KiEnterTrap(TrapFrame
);
1355 /* Check if this is the NPX thrad */
1356 Thread
= KeGetCurrentThread();
1357 if (Thread
!= KeGetCurrentPrcb()->NpxThread
)
1359 /* It isn't, kill the system */
1360 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 13, (ULONG_PTR
)Thread
, 0, 0, TrapFrame
);
1363 /* Get the NPX frame */
1364 SaveArea
= KiGetThreadNpxArea(Thread
);
1366 /* Check for VDM trap */
1367 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
1369 /* Check for user trap */
1370 if (!KiUserTrap(TrapFrame
))
1372 /* Kernel should not fault on XMMI */
1373 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 13, 0, 0, 2, TrapFrame
);
1378 Cr0
&= ~(CR0_MP
| CR0_EM
| CR0_TS
);
1381 /* Save FPU state */
1382 Ke386SaveFpuState(SaveArea
);
1384 /* Mark CR0 state dirty */
1385 Cr0
|= NPX_STATE_NOT_LOADED
;
1386 Cr0
|= SaveArea
->Cr0NpxState
;
1389 /* Update NPX state */
1390 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
1391 KeGetCurrentPrcb()->NpxThread
= NULL
;
1393 /* Clear the TS bit and re-enable interrupts */
1394 SaveArea
->Cr0NpxState
&= ~CR0_TS
;
1397 /* Now look at MxCsr to get the mask of errors we should care about */
1398 MxCsrMask
= ~((USHORT
)SaveArea
->U
.FxArea
.MXCsr
>> 7);
1400 /* Get legal exceptions that software should handle */
1401 Error
= (USHORT
)SaveArea
->U
.FxArea
.MXCsr
& (FSW_INVALID_OPERATION
|
1409 /* Now handle any of those legal errors */
1410 if (Error
& (FSW_INVALID_OPERATION
|
1417 /* By issuing an exception */
1418 KiDispatchException1Args(STATUS_FLOAT_MULTIPLE_TRAPS
,
1424 /* Unknown XMMI fault */
1425 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 13, 0, 0, 1, TrapFrame
);
1428 /* SOFTWARE SERVICES **********************************************************/
1432 KiGetTickCountHandler(IN PKTRAP_FRAME TrapFrame
)
1434 UNIMPLEMENTED_DBGBREAK();
1439 KiCallbackReturnHandler(IN PKTRAP_FRAME TrapFrame
)
1441 UNIMPLEMENTED_DBGBREAK();
1447 KiRaiseAssertionHandler(IN PKTRAP_FRAME TrapFrame
)
1449 /* Save trap frame */
1450 KiEnterTrap(TrapFrame
);
1452 /* Decrement EIP to point to the INT2C instruction (2 bytes, not 1 like INT3) */
1453 TrapFrame
->Eip
-= 2;
1455 /* Dispatch the exception */
1456 KiDispatchException0Args(STATUS_ASSERTION_FAILURE
,
1464 KiDebugServiceHandler(IN PKTRAP_FRAME TrapFrame
)
1466 /* Save trap frame */
1467 KiEnterTrap(TrapFrame
);
1469 /* Increment EIP to skip the INT3 instruction */
1472 /* Continue with the common handler */
1473 KiDebugHandler(TrapFrame
, TrapFrame
->Eax
, TrapFrame
->Ecx
, TrapFrame
->Edx
);
1479 KiDbgPreServiceHook(ULONG SystemCallNumber
, PULONG_PTR Arguments
)
1481 #if DBG && !defined(_WINKD_)
1482 if (SystemCallNumber
>= 0x1000 && KeWin32PreServiceHook
)
1483 KeWin32PreServiceHook(SystemCallNumber
, Arguments
);
1489 KiDbgPostServiceHook(ULONG SystemCallNumber
, ULONG_PTR Result
)
1491 #if DBG && !defined(_WINKD_)
1492 if (SystemCallNumber
>= 0x1000 && KeWin32PostServiceHook
)
1493 return KeWin32PostServiceHook(SystemCallNumber
, Result
);
1501 KiSystemCall(IN PKTRAP_FRAME TrapFrame
,
1505 PKSERVICE_TABLE_DESCRIPTOR DescriptorTable
;
1506 ULONG Id
, Offset
, StackBytes
, Result
;
1508 ULONG SystemCallNumber
= TrapFrame
->Eax
;
1510 /* Get the current thread */
1511 Thread
= KeGetCurrentThread();
1513 /* Set debug header */
1514 KiFillTrapFrameDebug(TrapFrame
);
1516 /* Chain trap frames */
1517 TrapFrame
->Edx
= (ULONG_PTR
)Thread
->TrapFrame
;
1520 TrapFrame
->ErrCode
= 0;
1522 /* Save previous mode */
1523 TrapFrame
->PreviousPreviousMode
= Thread
->PreviousMode
;
1525 /* Save the SEH chain and terminate it for now */
1526 TrapFrame
->ExceptionList
= KeGetPcr()->NtTib
.ExceptionList
;
1527 KeGetPcr()->NtTib
.ExceptionList
= EXCEPTION_CHAIN_END
;
1529 /* Default to debugging disabled */
1532 /* Check if the frame was from user mode */
1533 if (TrapFrame
->SegCs
& MODE_MASK
)
1535 /* Check for active debugging */
1536 if (KeGetCurrentThread()->Header
.DebugActive
& 0xFF)
1538 /* Handle debug registers */
1539 KiHandleDebugRegistersOnTrapEntry(TrapFrame
);
1543 /* Set thread fields */
1544 Thread
->TrapFrame
= TrapFrame
;
1545 Thread
->PreviousMode
= KiUserTrap(TrapFrame
);
1547 /* Enable interrupts */
1550 /* Decode the system call number */
1551 Offset
= (SystemCallNumber
>> SERVICE_TABLE_SHIFT
) & SERVICE_TABLE_MASK
;
1552 Id
= SystemCallNumber
& SERVICE_NUMBER_MASK
;
1554 /* Get descriptor table */
1555 DescriptorTable
= (PVOID
)((ULONG_PTR
)Thread
->ServiceTable
+ Offset
);
1557 /* Validate the system call number */
1558 if (__builtin_expect(Id
>= DescriptorTable
->Limit
, 0))
1560 /* Check if this is a GUI call */
1561 if (!(Offset
& SERVICE_TABLE_TEST
))
1564 Result
= STATUS_INVALID_SYSTEM_SERVICE
;
1568 /* Convert us to a GUI thread -- must wrap in ASM to get new EBP */
1569 Result
= KiConvertToGuiThread();
1571 /* Reload trap frame and descriptor table pointer from new stack */
1572 TrapFrame
= *(volatile PVOID
*)&Thread
->TrapFrame
;
1573 DescriptorTable
= (PVOID
)(*(volatile ULONG_PTR
*)&Thread
->ServiceTable
+ Offset
);
1575 if (!NT_SUCCESS(Result
))
1577 /* Set the last error and fail */
1578 //SetLastWin32Error(RtlNtStatusToDosError(Result));
1582 /* Validate the system call number again */
1583 if (Id
>= DescriptorTable
->Limit
)
1586 Result
= STATUS_INVALID_SYSTEM_SERVICE
;
1591 /* Check if this is a GUI call */
1592 if (__builtin_expect(Offset
& SERVICE_TABLE_TEST
, 0))
1594 /* Get the batch count and flush if necessary */
1595 if (NtCurrentTeb()->GdiBatchCount
) KeGdiFlushUserBatch();
1598 /* Increase system call count */
1599 KeGetCurrentPrcb()->KeSystemCalls
++;
1601 /* FIXME: Increase individual counts on debug systems */
1602 //KiIncreaseSystemCallCount(DescriptorTable, Id);
1604 /* Get stack bytes */
1605 StackBytes
= DescriptorTable
->Number
[Id
];
1607 /* Probe caller stack */
1608 if (__builtin_expect((Arguments
< (PVOID
)MmUserProbeAddress
) && !(KiUserTrap(TrapFrame
)), 0))
1610 /* Access violation */
1611 UNIMPLEMENTED_FATAL();
1614 /* Call pre-service debug hook */
1615 KiDbgPreServiceHook(SystemCallNumber
, Arguments
);
1617 /* Get the handler and make the system call */
1618 Handler
= (PVOID
)DescriptorTable
->Base
[Id
];
1619 Result
= KiSystemCallTrampoline(Handler
, Arguments
, StackBytes
);
1621 /* Call post-service debug hook */
1622 Result
= KiDbgPostServiceHook(SystemCallNumber
, Result
);
1624 /* Make sure we're exiting correctly */
1625 KiExitSystemCallDebugChecks(Id
, TrapFrame
);
1627 /* Restore the old trap frame */
1629 Thread
->TrapFrame
= (PKTRAP_FRAME
)TrapFrame
->Edx
;
1631 /* Exit from system call */
1632 KiServiceExit(TrapFrame
, Result
);
1638 KiSystemServiceHandler(IN PKTRAP_FRAME TrapFrame
,
1641 /* Call the shared handler (inline) */
1642 KiSystemCall(TrapFrame
, Arguments
);
1648 KiFastCallEntryHandler(IN PKTRAP_FRAME TrapFrame
,
1651 /* Set up a fake INT Stack and enable interrupts */
1652 TrapFrame
->HardwareSegSs
= KGDT_R3_DATA
| RPL_MASK
;
1653 TrapFrame
->HardwareEsp
= (ULONG_PTR
)Arguments
;
1654 TrapFrame
->EFlags
= __readeflags() | EFLAGS_INTERRUPT_MASK
;
1655 TrapFrame
->SegCs
= KGDT_R3_CODE
| RPL_MASK
;
1656 TrapFrame
->Eip
= SharedUserData
->SystemCallReturn
;
1657 TrapFrame
->SegFs
= KGDT_R3_TEB
| RPL_MASK
;
1660 /* Arguments are actually 2 frames down (because of the double indirection) */
1661 Arguments
= (PVOID
)(TrapFrame
->HardwareEsp
+ 8);
1663 /* Call the shared handler (inline) */
1664 KiSystemCall(TrapFrame
, Arguments
);
1672 Kei386EoiHelper(VOID
)
1674 /* We should never see this call happening */
1675 ERROR_FATAL("Mismatched NT/HAL version");