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 */
670 /* Bring IRQL back */
671 KfLowerIrql(OldIrql
);
674 /* Do a quick V86 exit if possible */
675 KiExitV86Trap(TrapFrame
);
678 /* Save trap frame */
679 KiEnterTrap(TrapFrame
);
681 /* Enable interrupts */
682 Instruction
= (PUCHAR
)TrapFrame
->Eip
;
685 /* Check for user trap */
686 if (KiUserTrap(TrapFrame
))
690 /* Scan next 4 opcodes */
691 for (i
= 0; i
< 4; i
++)
693 /* Check for LOCK instruction */
694 if (Instruction
[i
] == 0xF0)
696 /* Send invalid lock sequence exception */
697 KiDispatchException0Args(STATUS_INVALID_LOCK_SEQUENCE
,
703 /* FIXME: SEH ends here */
706 /* Kernel-mode or user-mode fault (but not LOCK) */
707 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
716 KiTrap07Handler(IN PKTRAP_FRAME TrapFrame
)
718 PKTHREAD Thread
, NpxThread
;
719 PFX_SAVE_AREA SaveArea
, NpxSaveArea
;
722 /* Save trap frame */
723 KiEnterTrap(TrapFrame
);
725 /* Try to handle NPX delay load */
728 /* Get the current thread */
729 Thread
= KeGetCurrentThread();
731 /* Get the NPX frame */
732 SaveArea
= KiGetThreadNpxArea(Thread
);
734 /* Check if emulation is enabled */
735 if (SaveArea
->Cr0NpxState
& CR0_EM
)
737 /* Not implemented */
743 /* Save CR0 and check NPX state */
745 if (Thread
->NpxState
!= NPX_STATE_LOADED
)
748 Cr0
&= ~(CR0_MP
| CR0_EM
| CR0_TS
);
751 /* Get the NPX thread */
752 NpxThread
= KeGetCurrentPrcb()->NpxThread
;
755 /* Get the NPX frame */
756 NpxSaveArea
= KiGetThreadNpxArea(NpxThread
);
759 DPRINT("FIXME: Save FPU state: %p\n", NpxSaveArea
);
760 //Ke386SaveFpuState(NpxSaveArea);
762 /* Update NPX state */
763 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
767 //Ke386LoadFpuState(SaveArea);
769 /* Update NPX state */
770 Thread
->NpxState
= NPX_STATE_LOADED
;
771 KeGetCurrentPrcb()->NpxThread
= Thread
;
773 /* Enable interrupts */
776 /* Check if CR0 needs to be reloaded due to context switch */
777 if (!SaveArea
->Cr0NpxState
) KiEoiHelper(TrapFrame
);
779 /* Otherwise, we need to reload CR0, disable interrupts */
784 Cr0
|= SaveArea
->Cr0NpxState
;
787 /* Now restore interrupts and check for TS */
789 if (Cr0
& CR0_TS
) KiEoiHelper(TrapFrame
);
791 /* We're still here -- clear TS and try again */
792 __writecr0(__readcr0() &~ CR0_TS
);
797 /* This is an actual fault, not a lack of FPU state */
802 /* TS should not be set */
806 * If it's incorrectly set, then maybe the state is actually still valid
807 * but we could've lock track of that due to a BIOS call.
808 * Make sure MP is still set, which should verify the theory.
812 /* Indeed, the state is actually still valid, so clear TS */
813 __writecr0(__readcr0() &~ CR0_TS
);
814 KiEoiHelper(TrapFrame
);
817 /* Otherwise, something strange is going on */
818 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 2, Cr0
, 0, 0, TrapFrame
);
821 /* It's not a delayed load, so process this trap as an NPX fault */
822 KiNpxHandler(TrapFrame
, Thread
, SaveArea
);
828 KiTrap08Handler(IN PKTRAP_FRAME TrapFrame
)
830 /* FIXME: Not handled */
831 KiSystemFatalException(EXCEPTION_DOUBLE_FAULT
, TrapFrame
);
837 KiTrap09Handler(IN PKTRAP_FRAME TrapFrame
)
839 /* Save trap frame */
840 KiEnterTrap(TrapFrame
);
842 /* Enable interrupts and kill the system */
844 KiSystemFatalException(EXCEPTION_NPX_OVERRUN
, TrapFrame
);
850 KiTrap0AHandler(IN PKTRAP_FRAME TrapFrame
)
852 /* Save trap frame */
853 KiEnterTrap(TrapFrame
);
855 /* Check for VDM trap */
856 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
858 /* Kill the system */
859 KiSystemFatalException(EXCEPTION_INVALID_TSS
, TrapFrame
);
865 KiTrap0BHandler(IN PKTRAP_FRAME TrapFrame
)
867 /* Save trap frame */
868 KiEnterTrap(TrapFrame
);
870 /* FIXME: Kill the system */
872 KiSystemFatalException(EXCEPTION_SEGMENT_NOT_PRESENT
, TrapFrame
);
878 KiTrap0CHandler(IN PKTRAP_FRAME TrapFrame
)
880 /* Save trap frame */
881 KiEnterTrap(TrapFrame
);
883 /* FIXME: Kill the system */
885 KiSystemFatalException(EXCEPTION_STACK_FAULT
, TrapFrame
);
891 KiTrap0DHandler(IN PKTRAP_FRAME TrapFrame
)
894 BOOLEAN Privileged
= FALSE
;
896 UCHAR Instruction
= 0;
899 /* Check for V86 GPF */
900 if (__builtin_expect(KiV86Trap(TrapFrame
), 1))
903 KiEnterV86Trap(TrapFrame
);
905 /* Must be a VDM process */
906 if (__builtin_expect(!PsGetCurrentProcess()->VdmObjects
, 0))
908 /* Enable interrupts */
911 /* Setup illegal instruction fault */
912 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
917 /* Go to APC level */
918 OldIrql
= KfRaiseIrql(APC_LEVEL
);
921 /* Handle the V86 opcode */
922 if (__builtin_expect(Ki386HandleOpcodeV86(TrapFrame
) == 0xFF, 0))
924 /* Should only happen in VDM mode */
930 /* Bring IRQL back */
931 KfLowerIrql(OldIrql
);
934 /* Do a quick V86 exit if possible */
935 KiExitV86Trap(TrapFrame
);
938 /* Save trap frame */
939 KiEnterTrap(TrapFrame
);
941 /* Check for user-mode GPF */
942 if (KiUserTrap(TrapFrame
))
944 /* Should not be VDM */
945 ASSERT(KiVdmTrap(TrapFrame
) == FALSE
);
947 /* Enable interrupts and check error code */
949 if (!TrapFrame
->ErrCode
)
952 Instructions
= (PUCHAR
)TrapFrame
->Eip
;
954 /* Scan next 15 bytes */
955 for (i
= 0; i
< 15; i
++)
957 /* Skip prefix instructions */
958 for (j
= 0; j
< sizeof(KiTrapPrefixTable
); j
++)
960 /* Is this a prefix instruction? */
961 if (Instructions
[i
] == KiTrapPrefixTable
[j
])
968 /* Is this NOT any prefix instruction? */
969 if (j
== sizeof(KiTrapPrefixTable
))
971 /* We can go ahead and handle the fault now */
972 Instruction
= Instructions
[i
];
977 /* If all we found was prefixes, then this instruction is too long */
980 /* Setup illegal instruction fault */
981 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION
,
986 /* Check for privileged instructions */
987 DPRINT("Instruction (%d) at fault: %lx %lx %lx %lx\n",
992 Instructions
[i
+ 3]);
993 if (Instruction
== 0xF4) // HLT
995 /* HLT is privileged */
998 else if (Instruction
== 0x0F)
1000 /* Test if it's any of the privileged two-byte opcodes */
1001 if (((Instructions
[i
+ 1] == 0x00) && // LLDT or LTR
1002 (((Instructions
[i
+ 2] & 0x38) == 0x10) || // LLDT
1003 (Instructions
[i
+ 2] == 0x18))) || // LTR
1004 ((Instructions
[i
+ 1] == 0x01) && // LGDT or LIDT or LMSW
1005 (((Instructions
[i
+ 2] & 0x38) == 0x10) || // LGDT
1006 (Instructions
[i
+ 2] == 0x18) || // LIDT
1007 (Instructions
[i
+ 2] == 0x30))) || // LMSW
1008 (Instructions
[i
+ 1] == 0x08) || // INVD
1009 (Instructions
[i
+ 1] == 0x09) || // WBINVD
1010 (Instructions
[i
+ 1] == 0x35) || // SYSEXIT
1011 (Instructions
[i
+ 1] == 0x21) || // MOV DR, XXX
1012 (Instructions
[i
+ 1] == 0x06) || // CLTS
1013 (Instructions
[i
+ 1] == 0x20) || // MOV CR, XXX
1014 (Instructions
[i
+ 1] == 0x22) || // MOV XXX, CR
1015 (Instructions
[i
+ 1] == 0x23) || // MOV YYY, DR
1016 (Instructions
[i
+ 1] == 0x30) || // WRMSR
1017 (Instructions
[i
+ 1] == 0x33)) // RDPMC
1018 // INVLPG, INVLPGA, SYSRET
1020 /* These are all privileged */
1026 /* Get the IOPL and compare with the RPL mask */
1027 Iopl
= (TrapFrame
->EFlags
& EFLAGS_IOPL
) >> 12;
1028 if ((TrapFrame
->SegCs
& RPL_MASK
) > Iopl
)
1030 /* I/O privilege error -- check for known instructions */
1031 if ((Instruction
== 0xFA) || (Instruction
== 0xFB)) // CLI or STI
1033 /* These are privileged */
1038 /* Last hope: an IN/OUT instruction */
1039 for (j
= 0; j
< sizeof(KiTrapIoTable
); j
++)
1041 /* Is this an I/O instruction? */
1042 if (Instruction
== KiTrapIoTable
[j
])
1044 /* Then it's privileged */
1053 /* So now... was the instruction privileged or not? */
1056 /* Whew! We have a privileged instruction, so dispatch the fault */
1057 KiDispatchException0Args(STATUS_PRIVILEGED_INSTRUCTION
,
1063 /* If we got here, send an access violation */
1064 KiDispatchException2Args(STATUS_ACCESS_VIOLATION
,
1072 * Check for a fault during checking of the user instruction.
1074 * Note that the SEH handler will catch invalid EIP, but we could be dealing
1075 * with an invalid CS, which will generate another GPF instead.
1078 if (((PVOID
)TrapFrame
->Eip
>= (PVOID
)KiTrap0DHandler
) &&
1079 ((PVOID
)TrapFrame
->Eip
< (PVOID
)KiTrap0DHandler
))
1081 /* Not implemented */
1088 * NOTE: The ASM trap exit code would restore segment registers by doing
1089 * a POP <SEG>, which could cause an invalid segment if someone had messed
1090 * with the segment values.
1092 * Another case is a bogus SS, which would hit a GPF when doing the iret.
1093 * This could only be done through a buggy or malicious driver, or perhaps
1094 * the kernel debugger.
1096 * The kernel normally restores the "true" segment if this happens.
1098 * However, since we're restoring in C, not ASM, we can't detect
1099 * POP <SEG> since the actual instructions will be different.
1101 * A better technique would be to check the EIP and somehow edit the
1102 * trap frame before restarting the instruction -- but we would need to
1103 * know the extract instruction that was used first.
1105 * We could force a special instrinsic to use stack instructions, or write
1106 * a simple instruction length checker.
1108 * Nevertheless, this is a lot of work for the purpose of avoiding a crash
1109 * when the user is purposedly trying to create one from kernel-mode, so
1110 * we should probably table this for now since it's not a "real" issue.
1114 * NOTE2: Another scenario is the IRET during a V8086 restore (BIOS Call)
1115 * which will cause a GPF since the trap frame is a total mess (on purpose)
1116 * as built in KiEnterV86Mode.
1118 * The idea is to scan for IRET, scan for the known EIP adress, validate CS
1119 * and then manually issue a jump to the V8086 return EIP.
1121 Instructions
= (PUCHAR
)TrapFrame
->Eip
;
1122 if (Instructions
[0] == 0xCF)
1125 * Some evil shit is going on here -- this is not the SS:ESP you're
1126 * looking for! Instead, this is actually CS:EIP you're looking at!
1127 * Why? Because part of the trap frame actually corresponds to the IRET
1128 * stack during the trap exit!
1130 if ((TrapFrame
->HardwareEsp
== (ULONG
)Ki386BiosCallReturnAddress
) &&
1131 (TrapFrame
->HardwareSegSs
== (KGDT_R0_CODE
| RPL_MASK
)))
1133 /* Exit the V86 trap! */
1134 Ki386BiosCallReturnAddress(TrapFrame
);
1138 /* Otherwise, this is another kind of IRET fault */
1145 /* So since we're not dealing with the above case, check for RDMSR/WRMSR */
1146 if ((Instructions
[0] == 0xF) && // 2-byte opcode
1147 ((Instructions
[1] == 0x32) || // RDMSR
1148 (Instructions
[1] == 0x30))) // WRMSR
1150 /* Unknown CPU MSR, so raise an access violation */
1151 KiDispatchException0Args(STATUS_ACCESS_VIOLATION
,
1156 /* Check for lazy segment load */
1157 if (TrapFrame
->SegDs
!= (KGDT_R3_DATA
| RPL_MASK
))
1160 TrapFrame
->SegDs
= (KGDT_R3_DATA
| RPL_MASK
);
1162 else if (TrapFrame
->SegEs
!= (KGDT_R3_DATA
| RPL_MASK
))
1165 TrapFrame
->SegEs
= (KGDT_R3_DATA
| RPL_MASK
);
1169 /* Whatever it is, we can't handle it */
1170 KiSystemFatalException(EXCEPTION_GP_FAULT
, TrapFrame
);
1173 /* Return to where we came from */
1174 KiTrapReturn(TrapFrame
);
1180 KiTrap0EHandler(IN PKTRAP_FRAME TrapFrame
)
1186 /* Save trap frame */
1187 KiEnterTrap(TrapFrame
);
1189 /* Check if this is the base frame */
1190 Thread
= KeGetCurrentThread();
1191 if (KeGetTrapFrame(Thread
) != TrapFrame
)
1193 /* It isn't, check if this is a second nested frame */
1194 if (((ULONG_PTR
)KeGetTrapFrame(Thread
) - (ULONG_PTR
)TrapFrame
) <=
1195 FIELD_OFFSET(KTRAP_FRAME
, EFlags
))
1197 /* The stack is somewhere in between frames, we need to fix it */
1207 /* Enable interupts */
1210 /* Check if we came in with interrupts disabled */
1211 if (!(TrapFrame
->EFlags
& EFLAGS_INTERRUPT_MASK
))
1213 /* This is completely illegal, bugcheck the system */
1214 KeBugCheckWithTf(IRQL_NOT_LESS_OR_EQUAL
,
1217 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1222 /* Check for S-LIST fault in kernel mode */
1223 if (TrapFrame
->Eip
== (ULONG_PTR
)ExpInterlockedPopEntrySListFault
)
1225 PSLIST_HEADER SListHeader
;
1227 /* Sanity check that the assembly is correct:
1228 This must be mov ebx, [eax]
1229 Followed by cmpxchg8b [ebp] */
1230 ASSERT((((UCHAR
*)TrapFrame
->Eip
)[0] == 0x8B) &&
1231 (((UCHAR
*)TrapFrame
->Eip
)[1] == 0x18) &&
1232 (((UCHAR
*)TrapFrame
->Eip
)[2] == 0x0F) &&
1233 (((UCHAR
*)TrapFrame
->Eip
)[3] == 0xC7) &&
1234 (((UCHAR
*)TrapFrame
->Eip
)[4] == 0x4D) &&
1235 (((UCHAR
*)TrapFrame
->Eip
)[5] == 0x00));
1237 /* Get the pointer to the SLIST_HEADER */
1238 SListHeader
= (PSLIST_HEADER
)TrapFrame
->Ebp
;
1240 /* Check if the Next member of the SLIST_HEADER was changed */
1241 if (SListHeader
->Next
.Next
!= (PSLIST_ENTRY
)TrapFrame
->Eax
)
1243 /* Restart the operation */
1244 TrapFrame
->Eip
= (ULONG_PTR
)ExpInterlockedPopEntrySListResume
;
1246 /* Continue execution */
1247 KiEoiHelper(TrapFrame
);
1251 /* Call the access fault handler */
1252 Status
= MmAccessFault(TrapFrame
->ErrCode
& 1,
1254 TrapFrame
->SegCs
& MODE_MASK
,
1256 if (NT_SUCCESS(Status
)) KiEoiHelper(TrapFrame
);
1258 /* Check for syscall fault */
1260 if ((TrapFrame
->Eip
== (ULONG_PTR
)CopyParams
) ||
1261 (TrapFrame
->Eip
== (ULONG_PTR
)ReadBatch
))
1263 /* Not yet implemented */
1269 /* Check for VDM trap */
1270 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
1272 /* Either kernel or user trap (non VDM) so dispatch exception */
1273 if (Status
== STATUS_ACCESS_VIOLATION
)
1275 /* This status code is repurposed so we can recognize it later */
1276 KiDispatchException2Args(KI_EXCEPTION_ACCESS_VIOLATION
,
1278 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1282 else if ((Status
== STATUS_GUARD_PAGE_VIOLATION
) ||
1283 (Status
== STATUS_STACK_OVERFLOW
))
1285 /* These faults only have two parameters */
1286 KiDispatchException2Args(Status
,
1288 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1293 /* Only other choice is an in-page error, with 3 parameters */
1294 KiDispatchExceptionFromTrapFrame(STATUS_IN_PAGE_ERROR
,
1297 TrapFrame
->ErrCode
& 2 ? TRUE
: FALSE
,
1306 KiTrap0FHandler(IN PKTRAP_FRAME TrapFrame
)
1308 /* Save trap frame */
1309 KiEnterTrap(TrapFrame
);
1311 /* FIXME: Kill the system */
1313 KiSystemFatalException(EXCEPTION_RESERVED_TRAP
, TrapFrame
);
1319 KiTrap10Handler(IN PKTRAP_FRAME TrapFrame
)
1322 PFX_SAVE_AREA SaveArea
;
1324 /* Save trap frame */
1325 KiEnterTrap(TrapFrame
);
1327 /* Check if this is the NPX thrad */
1328 Thread
= KeGetCurrentThread();
1329 SaveArea
= KiGetThreadNpxArea(Thread
);
1330 if (Thread
!= KeGetCurrentPrcb()->NpxThread
)
1332 /* It isn't, enable interrupts and set delayed error */
1334 SaveArea
->Cr0NpxState
|= CR0_TS
;
1337 KiEoiHelper(TrapFrame
);
1340 /* Otherwise, proceed with NPX fault handling */
1341 KiNpxHandler(TrapFrame
, Thread
, SaveArea
);
1347 KiTrap11Handler(IN PKTRAP_FRAME TrapFrame
)
1349 /* Save trap frame */
1350 KiEnterTrap(TrapFrame
);
1352 /* Enable interrupts and kill the system */
1354 KiSystemFatalException(EXCEPTION_ALIGNMENT_CHECK
, TrapFrame
);
1360 KiTrap13Handler(IN PKTRAP_FRAME TrapFrame
)
1363 PFX_SAVE_AREA SaveArea
;
1364 ULONG Cr0
, MxCsrMask
, Error
;
1366 /* Save trap frame */
1367 KiEnterTrap(TrapFrame
);
1369 /* Check if this is the NPX thrad */
1370 Thread
= KeGetCurrentThread();
1371 if (Thread
!= KeGetCurrentPrcb()->NpxThread
)
1373 /* It isn't, kill the system */
1374 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 13, (ULONG_PTR
)Thread
, 0, 0, TrapFrame
);
1377 /* Get the NPX frame */
1378 SaveArea
= KiGetThreadNpxArea(Thread
);
1380 /* Check for VDM trap */
1381 ASSERT((KiVdmTrap(TrapFrame
)) == FALSE
);
1383 /* Check for user trap */
1384 if (!KiUserTrap(TrapFrame
))
1386 /* Kernel should not fault on XMMI */
1387 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 13, 0, 0, 2, TrapFrame
);
1392 Cr0
&= ~(CR0_MP
| CR0_EM
| CR0_TS
);
1395 /* Save FPU state */
1396 Ke386SaveFpuState(SaveArea
);
1398 /* Mark CR0 state dirty */
1399 Cr0
|= NPX_STATE_NOT_LOADED
;
1400 Cr0
|= SaveArea
->Cr0NpxState
;
1403 /* Update NPX state */
1404 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
1405 KeGetCurrentPrcb()->NpxThread
= NULL
;
1407 /* Clear the TS bit and re-enable interrupts */
1408 SaveArea
->Cr0NpxState
&= ~CR0_TS
;
1411 /* Now look at MxCsr to get the mask of errors we should care about */
1412 MxCsrMask
= ~((USHORT
)SaveArea
->U
.FxArea
.MXCsr
>> 7);
1414 /* Get legal exceptions that software should handle */
1415 Error
= (USHORT
)SaveArea
->U
.FxArea
.MXCsr
& (FSW_INVALID_OPERATION
|
1423 /* Now handle any of those legal errors */
1424 if (Error
& (FSW_INVALID_OPERATION
|
1431 /* By issuing an exception */
1432 KiDispatchException1Args(STATUS_FLOAT_MULTIPLE_TRAPS
,
1438 /* Unknown XMMI fault */
1439 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN
, 13, 0, 0, 1, TrapFrame
);
1442 /* SOFTWARE SERVICES **********************************************************/
1446 KiGetTickCountHandler(IN PKTRAP_FRAME TrapFrame
)
1449 ASSERT(FALSE
); // while (TRUE);
1454 KiCallbackReturnHandler(IN PKTRAP_FRAME TrapFrame
)
1457 ASSERT(FALSE
); // while (TRUE);
1463 KiRaiseAssertionHandler(IN PKTRAP_FRAME TrapFrame
)
1465 /* Save trap frame */
1466 KiEnterTrap(TrapFrame
);
1468 /* Decrement EIP to point to the INT2C instruction (2 bytes, not 1 like INT3) */
1469 TrapFrame
->Eip
-= 2;
1471 /* Dispatch the exception */
1472 KiDispatchException0Args(STATUS_ASSERTION_FAILURE
,
1480 KiDebugServiceHandler(IN PKTRAP_FRAME TrapFrame
)
1482 /* Save trap frame */
1483 KiEnterTrap(TrapFrame
);
1485 /* Increment EIP to skip the INT3 instruction */
1488 /* Continue with the common handler */
1489 KiDebugHandler(TrapFrame
, TrapFrame
->Eax
, TrapFrame
->Ecx
, TrapFrame
->Edx
);
1495 KiDbgPreServiceHook(ULONG SystemCallNumber
, PULONG_PTR Arguments
)
1497 #if DBG && !defined(_WINKD_)
1498 if (SystemCallNumber
>= 0x1000 && KeWin32PreServiceHook
)
1499 KeWin32PreServiceHook(SystemCallNumber
, Arguments
);
1505 KiDbgPostServiceHook(ULONG SystemCallNumber
, ULONG_PTR Result
)
1507 #if DBG && !defined(_WINKD_)
1508 if (SystemCallNumber
>= 0x1000 && KeWin32PostServiceHook
)
1509 return KeWin32PostServiceHook(SystemCallNumber
, Result
);
1517 KiSystemCall(IN PKTRAP_FRAME TrapFrame
,
1521 PKSERVICE_TABLE_DESCRIPTOR DescriptorTable
;
1522 ULONG Id
, Offset
, StackBytes
, Result
;
1524 ULONG SystemCallNumber
= TrapFrame
->Eax
;
1526 /* Get the current thread */
1527 Thread
= KeGetCurrentThread();
1529 /* Set debug header */
1530 KiFillTrapFrameDebug(TrapFrame
);
1532 /* Chain trap frames */
1533 TrapFrame
->Edx
= (ULONG_PTR
)Thread
->TrapFrame
;
1536 TrapFrame
->ErrCode
= 0;
1538 /* Save previous mode */
1539 TrapFrame
->PreviousPreviousMode
= Thread
->PreviousMode
;
1541 /* Save the SEH chain and terminate it for now */
1542 TrapFrame
->ExceptionList
= KeGetPcr()->NtTib
.ExceptionList
;
1543 KeGetPcr()->NtTib
.ExceptionList
= EXCEPTION_CHAIN_END
;
1545 /* Default to debugging disabled */
1548 /* Check if the frame was from user mode */
1549 if (TrapFrame
->SegCs
& MODE_MASK
)
1551 /* Check for active debugging */
1552 if (KeGetCurrentThread()->Header
.DebugActive
& 0xFF)
1554 /* Handle debug registers */
1555 KiHandleDebugRegistersOnTrapEntry(TrapFrame
);
1559 /* Set thread fields */
1560 Thread
->TrapFrame
= TrapFrame
;
1561 Thread
->PreviousMode
= KiUserTrap(TrapFrame
);
1563 /* Enable interrupts */
1566 /* Decode the system call number */
1567 Offset
= (SystemCallNumber
>> SERVICE_TABLE_SHIFT
) & SERVICE_TABLE_MASK
;
1568 Id
= SystemCallNumber
& SERVICE_NUMBER_MASK
;
1570 /* Get descriptor table */
1571 DescriptorTable
= (PVOID
)((ULONG_PTR
)Thread
->ServiceTable
+ Offset
);
1573 /* Validate the system call number */
1574 if (__builtin_expect(Id
>= DescriptorTable
->Limit
, 0))
1576 /* Check if this is a GUI call */
1577 if (!(Offset
& SERVICE_TABLE_TEST
))
1580 Result
= STATUS_INVALID_SYSTEM_SERVICE
;
1584 /* Convert us to a GUI thread -- must wrap in ASM to get new EBP */
1585 Result
= KiConvertToGuiThread();
1587 /* Reload trap frame and descriptor table pointer from new stack */
1588 TrapFrame
= *(volatile PVOID
*)&Thread
->TrapFrame
;
1589 DescriptorTable
= (PVOID
)(*(volatile ULONG_PTR
*)&Thread
->ServiceTable
+ Offset
);
1591 if (!NT_SUCCESS(Result
))
1593 /* Set the last error and fail */
1594 //SetLastWin32Error(RtlNtStatusToDosError(Result));
1598 /* Validate the system call number again */
1599 if (Id
>= DescriptorTable
->Limit
)
1602 Result
= STATUS_INVALID_SYSTEM_SERVICE
;
1607 /* Check if this is a GUI call */
1608 if (__builtin_expect(Offset
& SERVICE_TABLE_TEST
, 0))
1610 /* Get the batch count and flush if necessary */
1611 if (NtCurrentTeb()->GdiBatchCount
) KeGdiFlushUserBatch();
1614 /* Increase system call count */
1615 KeGetCurrentPrcb()->KeSystemCalls
++;
1617 /* FIXME: Increase individual counts on debug systems */
1618 //KiIncreaseSystemCallCount(DescriptorTable, Id);
1620 /* Get stack bytes */
1621 StackBytes
= DescriptorTable
->Number
[Id
];
1623 /* Probe caller stack */
1624 if (__builtin_expect((Arguments
< (PVOID
)MmUserProbeAddress
) && !(KiUserTrap(TrapFrame
)), 0))
1626 /* Access violation */
1632 /* Call pre-service debug hook */
1633 KiDbgPreServiceHook(SystemCallNumber
, Arguments
);
1635 /* Get the handler and make the system call */
1636 Handler
= (PVOID
)DescriptorTable
->Base
[Id
];
1637 Result
= KiSystemCallTrampoline(Handler
, Arguments
, StackBytes
);
1639 /* Call post-service debug hook */
1640 Result
= KiDbgPostServiceHook(SystemCallNumber
, Result
);
1642 /* Make sure we're exiting correctly */
1643 KiExitSystemCallDebugChecks(Id
, TrapFrame
);
1645 /* Restore the old trap frame */
1647 Thread
->TrapFrame
= (PKTRAP_FRAME
)TrapFrame
->Edx
;
1649 /* Exit from system call */
1650 KiServiceExit(TrapFrame
, Result
);
1656 KiSystemServiceHandler(IN PKTRAP_FRAME TrapFrame
,
1659 /* Call the shared handler (inline) */
1660 KiSystemCall(TrapFrame
, Arguments
);
1666 KiFastCallEntryHandler(IN PKTRAP_FRAME TrapFrame
,
1669 /* Set up a fake INT Stack and enable interrupts */
1670 TrapFrame
->HardwareSegSs
= KGDT_R3_DATA
| RPL_MASK
;
1671 TrapFrame
->HardwareEsp
= (ULONG_PTR
)Arguments
;
1672 TrapFrame
->EFlags
= __readeflags() | EFLAGS_INTERRUPT_MASK
;
1673 TrapFrame
->SegCs
= KGDT_R3_CODE
| RPL_MASK
;
1674 TrapFrame
->Eip
= SharedUserData
->SystemCallReturn
;
1675 TrapFrame
->SegFs
= KGDT_R3_TEB
| RPL_MASK
;
1678 /* Arguments are actually 2 frames down (because of the double indirection) */
1679 Arguments
= (PVOID
)(TrapFrame
->HardwareEsp
+ 8);
1681 /* Call the shared handler (inline) */
1682 KiSystemCall(TrapFrame
, Arguments
);
1690 Kei386EoiHelper(VOID
)
1692 /* We should never see this call happening */
1693 DPRINT1("Mismatched NT/HAL version");