Synchronize with trunk's revision r57652.
[reactos.git] / ntoskrnl / ke / i386 / traphdlr.c
1 /*
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
7 */
8
9 /* INCLUDES *******************************************************************/
10
11 #include <ntoskrnl.h>
12 #define NDEBUG
13 #include <debug.h>
14
15 /* GLOBALS ********************************************************************/
16
17 UCHAR KiTrapPrefixTable[] =
18 {
19 0xF2, /* REP */
20 0xF3, /* REP INS/OUTS */
21 0x67, /* ADDR */
22 0xF0, /* LOCK */
23 0x66, /* OP */
24 0x2E, /* SEG */
25 0x3E, /* DS */
26 0x26, /* ES */
27 0x64, /* FS */
28 0x65, /* GS */
29 0x36, /* SS */
30 };
31
32 UCHAR KiTrapIoTable[] =
33 {
34 0xE4, /* IN */
35 0xE5, /* IN */
36 0xEC, /* IN */
37 0xED, /* IN */
38 0x6C, /* INS */
39 0x6D, /* INS */
40 0xE6, /* OUT */
41 0xE7, /* OUT */
42 0xEE, /* OUT */
43 0xEF, /* OUT */
44 0x6E, /* OUTS */
45 0x6F, /* OUTS */
46 };
47
48 PFAST_SYSTEM_CALL_EXIT KiFastCallExitHandler;
49 #if DBG && !defined(_WINKD_)
50 PKDBG_PRESERVICEHOOK KeWin32PreServiceHook = NULL;
51 PKDBG_POSTSERVICEHOOK KeWin32PostServiceHook = NULL;
52 #endif
53 #if TRAP_DEBUG
54 BOOLEAN StopChecking = FALSE;
55 #endif
56
57
58 /* TRAP EXIT CODE *************************************************************/
59
60 BOOLEAN
61 FORCEINLINE
62 KiVdmTrap(IN PKTRAP_FRAME TrapFrame)
63 {
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)));
67 }
68
69 BOOLEAN
70 FORCEINLINE
71 KiV86Trap(IN PKTRAP_FRAME TrapFrame)
72 {
73 /* Check if the V8086 flag is on */
74 return ((TrapFrame->EFlags & EFLAGS_V86_MASK) != 0);
75 }
76
77 BOOLEAN
78 FORCEINLINE
79 KiIsFrameEdited(IN PKTRAP_FRAME TrapFrame)
80 {
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);
84 }
85
86 VOID
87 FORCEINLINE
88 KiCommonExit(IN PKTRAP_FRAME TrapFrame, BOOLEAN SkipPreviousMode)
89 {
90 /* Disable interrupts until we return */
91 _disable();
92
93 /* Check for APC delivery */
94 KiCheckForApcDelivery(TrapFrame);
95
96 /* Restore the SEH handler chain */
97 KeGetPcr()->NtTib.ExceptionList = TrapFrame->ExceptionList;
98
99 /* Check if there are active debug registers */
100 if (__builtin_expect(TrapFrame->Dr7 & ~DR7_RESERVED_MASK, 0))
101 {
102 /* Check if the frame was from user mode or v86 mode */
103 if ((TrapFrame->SegCs & MODE_MASK) ||
104 (TrapFrame->EFlags & EFLAGS_V86_MASK))
105 {
106 /* Handle debug registers */
107 KiHandleDebugRegistersOnTrapExit(TrapFrame);
108 }
109 }
110
111 /* Debugging checks */
112 KiExitTrapDebugChecks(TrapFrame, SkipPreviousMode);
113 }
114
115 DECLSPEC_NORETURN
116 VOID
117 FASTCALL
118 KiEoiHelper(IN PKTRAP_FRAME TrapFrame)
119 {
120 /* Common trap exit code */
121 KiCommonExit(TrapFrame, TRUE);
122
123 /* Check if this was a V8086 trap */
124 if (TrapFrame->EFlags & EFLAGS_V86_MASK) KiTrapReturnNoSegments(TrapFrame);
125
126 /* Check for user mode exit */
127 if (TrapFrame->SegCs & MODE_MASK) KiTrapReturn(TrapFrame);
128
129 /* Check for edited frame */
130 if (KiIsFrameEdited(TrapFrame)) KiEditedTrapReturn(TrapFrame);
131
132 /* Exit the trap to kernel mode */
133 KiTrapReturnNoSegments(TrapFrame);
134 }
135
136 DECLSPEC_NORETURN
137 VOID
138 FASTCALL
139 KiServiceExit(IN PKTRAP_FRAME TrapFrame,
140 IN NTSTATUS Status)
141 {
142 ASSERT((TrapFrame->EFlags & EFLAGS_V86_MASK) == 0);
143 ASSERT(!KiIsFrameEdited(TrapFrame));
144
145 /* Copy the status into EAX */
146 TrapFrame->Eax = Status;
147
148 /* Common trap exit code */
149 KiCommonExit(TrapFrame, FALSE);
150
151 /* Restore previous mode */
152 KeGetCurrentThread()->PreviousMode = (CCHAR)TrapFrame->PreviousPreviousMode;
153
154 /* Check for user mode exit */
155 if (TrapFrame->SegCs & MODE_MASK)
156 {
157 /* Check if we were single stepping */
158 if (TrapFrame->EFlags & EFLAGS_TF)
159 {
160 /* Must use the IRET handler */
161 KiSystemCallTrapReturn(TrapFrame);
162 }
163 else
164 {
165 /* We can use the sysexit handler */
166 KiFastCallExitHandler(TrapFrame);
167 }
168 }
169
170 /* Exit to kernel mode */
171 KiSystemCallReturn(TrapFrame);
172 }
173
174 DECLSPEC_NORETURN
175 VOID
176 FASTCALL
177 KiServiceExit2(IN PKTRAP_FRAME TrapFrame)
178 {
179 /* Common trap exit code */
180 KiCommonExit(TrapFrame, FALSE);
181
182 /* Restore previous mode */
183 KeGetCurrentThread()->PreviousMode = (CCHAR)TrapFrame->PreviousPreviousMode;
184
185 /* Check if this was a V8086 trap */
186 if (TrapFrame->EFlags & EFLAGS_V86_MASK) KiTrapReturnNoSegments(TrapFrame);
187
188 /* Check for user mode exit */
189 if (TrapFrame->SegCs & MODE_MASK) KiTrapReturn(TrapFrame);
190
191 /* Check for edited frame */
192 if (KiIsFrameEdited(TrapFrame)) KiEditedTrapReturn(TrapFrame);
193
194 /* Exit the trap to kernel mode */
195 KiTrapReturnNoSegments(TrapFrame);
196 }
197
198
199 /* TRAP HANDLERS **************************************************************/
200
201 DECLSPEC_NORETURN
202 VOID
203 FASTCALL
204 KiDebugHandler(IN PKTRAP_FRAME TrapFrame,
205 IN ULONG Parameter1,
206 IN ULONG Parameter2,
207 IN ULONG Parameter3)
208 {
209 /* Check for VDM trap */
210 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
211
212 /* Enable interrupts if the trap came from user-mode */
213 if (KiUserTrap(TrapFrame)) _enable();
214
215 /* Dispatch the exception */
216 KiDispatchExceptionFromTrapFrame(STATUS_BREAKPOINT,
217 TrapFrame->Eip - 1,
218 3,
219 Parameter1,
220 Parameter2,
221 Parameter3,
222 TrapFrame);
223 }
224
225 DECLSPEC_NORETURN
226 VOID
227 FASTCALL
228 KiNpxHandler(IN PKTRAP_FRAME TrapFrame,
229 IN PKTHREAD Thread,
230 IN PFX_SAVE_AREA SaveArea)
231 {
232 ULONG Cr0, Mask, Error, ErrorOffset, DataOffset;
233
234 /* Check for VDM trap */
235 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
236
237 /* Check for kernel trap */
238 if (!KiUserTrap(TrapFrame))
239 {
240 /* Kernel might've tripped a delayed error */
241 SaveArea->Cr0NpxState |= CR0_TS;
242
243 /* Only valid if it happened during a restore */
244 //if ((PVOID)TrapFrame->Eip == FrRestore)
245 {
246 /* It did, so just skip the instruction */
247 //TrapFrame->Eip += 3; /* sizeof(FRSTOR) */
248 //KiEoiHelper(TrapFrame);
249 }
250 }
251
252 /* User or kernel trap -- get ready to issue an exception */
253 //if (Thread->NpxState == NPX_STATE_NOT_LOADED)
254 {
255 /* Update CR0 */
256 Cr0 = __readcr0();
257 Cr0 &= ~(CR0_MP | CR0_EM | CR0_TS);
258 __writecr0(Cr0);
259
260 /* Save FPU state */
261 Ke386SaveFpuState(SaveArea);
262
263 /* Mark CR0 state dirty */
264 Cr0 |= NPX_STATE_NOT_LOADED;
265 Cr0 |= SaveArea->Cr0NpxState;
266 __writecr0(Cr0);
267
268 /* Update NPX state */
269 Thread->NpxState = NPX_STATE_NOT_LOADED;
270 KeGetCurrentPrcb()->NpxThread = NULL;
271 }
272
273 /* Clear the TS bit and re-enable interrupts */
274 SaveArea->Cr0NpxState &= ~CR0_TS;
275 _enable();
276
277 /* Check if we should get the FN or FX error */
278 if (KeI386FxsrPresent)
279 {
280 /* Get it from FX */
281 Mask = SaveArea->U.FxArea.ControlWord;
282 Error = SaveArea->U.FxArea.StatusWord;
283
284 /* Get the FPU exception address too */
285 ErrorOffset = SaveArea->U.FxArea.ErrorOffset;
286 DataOffset = SaveArea->U.FxArea.DataOffset;
287 }
288 else
289 {
290 /* Get it from FN */
291 Mask = SaveArea->U.FnArea.ControlWord;
292 Error = SaveArea->U.FnArea.StatusWord;
293
294 /* Get the FPU exception address too */
295 ErrorOffset = SaveArea->U.FnArea.ErrorOffset;
296 DataOffset = SaveArea->U.FnArea.DataOffset;
297 }
298
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 |
303 FSW_DENORMAL |
304 FSW_ZERO_DIVIDE |
305 FSW_OVERFLOW |
306 FSW_UNDERFLOW |
307 FSW_PRECISION);
308 Error &= ~Mask;
309
310 /* Check for invalid operation */
311 if (Error & FSW_INVALID_OPERATION)
312 {
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)
317 {
318 /* Issue stack check fault */
319 KiDispatchException2Args(STATUS_FLOAT_STACK_CHECK,
320 ErrorOffset,
321 0,
322 DataOffset,
323 TrapFrame);
324 }
325
326 /* Issue fault */
327 KiDispatchException1Args(STATUS_FLOAT_INVALID_OPERATION,
328 ErrorOffset,
329 0,
330 TrapFrame);
331 }
332
333 /* Check for divide by zero */
334 if (Error & FSW_ZERO_DIVIDE)
335 {
336 /* Issue fault */
337 KiDispatchException1Args(STATUS_FLOAT_DIVIDE_BY_ZERO,
338 ErrorOffset,
339 0,
340 TrapFrame);
341 }
342
343 /* Check for denormal */
344 if (Error & FSW_DENORMAL)
345 {
346 /* Issue fault */
347 KiDispatchException1Args(STATUS_FLOAT_INVALID_OPERATION,
348 ErrorOffset,
349 0,
350 TrapFrame);
351 }
352
353 /* Check for overflow */
354 if (Error & FSW_OVERFLOW)
355 {
356 /* Issue fault */
357 KiDispatchException1Args(STATUS_FLOAT_OVERFLOW,
358 ErrorOffset,
359 0,
360 TrapFrame);
361 }
362
363 /* Check for underflow */
364 if (Error & FSW_UNDERFLOW)
365 {
366 /* Issue fault */
367 KiDispatchException1Args(STATUS_FLOAT_UNDERFLOW,
368 ErrorOffset,
369 0,
370 TrapFrame);
371 }
372
373 /* Check for precision fault */
374 if (Error & FSW_PRECISION)
375 {
376 /* Issue fault */
377 KiDispatchException1Args(STATUS_FLOAT_INEXACT_RESULT,
378 ErrorOffset,
379 0,
380 TrapFrame);
381 }
382
383 /* Unknown FPU fault */
384 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 1, Error, 0, 0, TrapFrame);
385 }
386
387 DECLSPEC_NORETURN
388 VOID
389 FASTCALL
390 KiTrap00Handler(IN PKTRAP_FRAME TrapFrame)
391 {
392 /* Save trap frame */
393 KiEnterTrap(TrapFrame);
394
395 /* Check for VDM trap */
396 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
397
398 /* Enable interrupts */
399 _enable();
400
401 /* Dispatch the exception */
402 KiDispatchException0Args(STATUS_INTEGER_DIVIDE_BY_ZERO,
403 TrapFrame->Eip,
404 TrapFrame);
405 }
406
407 DECLSPEC_NORETURN
408 VOID
409 FASTCALL
410 KiTrap01Handler(IN PKTRAP_FRAME TrapFrame)
411 {
412 /* Save trap frame */
413 KiEnterTrap(TrapFrame);
414
415 /* Check for VDM trap */
416 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
417
418 /* Enable interrupts if the trap came from user-mode */
419 if (KiUserTrap(TrapFrame)) _enable();
420
421 /* Mask out trap flag and dispatch the exception */
422 TrapFrame->EFlags &= ~EFLAGS_TF;
423 KiDispatchException0Args(STATUS_SINGLE_STEP,
424 TrapFrame->Eip,
425 TrapFrame);
426 }
427
428 DECLSPEC_NORETURN
429 VOID
430 __cdecl
431 KiTrap02(VOID)
432 {
433 PKTSS Tss, NmiTss;
434 PKTHREAD Thread;
435 PKPROCESS Process;
436 PKGDTENTRY TssGdt;
437 KTRAP_FRAME TrapFrame;
438 KIRQL OldIrql;
439
440 //
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.
444 //
445 // For sanity's sake, make sure interrupts are disabled for sure.
446 // NMIs will already be since the CPU does it for us.
447 //
448 _disable();
449
450 //
451 // Get the current TSS, thread, and process
452 //
453 Tss = PCR->TSS;
454 Thread = ((PKIPCR)PCR)->PrcbData.CurrentThread;
455 Process = Thread->ApcState.Process;
456
457 //
458 // Save data usually not in the TSS
459 //
460 Tss->CR3 = Process->DirectoryTableBase[0];
461 Tss->IoMapBase = Process->IopmOffset;
462 Tss->LDT = Process->LdtDescriptor.LimitLow ? KGDT_LDT : 0;
463
464 //
465 // Now get the base address of the NMI TSS
466 //
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);
471
472 //
473 // Switch to it and activate it, masking off the nested flag
474 //
475 // Note that in reality, we are already on the NMI tss -- we just need to
476 // update the PCR to reflect this
477 //
478 PCR->TSS = NmiTss;
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;
483
484 //
485 // Now build the trap frame based on the original TSS
486 //
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.
489 //
490 // We just have to go get the values...
491 //
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;
513
514 //
515 // Store the trap frame in the KPRCB
516 //
517 KiSaveProcessorState(&TrapFrame, NULL);
518
519 //
520 // Call any registered NMI handlers and see if they handled it or not
521 //
522 if (!KiHandleNmi())
523 {
524 //
525 // They did not, so call the platform HAL routine to bugcheck the system
526 //
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
529 // state
530 //
531 OldIrql = PCR->Irql;
532 PCR->Irql = HIGH_LEVEL;
533 HalHandleNMI(NULL);
534 PCR->Irql = OldIrql;
535 }
536
537 //
538 // Although the CPU disabled NMIs, we just did a BIOS Call, which could've
539 // totally changed things.
540 //
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.
543 //
544 if (PCR->TSS->Backlink != KGDT_NMI_TSS)
545 {
546 //
547 // Restore original TSS
548 //
549 PCR->TSS = Tss;
550
551 //
552 // Set it back to busy
553 //
554 TssGdt->HighWord.Bits.Dpl = 0;
555 TssGdt->HighWord.Bits.Pres = 1;
556 TssGdt->HighWord.Bits.Type = I386_ACTIVE_TSS;
557
558 //
559 // Restore nested flag
560 //
561 __writeeflags(__readeflags() | EFLAGS_NESTED_TASK);
562
563 //
564 // Handled, return from interrupt
565 //
566 KiIret();
567 }
568
569 //
570 // Unhandled: crash the system
571 //
572 KiSystemFatalException(EXCEPTION_NMI, NULL);
573 }
574
575 DECLSPEC_NORETURN
576 VOID
577 FASTCALL
578 KiTrap03Handler(IN PKTRAP_FRAME TrapFrame)
579 {
580 /* Save trap frame */
581 KiEnterTrap(TrapFrame);
582
583 /* Continue with the common handler */
584 KiDebugHandler(TrapFrame, BREAKPOINT_BREAK, 0, 0);
585 }
586
587 DECLSPEC_NORETURN
588 VOID
589 FASTCALL
590 KiTrap04Handler(IN PKTRAP_FRAME TrapFrame)
591 {
592 /* Save trap frame */
593 KiEnterTrap(TrapFrame);
594
595 /* Check for VDM trap */
596 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
597
598 /* Enable interrupts */
599 _enable();
600
601 /* Dispatch the exception */
602 KiDispatchException0Args(STATUS_INTEGER_OVERFLOW,
603 TrapFrame->Eip - 1,
604 TrapFrame);
605 }
606
607 DECLSPEC_NORETURN
608 VOID
609 FASTCALL
610 KiTrap05Handler(IN PKTRAP_FRAME TrapFrame)
611 {
612 /* Save trap frame */
613 KiEnterTrap(TrapFrame);
614
615 /* Check for VDM trap */
616 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
617
618 /* Check for kernel-mode fault */
619 if (!KiUserTrap(TrapFrame)) KiSystemFatalException(EXCEPTION_BOUND_CHECK, TrapFrame);
620
621 /* Enable interrupts */
622 _enable();
623
624 /* Dispatch the exception */
625 KiDispatchException0Args(STATUS_ARRAY_BOUNDS_EXCEEDED,
626 TrapFrame->Eip,
627 TrapFrame);
628 }
629
630 DECLSPEC_NORETURN
631 VOID
632 FASTCALL
633 KiTrap06Handler(IN PKTRAP_FRAME TrapFrame)
634 {
635 PUCHAR Instruction;
636 ULONG i;
637 KIRQL OldIrql;
638
639 /* Check for V86 GPF */
640 if (__builtin_expect(KiV86Trap(TrapFrame), 1))
641 {
642 /* Enter V86 trap */
643 KiEnterV86Trap(TrapFrame);
644
645 /* Must be a VDM process */
646 if (__builtin_expect(!PsGetCurrentProcess()->VdmObjects, 0))
647 {
648 /* Enable interrupts */
649 _enable();
650
651 /* Setup illegal instruction fault */
652 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
653 TrapFrame->Eip,
654 TrapFrame);
655 }
656
657 /* Go to APC level */
658 OldIrql = KfRaiseIrql(APC_LEVEL);
659 _enable();
660
661 /* Check for BOP */
662 if (!VdmDispatchBop(TrapFrame))
663 {
664 /* Should only happen in VDM mode */
665 UNIMPLEMENTED;
666 while (TRUE);
667 }
668
669 /* Bring IRQL back */
670 KfLowerIrql(OldIrql);
671 _disable();
672
673 /* Do a quick V86 exit if possible */
674 KiExitV86Trap(TrapFrame);
675 }
676
677 /* Save trap frame */
678 KiEnterTrap(TrapFrame);
679
680 /* Enable interrupts */
681 Instruction = (PUCHAR)TrapFrame->Eip;
682 _enable();
683
684 /* Check for user trap */
685 if (KiUserTrap(TrapFrame))
686 {
687 /* FIXME: Use SEH */
688
689 /* Scan next 4 opcodes */
690 for (i = 0; i < 4; i++)
691 {
692 /* Check for LOCK instruction */
693 if (Instruction[i] == 0xF0)
694 {
695 /* Send invalid lock sequence exception */
696 KiDispatchException0Args(STATUS_INVALID_LOCK_SEQUENCE,
697 TrapFrame->Eip,
698 TrapFrame);
699 }
700 }
701
702 /* FIXME: SEH ends here */
703 }
704
705 /* Kernel-mode or user-mode fault (but not LOCK) */
706 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
707 TrapFrame->Eip,
708 TrapFrame);
709
710 }
711
712 DECLSPEC_NORETURN
713 VOID
714 FASTCALL
715 KiTrap07Handler(IN PKTRAP_FRAME TrapFrame)
716 {
717 PKTHREAD Thread, NpxThread;
718 PFX_SAVE_AREA SaveArea, NpxSaveArea;
719 ULONG Cr0;
720
721 /* Save trap frame */
722 KiEnterTrap(TrapFrame);
723
724 /* Try to handle NPX delay load */
725 while (TRUE)
726 {
727 /* Get the current thread */
728 Thread = KeGetCurrentThread();
729
730 /* Get the NPX frame */
731 SaveArea = KiGetThreadNpxArea(Thread);
732
733 /* Check if emulation is enabled */
734 if (SaveArea->Cr0NpxState & CR0_EM)
735 {
736 /* Not implemented */
737 UNIMPLEMENTED;
738 while (TRUE);
739 }
740
741 /* Save CR0 and check NPX state */
742 Cr0 = __readcr0();
743 if (Thread->NpxState != NPX_STATE_LOADED)
744 {
745 /* Update CR0 */
746 Cr0 &= ~(CR0_MP | CR0_EM | CR0_TS);
747 __writecr0(Cr0);
748
749 /* Get the NPX thread */
750 NpxThread = KeGetCurrentPrcb()->NpxThread;
751 if (NpxThread)
752 {
753 /* Get the NPX frame */
754 NpxSaveArea = KiGetThreadNpxArea(NpxThread);
755
756 /* Save FPU state */
757 DPRINT("FIXME: Save FPU state: %p\n", NpxSaveArea);
758 //Ke386SaveFpuState(NpxSaveArea);
759
760 /* Update NPX state */
761 Thread->NpxState = NPX_STATE_NOT_LOADED;
762 }
763
764 /* Load FPU state */
765 //Ke386LoadFpuState(SaveArea);
766
767 /* Update NPX state */
768 Thread->NpxState = NPX_STATE_LOADED;
769 KeGetCurrentPrcb()->NpxThread = Thread;
770
771 /* Enable interrupts */
772 _enable();
773
774 /* Check if CR0 needs to be reloaded due to context switch */
775 if (!SaveArea->Cr0NpxState) KiEoiHelper(TrapFrame);
776
777 /* Otherwise, we need to reload CR0, disable interrupts */
778 _disable();
779
780 /* Reload CR0 */
781 Cr0 = __readcr0();
782 Cr0 |= SaveArea->Cr0NpxState;
783 __writecr0(Cr0);
784
785 /* Now restore interrupts and check for TS */
786 _enable();
787 if (Cr0 & CR0_TS) KiEoiHelper(TrapFrame);
788
789 /* We're still here -- clear TS and try again */
790 __writecr0(__readcr0() &~ CR0_TS);
791 _disable();
792 }
793 else
794 {
795 /* This is an actual fault, not a lack of FPU state */
796 break;
797 }
798 }
799
800 /* TS should not be set */
801 if (Cr0 & CR0_TS)
802 {
803 /*
804 * If it's incorrectly set, then maybe the state is actually still valid
805 * but we could've lock track of that due to a BIOS call.
806 * Make sure MP is still set, which should verify the theory.
807 */
808 if (Cr0 & CR0_MP)
809 {
810 /* Indeed, the state is actually still valid, so clear TS */
811 __writecr0(__readcr0() &~ CR0_TS);
812 KiEoiHelper(TrapFrame);
813 }
814
815 /* Otherwise, something strange is going on */
816 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 2, Cr0, 0, 0, TrapFrame);
817 }
818
819 /* It's not a delayed load, so process this trap as an NPX fault */
820 KiNpxHandler(TrapFrame, Thread, SaveArea);
821 }
822
823 DECLSPEC_NORETURN
824 VOID
825 FASTCALL
826 KiTrap08Handler(IN PKTRAP_FRAME TrapFrame)
827 {
828 /* FIXME: Not handled */
829 KiSystemFatalException(EXCEPTION_DOUBLE_FAULT, TrapFrame);
830 }
831
832 DECLSPEC_NORETURN
833 VOID
834 FASTCALL
835 KiTrap09Handler(IN PKTRAP_FRAME TrapFrame)
836 {
837 /* Save trap frame */
838 KiEnterTrap(TrapFrame);
839
840 /* Enable interrupts and kill the system */
841 _enable();
842 KiSystemFatalException(EXCEPTION_NPX_OVERRUN, TrapFrame);
843 }
844
845 DECLSPEC_NORETURN
846 VOID
847 FASTCALL
848 KiTrap0AHandler(IN PKTRAP_FRAME TrapFrame)
849 {
850 /* Save trap frame */
851 KiEnterTrap(TrapFrame);
852
853 /* Check for VDM trap */
854 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
855
856 /* Kill the system */
857 KiSystemFatalException(EXCEPTION_INVALID_TSS, TrapFrame);
858 }
859
860 DECLSPEC_NORETURN
861 VOID
862 FASTCALL
863 KiTrap0BHandler(IN PKTRAP_FRAME TrapFrame)
864 {
865 /* Save trap frame */
866 KiEnterTrap(TrapFrame);
867
868 /* FIXME: Kill the system */
869 UNIMPLEMENTED;
870 KiSystemFatalException(EXCEPTION_SEGMENT_NOT_PRESENT, TrapFrame);
871 }
872
873 DECLSPEC_NORETURN
874 VOID
875 FASTCALL
876 KiTrap0CHandler(IN PKTRAP_FRAME TrapFrame)
877 {
878 /* Save trap frame */
879 KiEnterTrap(TrapFrame);
880
881 /* FIXME: Kill the system */
882 UNIMPLEMENTED;
883 KiSystemFatalException(EXCEPTION_STACK_FAULT, TrapFrame);
884 }
885
886 DECLSPEC_NORETURN
887 VOID
888 FASTCALL
889 KiTrap0DHandler(IN PKTRAP_FRAME TrapFrame)
890 {
891 ULONG i, j, Iopl;
892 BOOLEAN Privileged = FALSE;
893 PUCHAR Instructions;
894 UCHAR Instruction = 0;
895 KIRQL OldIrql;
896
897 /* Check for V86 GPF */
898 if (__builtin_expect(KiV86Trap(TrapFrame), 1))
899 {
900 /* Enter V86 trap */
901 KiEnterV86Trap(TrapFrame);
902
903 /* Must be a VDM process */
904 if (__builtin_expect(!PsGetCurrentProcess()->VdmObjects, 0))
905 {
906 /* Enable interrupts */
907 _enable();
908
909 /* Setup illegal instruction fault */
910 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
911 TrapFrame->Eip,
912 TrapFrame);
913 }
914
915 /* Go to APC level */
916 OldIrql = KfRaiseIrql(APC_LEVEL);
917 _enable();
918
919 /* Handle the V86 opcode */
920 if (__builtin_expect(Ki386HandleOpcodeV86(TrapFrame) == 0xFF, 0))
921 {
922 /* Should only happen in VDM mode */
923 UNIMPLEMENTED;
924 while (TRUE);
925 }
926
927 /* Bring IRQL back */
928 KfLowerIrql(OldIrql);
929 _disable();
930
931 /* Do a quick V86 exit if possible */
932 KiExitV86Trap(TrapFrame);
933 }
934
935 /* Save trap frame */
936 KiEnterTrap(TrapFrame);
937
938 /* Check for user-mode GPF */
939 if (KiUserTrap(TrapFrame))
940 {
941 /* Should not be VDM */
942 ASSERT(KiVdmTrap(TrapFrame) == FALSE);
943
944 /* Enable interrupts and check error code */
945 _enable();
946 if (!TrapFrame->ErrCode)
947 {
948 /* FIXME: Use SEH */
949 Instructions = (PUCHAR)TrapFrame->Eip;
950
951 /* Scan next 15 bytes */
952 for (i = 0; i < 15; i++)
953 {
954 /* Skip prefix instructions */
955 for (j = 0; j < sizeof(KiTrapPrefixTable); j++)
956 {
957 /* Is this a prefix instruction? */
958 if (Instructions[i] == KiTrapPrefixTable[j])
959 {
960 /* Stop looking */
961 break;
962 }
963 }
964
965 /* Is this NOT any prefix instruction? */
966 if (j == sizeof(KiTrapPrefixTable))
967 {
968 /* We can go ahead and handle the fault now */
969 Instruction = Instructions[i];
970 break;
971 }
972 }
973
974 /* If all we found was prefixes, then this instruction is too long */
975 if (i == 15)
976 {
977 /* Setup illegal instruction fault */
978 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
979 TrapFrame->Eip,
980 TrapFrame);
981 }
982
983 /* Check for privileged instructions */
984 DPRINT("Instruction (%d) at fault: %lx %lx %lx %lx\n",
985 i,
986 Instructions[i],
987 Instructions[i + 1],
988 Instructions[i + 2],
989 Instructions[i + 3]);
990 if (Instruction == 0xF4) // HLT
991 {
992 /* HLT is privileged */
993 Privileged = TRUE;
994 }
995 else if (Instruction == 0x0F)
996 {
997 /* Test if it's any of the privileged two-byte opcodes */
998 if (((Instructions[i + 1] == 0x00) && // LLDT or LTR
999 (((Instructions[i + 2] & 0x38) == 0x10) || // LLDT
1000 (Instructions[i + 2] == 0x18))) || // LTR
1001 ((Instructions[i + 1] == 0x01) && // LGDT or LIDT or LMSW
1002 (((Instructions[i + 2] & 0x38) == 0x10) || // LGDT
1003 (Instructions[i + 2] == 0x18) || // LIDT
1004 (Instructions[i + 2] == 0x30))) || // LMSW
1005 (Instructions[i + 1] == 0x08) || // INVD
1006 (Instructions[i + 1] == 0x09) || // WBINVD
1007 (Instructions[i + 1] == 0x35) || // SYSEXIT
1008 (Instructions[i + 1] == 0x21) || // MOV DR, XXX
1009 (Instructions[i + 1] == 0x06) || // CLTS
1010 (Instructions[i + 1] == 0x20) || // MOV CR, XXX
1011 (Instructions[i + 1] == 0x22) || // MOV XXX, CR
1012 (Instructions[i + 1] == 0x23) || // MOV YYY, DR
1013 (Instructions[i + 1] == 0x30) || // WRMSR
1014 (Instructions[i + 1] == 0x33)) // RDPMC
1015 // INVLPG, INVLPGA, SYSRET
1016 {
1017 /* These are all privileged */
1018 Privileged = TRUE;
1019 }
1020 }
1021 else
1022 {
1023 /* Get the IOPL and compare with the RPL mask */
1024 Iopl = (TrapFrame->EFlags & EFLAGS_IOPL) >> 12;
1025 if ((TrapFrame->SegCs & RPL_MASK) > Iopl)
1026 {
1027 /* I/O privilege error -- check for known instructions */
1028 if ((Instruction == 0xFA) || (Instruction == 0xFB)) // CLI or STI
1029 {
1030 /* These are privileged */
1031 Privileged = TRUE;
1032 }
1033 else
1034 {
1035 /* Last hope: an IN/OUT instruction */
1036 for (j = 0; j < sizeof(KiTrapIoTable); j++)
1037 {
1038 /* Is this an I/O instruction? */
1039 if (Instruction == KiTrapIoTable[j])
1040 {
1041 /* Then it's privileged */
1042 Privileged = TRUE;
1043 break;
1044 }
1045 }
1046 }
1047 }
1048 }
1049
1050 /* So now... was the instruction privileged or not? */
1051 if (Privileged)
1052 {
1053 /* Whew! We have a privileged instruction, so dispatch the fault */
1054 KiDispatchException0Args(STATUS_PRIVILEGED_INSTRUCTION,
1055 TrapFrame->Eip,
1056 TrapFrame);
1057 }
1058 }
1059
1060 /* If we got here, send an access violation */
1061 KiDispatchException2Args(STATUS_ACCESS_VIOLATION,
1062 TrapFrame->Eip,
1063 0,
1064 0xFFFFFFFF,
1065 TrapFrame);
1066 }
1067
1068 /*
1069 * Check for a fault during checking of the user instruction.
1070 *
1071 * Note that the SEH handler will catch invalid EIP, but we could be dealing
1072 * with an invalid CS, which will generate another GPF instead.
1073 *
1074 */
1075 if (((PVOID)TrapFrame->Eip >= (PVOID)KiTrap0DHandler) &&
1076 ((PVOID)TrapFrame->Eip < (PVOID)KiTrap0DHandler))
1077 {
1078 /* Not implemented */
1079 UNIMPLEMENTED;
1080 while (TRUE);
1081 }
1082
1083 /*
1084 * NOTE: The ASM trap exit code would restore segment registers by doing
1085 * a POP <SEG>, which could cause an invalid segment if someone had messed
1086 * with the segment values.
1087 *
1088 * Another case is a bogus SS, which would hit a GPF when doing the iret.
1089 * This could only be done through a buggy or malicious driver, or perhaps
1090 * the kernel debugger.
1091 *
1092 * The kernel normally restores the "true" segment if this happens.
1093 *
1094 * However, since we're restoring in C, not ASM, we can't detect
1095 * POP <SEG> since the actual instructions will be different.
1096 *
1097 * A better technique would be to check the EIP and somehow edit the
1098 * trap frame before restarting the instruction -- but we would need to
1099 * know the extract instruction that was used first.
1100 *
1101 * We could force a special instrinsic to use stack instructions, or write
1102 * a simple instruction length checker.
1103 *
1104 * Nevertheless, this is a lot of work for the purpose of avoiding a crash
1105 * when the user is purposedly trying to create one from kernel-mode, so
1106 * we should probably table this for now since it's not a "real" issue.
1107 */
1108
1109 /*
1110 * NOTE2: Another scenario is the IRET during a V8086 restore (BIOS Call)
1111 * which will cause a GPF since the trap frame is a total mess (on purpose)
1112 * as built in KiEnterV86Mode.
1113 *
1114 * The idea is to scan for IRET, scan for the known EIP adress, validate CS
1115 * and then manually issue a jump to the V8086 return EIP.
1116 */
1117 Instructions = (PUCHAR)TrapFrame->Eip;
1118 if (Instructions[0] == 0xCF)
1119 {
1120 /*
1121 * Some evil shit is going on here -- this is not the SS:ESP you're
1122 * looking for! Instead, this is actually CS:EIP you're looking at!
1123 * Why? Because part of the trap frame actually corresponds to the IRET
1124 * stack during the trap exit!
1125 */
1126 if ((TrapFrame->HardwareEsp == (ULONG)Ki386BiosCallReturnAddress) &&
1127 (TrapFrame->HardwareSegSs == (KGDT_R0_CODE | RPL_MASK)))
1128 {
1129 /* Exit the V86 trap! */
1130 Ki386BiosCallReturnAddress(TrapFrame);
1131 }
1132 else
1133 {
1134 /* Otherwise, this is another kind of IRET fault */
1135 UNIMPLEMENTED;
1136 while (TRUE);
1137 }
1138 }
1139
1140 /* So since we're not dealing with the above case, check for RDMSR/WRMSR */
1141 if ((Instructions[0] == 0xF) && // 2-byte opcode
1142 ((Instructions[1] == 0x32) || // RDMSR
1143 (Instructions[1] == 0x30))) // WRMSR
1144 {
1145 /* Unknown CPU MSR, so raise an access violation */
1146 KiDispatchException0Args(STATUS_ACCESS_VIOLATION,
1147 TrapFrame->Eip,
1148 TrapFrame);
1149 }
1150
1151 /* Check for lazy segment load */
1152 if (TrapFrame->SegDs != (KGDT_R3_DATA | RPL_MASK))
1153 {
1154 /* Fix it */
1155 TrapFrame->SegDs = (KGDT_R3_DATA | RPL_MASK);
1156 }
1157 else if (TrapFrame->SegEs != (KGDT_R3_DATA | RPL_MASK))
1158 {
1159 /* Fix it */
1160 TrapFrame->SegEs = (KGDT_R3_DATA | RPL_MASK);
1161 }
1162 else
1163 {
1164 /* Whatever it is, we can't handle it */
1165 KiSystemFatalException(EXCEPTION_GP_FAULT, TrapFrame);
1166 }
1167
1168 /* Return to where we came from */
1169 KiTrapReturn(TrapFrame);
1170 }
1171
1172 DECLSPEC_NORETURN
1173 VOID
1174 FASTCALL
1175 KiTrap0EHandler(IN PKTRAP_FRAME TrapFrame)
1176 {
1177 PKTHREAD Thread;
1178 ULONG_PTR Cr2;
1179 NTSTATUS Status;
1180
1181 /* Save trap frame */
1182 KiEnterTrap(TrapFrame);
1183
1184 /* Check if this is the base frame */
1185 Thread = KeGetCurrentThread();
1186 if (KeGetTrapFrame(Thread) != TrapFrame)
1187 {
1188 /* It isn't, check if this is a second nested frame */
1189 if (((ULONG_PTR)KeGetTrapFrame(Thread) - (ULONG_PTR)TrapFrame) <=
1190 FIELD_OFFSET(KTRAP_FRAME, EFlags))
1191 {
1192 /* The stack is somewhere in between frames, we need to fix it */
1193 UNIMPLEMENTED;
1194 while (TRUE);
1195 }
1196 }
1197
1198 /* Save CR2 */
1199 Cr2 = __readcr2();
1200
1201 /* Enable interupts */
1202 _enable();
1203
1204 /* Check if we came in with interrupts disabled */
1205 if (!(TrapFrame->EFlags & EFLAGS_INTERRUPT_MASK))
1206 {
1207 /* This is completely illegal, bugcheck the system */
1208 KeBugCheckWithTf(IRQL_NOT_LESS_OR_EQUAL,
1209 Cr2,
1210 -1,
1211 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1212 TrapFrame->Eip,
1213 TrapFrame);
1214 }
1215
1216 /* Check for S-LIST fault in kernel mode */
1217 if (TrapFrame->Eip == (ULONG_PTR)ExpInterlockedPopEntrySListFault)
1218 {
1219 PSLIST_HEADER SListHeader;
1220
1221 /* Sanity check that the assembly is correct:
1222 This must be mov ebx, [eax]
1223 Followed by cmpxchg8b [ebp] */
1224 ASSERT((((UCHAR*)TrapFrame->Eip)[0] == 0x8B) &&
1225 (((UCHAR*)TrapFrame->Eip)[1] == 0x18) &&
1226 (((UCHAR*)TrapFrame->Eip)[2] == 0x0F) &&
1227 (((UCHAR*)TrapFrame->Eip)[3] == 0xC7) &&
1228 (((UCHAR*)TrapFrame->Eip)[4] == 0x4D) &&
1229 (((UCHAR*)TrapFrame->Eip)[5] == 0x00));
1230
1231 /* Get the pointer to the SLIST_HEADER */
1232 SListHeader = (PSLIST_HEADER)TrapFrame->Ebp;
1233
1234 /* Check if the Next member of the SLIST_HEADER was changed */
1235 if (SListHeader->Next.Next != (PSLIST_ENTRY)TrapFrame->Eax)
1236 {
1237 /* Restart the operation */
1238 TrapFrame->Eip = (ULONG_PTR)ExpInterlockedPopEntrySListResume;
1239
1240 /* Continue execution */
1241 KiEoiHelper(TrapFrame);
1242 }
1243 }
1244
1245 /* Call the access fault handler */
1246 Status = MmAccessFault(TrapFrame->ErrCode & 1,
1247 (PVOID)Cr2,
1248 TrapFrame->SegCs & MODE_MASK,
1249 TrapFrame);
1250 if (NT_SUCCESS(Status)) KiEoiHelper(TrapFrame);
1251
1252 /* Check for syscall fault */
1253 #if 0
1254 if ((TrapFrame->Eip == (ULONG_PTR)CopyParams) ||
1255 (TrapFrame->Eip == (ULONG_PTR)ReadBatch))
1256 {
1257 /* Not yet implemented */
1258 UNIMPLEMENTED;
1259 while (TRUE);
1260 }
1261 #endif
1262 /* Check for VDM trap */
1263 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
1264
1265 /* Either kernel or user trap (non VDM) so dispatch exception */
1266 if (Status == STATUS_ACCESS_VIOLATION)
1267 {
1268 /* This status code is repurposed so we can recognize it later */
1269 KiDispatchException2Args(KI_EXCEPTION_ACCESS_VIOLATION,
1270 TrapFrame->Eip,
1271 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1272 Cr2,
1273 TrapFrame);
1274 }
1275 else if ((Status == STATUS_GUARD_PAGE_VIOLATION) ||
1276 (Status == STATUS_STACK_OVERFLOW))
1277 {
1278 /* These faults only have two parameters */
1279 KiDispatchException2Args(Status,
1280 TrapFrame->Eip,
1281 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1282 Cr2,
1283 TrapFrame);
1284 }
1285
1286 /* Only other choice is an in-page error, with 3 parameters */
1287 KiDispatchExceptionFromTrapFrame(STATUS_IN_PAGE_ERROR,
1288 TrapFrame->Eip,
1289 3,
1290 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1291 Cr2,
1292 Status,
1293 TrapFrame);
1294 }
1295
1296 DECLSPEC_NORETURN
1297 VOID
1298 FASTCALL
1299 KiTrap0FHandler(IN PKTRAP_FRAME TrapFrame)
1300 {
1301 /* Save trap frame */
1302 KiEnterTrap(TrapFrame);
1303
1304 /* FIXME: Kill the system */
1305 UNIMPLEMENTED;
1306 KiSystemFatalException(EXCEPTION_RESERVED_TRAP, TrapFrame);
1307 }
1308
1309 DECLSPEC_NORETURN
1310 VOID
1311 FASTCALL
1312 KiTrap10Handler(IN PKTRAP_FRAME TrapFrame)
1313 {
1314 PKTHREAD Thread;
1315 PFX_SAVE_AREA SaveArea;
1316
1317 /* Save trap frame */
1318 KiEnterTrap(TrapFrame);
1319
1320 /* Check if this is the NPX thrad */
1321 Thread = KeGetCurrentThread();
1322 SaveArea = KiGetThreadNpxArea(Thread);
1323 if (Thread != KeGetCurrentPrcb()->NpxThread)
1324 {
1325 /* It isn't, enable interrupts and set delayed error */
1326 _enable();
1327 SaveArea->Cr0NpxState |= CR0_TS;
1328
1329 /* End trap */
1330 KiEoiHelper(TrapFrame);
1331 }
1332
1333 /* Otherwise, proceed with NPX fault handling */
1334 KiNpxHandler(TrapFrame, Thread, SaveArea);
1335 }
1336
1337 DECLSPEC_NORETURN
1338 VOID
1339 FASTCALL
1340 KiTrap11Handler(IN PKTRAP_FRAME TrapFrame)
1341 {
1342 /* Save trap frame */
1343 KiEnterTrap(TrapFrame);
1344
1345 /* Enable interrupts and kill the system */
1346 _enable();
1347 KiSystemFatalException(EXCEPTION_ALIGNMENT_CHECK, TrapFrame);
1348 }
1349
1350 DECLSPEC_NORETURN
1351 VOID
1352 FASTCALL
1353 KiTrap13Handler(IN PKTRAP_FRAME TrapFrame)
1354 {
1355 PKTHREAD Thread;
1356 PFX_SAVE_AREA SaveArea;
1357 ULONG Cr0, MxCsrMask, Error;
1358
1359 /* Save trap frame */
1360 KiEnterTrap(TrapFrame);
1361
1362 /* Check if this is the NPX thrad */
1363 Thread = KeGetCurrentThread();
1364 if (Thread != KeGetCurrentPrcb()->NpxThread)
1365 {
1366 /* It isn't, kill the system */
1367 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, (ULONG_PTR)Thread, 0, 0, TrapFrame);
1368 }
1369
1370 /* Get the NPX frame */
1371 SaveArea = KiGetThreadNpxArea(Thread);
1372
1373 /* Check for VDM trap */
1374 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
1375
1376 /* Check for user trap */
1377 if (!KiUserTrap(TrapFrame))
1378 {
1379 /* Kernel should not fault on XMMI */
1380 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, 0, 0, 2, TrapFrame);
1381 }
1382
1383 /* Update CR0 */
1384 Cr0 = __readcr0();
1385 Cr0 &= ~(CR0_MP | CR0_EM | CR0_TS);
1386 __writecr0(Cr0);
1387
1388 /* Save FPU state */
1389 Ke386SaveFpuState(SaveArea);
1390
1391 /* Mark CR0 state dirty */
1392 Cr0 |= NPX_STATE_NOT_LOADED;
1393 Cr0 |= SaveArea->Cr0NpxState;
1394 __writecr0(Cr0);
1395
1396 /* Update NPX state */
1397 Thread->NpxState = NPX_STATE_NOT_LOADED;
1398 KeGetCurrentPrcb()->NpxThread = NULL;
1399
1400 /* Clear the TS bit and re-enable interrupts */
1401 SaveArea->Cr0NpxState &= ~CR0_TS;
1402 _enable();
1403
1404 /* Now look at MxCsr to get the mask of errors we should care about */
1405 MxCsrMask = ~((USHORT)SaveArea->U.FxArea.MXCsr >> 7);
1406
1407 /* Get legal exceptions that software should handle */
1408 Error = (USHORT)SaveArea->U.FxArea.MXCsr & (FSW_INVALID_OPERATION |
1409 FSW_DENORMAL |
1410 FSW_ZERO_DIVIDE |
1411 FSW_OVERFLOW |
1412 FSW_UNDERFLOW |
1413 FSW_PRECISION);
1414 Error &= MxCsrMask;
1415
1416 /* Now handle any of those legal errors */
1417 if (Error & (FSW_INVALID_OPERATION |
1418 FSW_DENORMAL |
1419 FSW_ZERO_DIVIDE |
1420 FSW_OVERFLOW |
1421 FSW_UNDERFLOW |
1422 FSW_PRECISION))
1423 {
1424 /* By issuing an exception */
1425 KiDispatchException1Args(STATUS_FLOAT_MULTIPLE_TRAPS,
1426 TrapFrame->Eip,
1427 0,
1428 TrapFrame);
1429 }
1430
1431 /* Unknown XMMI fault */
1432 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, 0, 0, 1, TrapFrame);
1433 }
1434
1435 /* SOFTWARE SERVICES **********************************************************/
1436
1437 VOID
1438 FASTCALL
1439 KiGetTickCountHandler(IN PKTRAP_FRAME TrapFrame)
1440 {
1441 UNIMPLEMENTED;
1442 while (TRUE);
1443 }
1444
1445 VOID
1446 FASTCALL
1447 KiCallbackReturnHandler(IN PKTRAP_FRAME TrapFrame)
1448 {
1449 UNIMPLEMENTED;
1450 while (TRUE);
1451 }
1452
1453 DECLSPEC_NORETURN
1454 VOID
1455 FASTCALL
1456 KiRaiseAssertionHandler(IN PKTRAP_FRAME TrapFrame)
1457 {
1458 /* Save trap frame */
1459 KiEnterTrap(TrapFrame);
1460
1461 /* Decrement EIP to point to the INT2C instruction (2 bytes, not 1 like INT3) */
1462 TrapFrame->Eip -= 2;
1463
1464 /* Dispatch the exception */
1465 KiDispatchException0Args(STATUS_ASSERTION_FAILURE,
1466 TrapFrame->Eip,
1467 TrapFrame);
1468 }
1469
1470 DECLSPEC_NORETURN
1471 VOID
1472 FASTCALL
1473 KiDebugServiceHandler(IN PKTRAP_FRAME TrapFrame)
1474 {
1475 /* Save trap frame */
1476 KiEnterTrap(TrapFrame);
1477
1478 /* Increment EIP to skip the INT3 instruction */
1479 TrapFrame->Eip++;
1480
1481 /* Continue with the common handler */
1482 KiDebugHandler(TrapFrame, TrapFrame->Eax, TrapFrame->Ecx, TrapFrame->Edx);
1483 }
1484
1485
1486 FORCEINLINE
1487 VOID
1488 KiDbgPreServiceHook(ULONG SystemCallNumber, PULONG_PTR Arguments)
1489 {
1490 #if DBG && !defined(_WINKD_)
1491 if (SystemCallNumber >= 0x1000 && KeWin32PreServiceHook)
1492 KeWin32PreServiceHook(SystemCallNumber, Arguments);
1493 #endif
1494 }
1495
1496 FORCEINLINE
1497 ULONG_PTR
1498 KiDbgPostServiceHook(ULONG SystemCallNumber, ULONG_PTR Result)
1499 {
1500 #if DBG && !defined(_WINKD_)
1501 if (SystemCallNumber >= 0x1000 && KeWin32PostServiceHook)
1502 return KeWin32PostServiceHook(SystemCallNumber, Result);
1503 #endif
1504 return Result;
1505 }
1506
1507 DECLSPEC_NORETURN
1508 VOID
1509 FORCEINLINE
1510 KiSystemCall(IN PKTRAP_FRAME TrapFrame,
1511 IN PVOID Arguments)
1512 {
1513 PKTHREAD Thread;
1514 PKSERVICE_TABLE_DESCRIPTOR DescriptorTable;
1515 ULONG Id, Offset, StackBytes, Result;
1516 PVOID Handler;
1517 ULONG SystemCallNumber = TrapFrame->Eax;
1518
1519 /* Get the current thread */
1520 Thread = KeGetCurrentThread();
1521
1522 /* Set debug header */
1523 KiFillTrapFrameDebug(TrapFrame);
1524
1525 /* Chain trap frames */
1526 TrapFrame->Edx = (ULONG_PTR)Thread->TrapFrame;
1527
1528 /* No error code */
1529 TrapFrame->ErrCode = 0;
1530
1531 /* Save previous mode */
1532 TrapFrame->PreviousPreviousMode = Thread->PreviousMode;
1533
1534 /* Save the SEH chain and terminate it for now */
1535 TrapFrame->ExceptionList = KeGetPcr()->NtTib.ExceptionList;
1536 KeGetPcr()->NtTib.ExceptionList = EXCEPTION_CHAIN_END;
1537
1538 /* Default to debugging disabled */
1539 TrapFrame->Dr7 = 0;
1540
1541 /* Check if the frame was from user mode */
1542 if (TrapFrame->SegCs & MODE_MASK)
1543 {
1544 /* Check for active debugging */
1545 if (KeGetCurrentThread()->Header.DebugActive & 0xFF)
1546 {
1547 /* Handle debug registers */
1548 KiHandleDebugRegistersOnTrapEntry(TrapFrame);
1549 }
1550 }
1551
1552 /* Set thread fields */
1553 Thread->TrapFrame = TrapFrame;
1554 Thread->PreviousMode = KiUserTrap(TrapFrame);
1555
1556 /* Enable interrupts */
1557 _enable();
1558
1559 /* Decode the system call number */
1560 Offset = (SystemCallNumber >> SERVICE_TABLE_SHIFT) & SERVICE_TABLE_MASK;
1561 Id = SystemCallNumber & SERVICE_NUMBER_MASK;
1562
1563 /* Get descriptor table */
1564 DescriptorTable = (PVOID)((ULONG_PTR)Thread->ServiceTable + Offset);
1565
1566 /* Validate the system call number */
1567 if (__builtin_expect(Id >= DescriptorTable->Limit, 0))
1568 {
1569 /* Check if this is a GUI call */
1570 if (!(Offset & SERVICE_TABLE_TEST))
1571 {
1572 /* Fail the call */
1573 Result = STATUS_INVALID_SYSTEM_SERVICE;
1574 goto ExitCall;
1575 }
1576
1577 /* Convert us to a GUI thread -- must wrap in ASM to get new EBP */
1578 Result = KiConvertToGuiThread();
1579
1580 /* Reload trap frame and descriptor table pointer from new stack */
1581 TrapFrame = *(volatile PVOID*)&Thread->TrapFrame;
1582 DescriptorTable = (PVOID)(*(volatile ULONG_PTR*)&Thread->ServiceTable + Offset);
1583
1584 if (!NT_SUCCESS(Result))
1585 {
1586 /* Set the last error and fail */
1587 //SetLastWin32Error(RtlNtStatusToDosError(Result));
1588 goto ExitCall;
1589 }
1590
1591 /* Validate the system call number again */
1592 if (Id >= DescriptorTable->Limit)
1593 {
1594 /* Fail the call */
1595 Result = STATUS_INVALID_SYSTEM_SERVICE;
1596 goto ExitCall;
1597 }
1598 }
1599
1600 /* Check if this is a GUI call */
1601 if (__builtin_expect(Offset & SERVICE_TABLE_TEST, 0))
1602 {
1603 /* Get the batch count and flush if necessary */
1604 if (NtCurrentTeb()->GdiBatchCount) KeGdiFlushUserBatch();
1605 }
1606
1607 /* Increase system call count */
1608 KeGetCurrentPrcb()->KeSystemCalls++;
1609
1610 /* FIXME: Increase individual counts on debug systems */
1611 //KiIncreaseSystemCallCount(DescriptorTable, Id);
1612
1613 /* Get stack bytes */
1614 StackBytes = DescriptorTable->Number[Id];
1615
1616 /* Probe caller stack */
1617 if (__builtin_expect((Arguments < (PVOID)MmUserProbeAddress) && !(KiUserTrap(TrapFrame)), 0))
1618 {
1619 /* Access violation */
1620 UNIMPLEMENTED;
1621 while (TRUE);
1622 }
1623
1624 /* Call pre-service debug hook */
1625 KiDbgPreServiceHook(SystemCallNumber, Arguments);
1626
1627 /* Get the handler and make the system call */
1628 Handler = (PVOID)DescriptorTable->Base[Id];
1629 Result = KiSystemCallTrampoline(Handler, Arguments, StackBytes);
1630
1631 /* Call post-service debug hook */
1632 Result = KiDbgPostServiceHook(SystemCallNumber, Result);
1633
1634 /* Make sure we're exiting correctly */
1635 KiExitSystemCallDebugChecks(Id, TrapFrame);
1636
1637 /* Restore the old trap frame */
1638 ExitCall:
1639 Thread->TrapFrame = (PKTRAP_FRAME)TrapFrame->Edx;
1640
1641 /* Exit from system call */
1642 KiServiceExit(TrapFrame, Result);
1643 }
1644
1645 DECLSPEC_NORETURN
1646 VOID
1647 FASTCALL
1648 KiSystemServiceHandler(IN PKTRAP_FRAME TrapFrame,
1649 IN PVOID Arguments)
1650 {
1651 /* Call the shared handler (inline) */
1652 KiSystemCall(TrapFrame, Arguments);
1653 }
1654
1655 DECLSPEC_NORETURN
1656 VOID
1657 FASTCALL
1658 KiFastCallEntryHandler(IN PKTRAP_FRAME TrapFrame,
1659 IN PVOID Arguments)
1660 {
1661 /* Set up a fake INT Stack and enable interrupts */
1662 TrapFrame->HardwareSegSs = KGDT_R3_DATA | RPL_MASK;
1663 TrapFrame->HardwareEsp = (ULONG_PTR)Arguments;
1664 TrapFrame->EFlags = __readeflags() | EFLAGS_INTERRUPT_MASK;
1665 TrapFrame->SegCs = KGDT_R3_CODE | RPL_MASK;
1666 TrapFrame->Eip = SharedUserData->SystemCallReturn;
1667 TrapFrame->SegFs = KGDT_R3_TEB | RPL_MASK;
1668 __writeeflags(0x2);
1669
1670 /* Arguments are actually 2 frames down (because of the double indirection) */
1671 Arguments = (PVOID)(TrapFrame->HardwareEsp + 8);
1672
1673 /* Call the shared handler (inline) */
1674 KiSystemCall(TrapFrame, Arguments);
1675 }
1676
1677 /*
1678 * @implemented
1679 */
1680 VOID
1681 NTAPI
1682 Kei386EoiHelper(VOID)
1683 {
1684 /* We should never see this call happening */
1685 DPRINT1("Mismatched NT/HAL version");
1686 while (TRUE);
1687 }
1688
1689 /* EOF */