Sync with trunk.
[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_FATAL();
666 }
667
668 /* Bring IRQL back */
669 KfLowerIrql(OldIrql);
670 _disable();
671
672 /* Do a quick V86 exit if possible */
673 KiExitV86Trap(TrapFrame);
674 }
675
676 /* Save trap frame */
677 KiEnterTrap(TrapFrame);
678
679 /* Enable interrupts */
680 Instruction = (PUCHAR)TrapFrame->Eip;
681 _enable();
682
683 /* Check for user trap */
684 if (KiUserTrap(TrapFrame))
685 {
686 /* FIXME: Use SEH */
687
688 /* Scan next 4 opcodes */
689 for (i = 0; i < 4; i++)
690 {
691 /* Check for LOCK instruction */
692 if (Instruction[i] == 0xF0)
693 {
694 /* Send invalid lock sequence exception */
695 KiDispatchException0Args(STATUS_INVALID_LOCK_SEQUENCE,
696 TrapFrame->Eip,
697 TrapFrame);
698 }
699 }
700
701 /* FIXME: SEH ends here */
702 }
703
704 /* Kernel-mode or user-mode fault (but not LOCK) */
705 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
706 TrapFrame->Eip,
707 TrapFrame);
708
709 }
710
711 DECLSPEC_NORETURN
712 VOID
713 FASTCALL
714 KiTrap07Handler(IN PKTRAP_FRAME TrapFrame)
715 {
716 PKTHREAD Thread, NpxThread;
717 PFX_SAVE_AREA SaveArea, NpxSaveArea;
718 ULONG Cr0;
719
720 /* Save trap frame */
721 KiEnterTrap(TrapFrame);
722
723 /* Try to handle NPX delay load */
724 while (TRUE)
725 {
726 /* Get the current thread */
727 Thread = KeGetCurrentThread();
728
729 /* Get the NPX frame */
730 SaveArea = KiGetThreadNpxArea(Thread);
731
732 /* Check if emulation is enabled */
733 if (SaveArea->Cr0NpxState & CR0_EM)
734 {
735 /* Not implemented */
736 UNIMPLEMENTED_FATAL();
737 }
738
739 /* Save CR0 and check NPX state */
740 Cr0 = __readcr0();
741 if (Thread->NpxState != NPX_STATE_LOADED)
742 {
743 /* Update CR0 */
744 Cr0 &= ~(CR0_MP | CR0_EM | CR0_TS);
745 __writecr0(Cr0);
746
747 /* Get the NPX thread */
748 NpxThread = KeGetCurrentPrcb()->NpxThread;
749 if (NpxThread)
750 {
751 /* Get the NPX frame */
752 NpxSaveArea = KiGetThreadNpxArea(NpxThread);
753
754 /* Save FPU state */
755 DPRINT("FIXME: Save FPU state: %p\n", NpxSaveArea);
756 //Ke386SaveFpuState(NpxSaveArea);
757
758 /* Update NPX state */
759 NpxThread->NpxState = NPX_STATE_NOT_LOADED;
760 }
761
762 /* Load FPU state */
763 //Ke386LoadFpuState(SaveArea);
764
765 /* Update NPX state */
766 Thread->NpxState = NPX_STATE_LOADED;
767 KeGetCurrentPrcb()->NpxThread = Thread;
768
769 /* Enable interrupts */
770 _enable();
771
772 /* Check if CR0 needs to be reloaded due to context switch */
773 if (!SaveArea->Cr0NpxState) KiEoiHelper(TrapFrame);
774
775 /* Otherwise, we need to reload CR0, disable interrupts */
776 _disable();
777
778 /* Reload CR0 */
779 Cr0 = __readcr0();
780 Cr0 |= SaveArea->Cr0NpxState;
781 __writecr0(Cr0);
782
783 /* Now restore interrupts and check for TS */
784 _enable();
785 if (Cr0 & CR0_TS) KiEoiHelper(TrapFrame);
786
787 /* We're still here -- clear TS and try again */
788 __writecr0(__readcr0() &~ CR0_TS);
789 _disable();
790 }
791 else
792 {
793 /* This is an actual fault, not a lack of FPU state */
794 break;
795 }
796 }
797
798 /* TS should not be set */
799 if (Cr0 & CR0_TS)
800 {
801 /*
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.
805 */
806 if (Cr0 & CR0_MP)
807 {
808 /* Indeed, the state is actually still valid, so clear TS */
809 __writecr0(__readcr0() &~ CR0_TS);
810 KiEoiHelper(TrapFrame);
811 }
812
813 /* Otherwise, something strange is going on */
814 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 2, Cr0, 0, 0, TrapFrame);
815 }
816
817 /* It's not a delayed load, so process this trap as an NPX fault */
818 KiNpxHandler(TrapFrame, Thread, SaveArea);
819 }
820
821 DECLSPEC_NORETURN
822 VOID
823 FASTCALL
824 KiTrap08Handler(IN PKTRAP_FRAME TrapFrame)
825 {
826 /* FIXME: Not handled */
827 KiSystemFatalException(EXCEPTION_DOUBLE_FAULT, TrapFrame);
828 }
829
830 DECLSPEC_NORETURN
831 VOID
832 FASTCALL
833 KiTrap09Handler(IN PKTRAP_FRAME TrapFrame)
834 {
835 /* Save trap frame */
836 KiEnterTrap(TrapFrame);
837
838 /* Enable interrupts and kill the system */
839 _enable();
840 KiSystemFatalException(EXCEPTION_NPX_OVERRUN, TrapFrame);
841 }
842
843 DECLSPEC_NORETURN
844 VOID
845 FASTCALL
846 KiTrap0AHandler(IN PKTRAP_FRAME TrapFrame)
847 {
848 /* Save trap frame */
849 KiEnterTrap(TrapFrame);
850
851 /* Check for VDM trap */
852 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
853
854 /* Kill the system */
855 KiSystemFatalException(EXCEPTION_INVALID_TSS, TrapFrame);
856 }
857
858 DECLSPEC_NORETURN
859 VOID
860 FASTCALL
861 KiTrap0BHandler(IN PKTRAP_FRAME TrapFrame)
862 {
863 /* Save trap frame */
864 KiEnterTrap(TrapFrame);
865
866 /* FIXME: Kill the system */
867 UNIMPLEMENTED;
868 KiSystemFatalException(EXCEPTION_SEGMENT_NOT_PRESENT, TrapFrame);
869 }
870
871 DECLSPEC_NORETURN
872 VOID
873 FASTCALL
874 KiTrap0CHandler(IN PKTRAP_FRAME TrapFrame)
875 {
876 /* Save trap frame */
877 KiEnterTrap(TrapFrame);
878
879 /* FIXME: Kill the system */
880 UNIMPLEMENTED;
881 KiSystemFatalException(EXCEPTION_STACK_FAULT, TrapFrame);
882 }
883
884 DECLSPEC_NORETURN
885 VOID
886 FASTCALL
887 KiTrap0DHandler(IN PKTRAP_FRAME TrapFrame)
888 {
889 ULONG i, j, Iopl;
890 BOOLEAN Privileged = FALSE;
891 PUCHAR Instructions;
892 UCHAR Instruction = 0;
893 KIRQL OldIrql;
894
895 /* Check for V86 GPF */
896 if (__builtin_expect(KiV86Trap(TrapFrame), 1))
897 {
898 /* Enter V86 trap */
899 KiEnterV86Trap(TrapFrame);
900
901 /* Must be a VDM process */
902 if (__builtin_expect(!PsGetCurrentProcess()->VdmObjects, 0))
903 {
904 /* Enable interrupts */
905 _enable();
906
907 /* Setup illegal instruction fault */
908 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
909 TrapFrame->Eip,
910 TrapFrame);
911 }
912
913 /* Go to APC level */
914 OldIrql = KfRaiseIrql(APC_LEVEL);
915 _enable();
916
917 /* Handle the V86 opcode */
918 if (__builtin_expect(Ki386HandleOpcodeV86(TrapFrame) == 0xFF, 0))
919 {
920 /* Should only happen in VDM mode */
921 UNIMPLEMENTED_FATAL();
922 }
923
924 /* Bring IRQL back */
925 KfLowerIrql(OldIrql);
926 _disable();
927
928 /* Do a quick V86 exit if possible */
929 KiExitV86Trap(TrapFrame);
930 }
931
932 /* Save trap frame */
933 KiEnterTrap(TrapFrame);
934
935 /* Check for user-mode GPF */
936 if (KiUserTrap(TrapFrame))
937 {
938 /* Should not be VDM */
939 ASSERT(KiVdmTrap(TrapFrame) == FALSE);
940
941 /* Enable interrupts and check error code */
942 _enable();
943 if (!TrapFrame->ErrCode)
944 {
945 /* FIXME: Use SEH */
946 Instructions = (PUCHAR)TrapFrame->Eip;
947
948 /* Scan next 15 bytes */
949 for (i = 0; i < 15; i++)
950 {
951 /* Skip prefix instructions */
952 for (j = 0; j < sizeof(KiTrapPrefixTable); j++)
953 {
954 /* Is this a prefix instruction? */
955 if (Instructions[i] == KiTrapPrefixTable[j])
956 {
957 /* Stop looking */
958 break;
959 }
960 }
961
962 /* Is this NOT any prefix instruction? */
963 if (j == sizeof(KiTrapPrefixTable))
964 {
965 /* We can go ahead and handle the fault now */
966 Instruction = Instructions[i];
967 break;
968 }
969 }
970
971 /* If all we found was prefixes, then this instruction is too long */
972 if (i == 15)
973 {
974 /* Setup illegal instruction fault */
975 KiDispatchException0Args(STATUS_ILLEGAL_INSTRUCTION,
976 TrapFrame->Eip,
977 TrapFrame);
978 }
979
980 /* Check for privileged instructions */
981 DPRINT("Instruction (%d) at fault: %lx %lx %lx %lx\n",
982 i,
983 Instructions[i],
984 Instructions[i + 1],
985 Instructions[i + 2],
986 Instructions[i + 3]);
987 if (Instruction == 0xF4) // HLT
988 {
989 /* HLT is privileged */
990 Privileged = TRUE;
991 }
992 else if (Instruction == 0x0F)
993 {
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
1013 {
1014 /* These are all privileged */
1015 Privileged = TRUE;
1016 }
1017 }
1018 else
1019 {
1020 /* Get the IOPL and compare with the RPL mask */
1021 Iopl = (TrapFrame->EFlags & EFLAGS_IOPL) >> 12;
1022 if ((TrapFrame->SegCs & RPL_MASK) > Iopl)
1023 {
1024 /* I/O privilege error -- check for known instructions */
1025 if ((Instruction == 0xFA) || (Instruction == 0xFB)) // CLI or STI
1026 {
1027 /* These are privileged */
1028 Privileged = TRUE;
1029 }
1030 else
1031 {
1032 /* Last hope: an IN/OUT instruction */
1033 for (j = 0; j < sizeof(KiTrapIoTable); j++)
1034 {
1035 /* Is this an I/O instruction? */
1036 if (Instruction == KiTrapIoTable[j])
1037 {
1038 /* Then it's privileged */
1039 Privileged = TRUE;
1040 break;
1041 }
1042 }
1043 }
1044 }
1045 }
1046
1047 /* So now... was the instruction privileged or not? */
1048 if (Privileged)
1049 {
1050 /* Whew! We have a privileged instruction, so dispatch the fault */
1051 KiDispatchException0Args(STATUS_PRIVILEGED_INSTRUCTION,
1052 TrapFrame->Eip,
1053 TrapFrame);
1054 }
1055 }
1056
1057 /* If we got here, send an access violation */
1058 KiDispatchException2Args(STATUS_ACCESS_VIOLATION,
1059 TrapFrame->Eip,
1060 0,
1061 0xFFFFFFFF,
1062 TrapFrame);
1063 }
1064
1065 /*
1066 * Check for a fault during checking of the user instruction.
1067 *
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.
1070 *
1071 */
1072 if (((PVOID)TrapFrame->Eip >= (PVOID)KiTrap0DHandler) &&
1073 ((PVOID)TrapFrame->Eip < (PVOID)KiTrap0DHandler))
1074 {
1075 /* Not implemented */
1076 UNIMPLEMENTED_FATAL();
1077 }
1078
1079 /*
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.
1083 *
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.
1087 *
1088 * The kernel normally restores the "true" segment if this happens.
1089 *
1090 * However, since we're restoring in C, not ASM, we can't detect
1091 * POP <SEG> since the actual instructions will be different.
1092 *
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.
1096 *
1097 * We could force a special instrinsic to use stack instructions, or write
1098 * a simple instruction length checker.
1099 *
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.
1103 */
1104
1105 /*
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.
1109 *
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.
1112 */
1113 Instructions = (PUCHAR)TrapFrame->Eip;
1114 if (Instructions[0] == 0xCF)
1115 {
1116 /*
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!
1121 */
1122 if ((TrapFrame->HardwareEsp == (ULONG)Ki386BiosCallReturnAddress) &&
1123 (TrapFrame->HardwareSegSs == (KGDT_R0_CODE | RPL_MASK)))
1124 {
1125 /* Exit the V86 trap! */
1126 Ki386BiosCallReturnAddress(TrapFrame);
1127 }
1128 else
1129 {
1130 /* Otherwise, this is another kind of IRET fault */
1131 UNIMPLEMENTED_FATAL();
1132 }
1133 }
1134
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
1139 {
1140 /* Unknown CPU MSR, so raise an access violation */
1141 KiDispatchException0Args(STATUS_ACCESS_VIOLATION,
1142 TrapFrame->Eip,
1143 TrapFrame);
1144 }
1145
1146 /* Check for lazy segment load */
1147 if (TrapFrame->SegDs != (KGDT_R3_DATA | RPL_MASK))
1148 {
1149 /* Fix it */
1150 TrapFrame->SegDs = (KGDT_R3_DATA | RPL_MASK);
1151 }
1152 else if (TrapFrame->SegEs != (KGDT_R3_DATA | RPL_MASK))
1153 {
1154 /* Fix it */
1155 TrapFrame->SegEs = (KGDT_R3_DATA | RPL_MASK);
1156 }
1157 else
1158 {
1159 /* Whatever it is, we can't handle it */
1160 KiSystemFatalException(EXCEPTION_GP_FAULT, TrapFrame);
1161 }
1162
1163 /* Return to where we came from */
1164 KiTrapReturn(TrapFrame);
1165 }
1166
1167 DECLSPEC_NORETURN
1168 VOID
1169 FASTCALL
1170 KiTrap0EHandler(IN PKTRAP_FRAME TrapFrame)
1171 {
1172 PKTHREAD Thread;
1173 ULONG_PTR Cr2;
1174 NTSTATUS Status;
1175
1176 /* Save trap frame */
1177 KiEnterTrap(TrapFrame);
1178
1179 /* Check if this is the base frame */
1180 Thread = KeGetCurrentThread();
1181 if (KeGetTrapFrame(Thread) != TrapFrame)
1182 {
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))
1186 {
1187 /* The stack is somewhere in between frames, we need to fix it */
1188 UNIMPLEMENTED_FATAL();
1189 }
1190 }
1191
1192 /* Save CR2 */
1193 Cr2 = __readcr2();
1194
1195 /* Enable interupts */
1196 _enable();
1197
1198 /* Check if we came in with interrupts disabled */
1199 if (!(TrapFrame->EFlags & EFLAGS_INTERRUPT_MASK))
1200 {
1201 /* This is completely illegal, bugcheck the system */
1202 KeBugCheckWithTf(IRQL_NOT_LESS_OR_EQUAL,
1203 Cr2,
1204 -1,
1205 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1206 TrapFrame->Eip,
1207 TrapFrame);
1208 }
1209
1210 /* Check for S-LIST fault in kernel mode */
1211 if (TrapFrame->Eip == (ULONG_PTR)ExpInterlockedPopEntrySListFault)
1212 {
1213 PSLIST_HEADER SListHeader;
1214
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));
1224
1225 /* Get the pointer to the SLIST_HEADER */
1226 SListHeader = (PSLIST_HEADER)TrapFrame->Ebp;
1227
1228 /* Check if the Next member of the SLIST_HEADER was changed */
1229 if (SListHeader->Next.Next != (PSLIST_ENTRY)TrapFrame->Eax)
1230 {
1231 /* Restart the operation */
1232 TrapFrame->Eip = (ULONG_PTR)ExpInterlockedPopEntrySListResume;
1233
1234 /* Continue execution */
1235 KiEoiHelper(TrapFrame);
1236 }
1237 }
1238
1239 /* Call the access fault handler */
1240 Status = MmAccessFault(TrapFrame->ErrCode & 1,
1241 (PVOID)Cr2,
1242 TrapFrame->SegCs & MODE_MASK,
1243 TrapFrame);
1244 if (NT_SUCCESS(Status)) KiEoiHelper(TrapFrame);
1245
1246 /* Check for syscall fault */
1247 #if 0
1248 if ((TrapFrame->Eip == (ULONG_PTR)CopyParams) ||
1249 (TrapFrame->Eip == (ULONG_PTR)ReadBatch))
1250 {
1251 /* Not yet implemented */
1252 UNIMPLEMENTED_FATAL();
1253 }
1254 #endif
1255 /* Check for VDM trap */
1256 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
1257
1258 /* Either kernel or user trap (non VDM) so dispatch exception */
1259 if (Status == STATUS_ACCESS_VIOLATION)
1260 {
1261 /* This status code is repurposed so we can recognize it later */
1262 KiDispatchException2Args(KI_EXCEPTION_ACCESS_VIOLATION,
1263 TrapFrame->Eip,
1264 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1265 Cr2,
1266 TrapFrame);
1267 }
1268 else if ((Status == STATUS_GUARD_PAGE_VIOLATION) ||
1269 (Status == STATUS_STACK_OVERFLOW))
1270 {
1271 /* These faults only have two parameters */
1272 KiDispatchException2Args(Status,
1273 TrapFrame->Eip,
1274 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1275 Cr2,
1276 TrapFrame);
1277 }
1278
1279 /* Only other choice is an in-page error, with 3 parameters */
1280 KiDispatchExceptionFromTrapFrame(STATUS_IN_PAGE_ERROR,
1281 TrapFrame->Eip,
1282 3,
1283 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1284 Cr2,
1285 Status,
1286 TrapFrame);
1287 }
1288
1289 DECLSPEC_NORETURN
1290 VOID
1291 FASTCALL
1292 KiTrap0FHandler(IN PKTRAP_FRAME TrapFrame)
1293 {
1294 /* Save trap frame */
1295 KiEnterTrap(TrapFrame);
1296
1297 /* FIXME: Kill the system */
1298 UNIMPLEMENTED;
1299 KiSystemFatalException(EXCEPTION_RESERVED_TRAP, TrapFrame);
1300 }
1301
1302 DECLSPEC_NORETURN
1303 VOID
1304 FASTCALL
1305 KiTrap10Handler(IN PKTRAP_FRAME TrapFrame)
1306 {
1307 PKTHREAD Thread;
1308 PFX_SAVE_AREA SaveArea;
1309
1310 /* Save trap frame */
1311 KiEnterTrap(TrapFrame);
1312
1313 /* Check if this is the NPX thrad */
1314 Thread = KeGetCurrentThread();
1315 SaveArea = KiGetThreadNpxArea(Thread);
1316 if (Thread != KeGetCurrentPrcb()->NpxThread)
1317 {
1318 /* It isn't, enable interrupts and set delayed error */
1319 _enable();
1320 SaveArea->Cr0NpxState |= CR0_TS;
1321
1322 /* End trap */
1323 KiEoiHelper(TrapFrame);
1324 }
1325
1326 /* Otherwise, proceed with NPX fault handling */
1327 KiNpxHandler(TrapFrame, Thread, SaveArea);
1328 }
1329
1330 DECLSPEC_NORETURN
1331 VOID
1332 FASTCALL
1333 KiTrap11Handler(IN PKTRAP_FRAME TrapFrame)
1334 {
1335 /* Save trap frame */
1336 KiEnterTrap(TrapFrame);
1337
1338 /* Enable interrupts and kill the system */
1339 _enable();
1340 KiSystemFatalException(EXCEPTION_ALIGNMENT_CHECK, TrapFrame);
1341 }
1342
1343 DECLSPEC_NORETURN
1344 VOID
1345 FASTCALL
1346 KiTrap13Handler(IN PKTRAP_FRAME TrapFrame)
1347 {
1348 PKTHREAD Thread;
1349 PFX_SAVE_AREA SaveArea;
1350 ULONG Cr0, MxCsrMask, Error;
1351
1352 /* Save trap frame */
1353 KiEnterTrap(TrapFrame);
1354
1355 /* Check if this is the NPX thrad */
1356 Thread = KeGetCurrentThread();
1357 if (Thread != KeGetCurrentPrcb()->NpxThread)
1358 {
1359 /* It isn't, kill the system */
1360 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, (ULONG_PTR)Thread, 0, 0, TrapFrame);
1361 }
1362
1363 /* Get the NPX frame */
1364 SaveArea = KiGetThreadNpxArea(Thread);
1365
1366 /* Check for VDM trap */
1367 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
1368
1369 /* Check for user trap */
1370 if (!KiUserTrap(TrapFrame))
1371 {
1372 /* Kernel should not fault on XMMI */
1373 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, 0, 0, 2, TrapFrame);
1374 }
1375
1376 /* Update CR0 */
1377 Cr0 = __readcr0();
1378 Cr0 &= ~(CR0_MP | CR0_EM | CR0_TS);
1379 __writecr0(Cr0);
1380
1381 /* Save FPU state */
1382 Ke386SaveFpuState(SaveArea);
1383
1384 /* Mark CR0 state dirty */
1385 Cr0 |= NPX_STATE_NOT_LOADED;
1386 Cr0 |= SaveArea->Cr0NpxState;
1387 __writecr0(Cr0);
1388
1389 /* Update NPX state */
1390 Thread->NpxState = NPX_STATE_NOT_LOADED;
1391 KeGetCurrentPrcb()->NpxThread = NULL;
1392
1393 /* Clear the TS bit and re-enable interrupts */
1394 SaveArea->Cr0NpxState &= ~CR0_TS;
1395 _enable();
1396
1397 /* Now look at MxCsr to get the mask of errors we should care about */
1398 MxCsrMask = ~((USHORT)SaveArea->U.FxArea.MXCsr >> 7);
1399
1400 /* Get legal exceptions that software should handle */
1401 Error = (USHORT)SaveArea->U.FxArea.MXCsr & (FSW_INVALID_OPERATION |
1402 FSW_DENORMAL |
1403 FSW_ZERO_DIVIDE |
1404 FSW_OVERFLOW |
1405 FSW_UNDERFLOW |
1406 FSW_PRECISION);
1407 Error &= MxCsrMask;
1408
1409 /* Now handle any of those legal errors */
1410 if (Error & (FSW_INVALID_OPERATION |
1411 FSW_DENORMAL |
1412 FSW_ZERO_DIVIDE |
1413 FSW_OVERFLOW |
1414 FSW_UNDERFLOW |
1415 FSW_PRECISION))
1416 {
1417 /* By issuing an exception */
1418 KiDispatchException1Args(STATUS_FLOAT_MULTIPLE_TRAPS,
1419 TrapFrame->Eip,
1420 0,
1421 TrapFrame);
1422 }
1423
1424 /* Unknown XMMI fault */
1425 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, 0, 0, 1, TrapFrame);
1426 }
1427
1428 /* SOFTWARE SERVICES **********************************************************/
1429
1430 VOID
1431 FASTCALL
1432 KiGetTickCountHandler(IN PKTRAP_FRAME TrapFrame)
1433 {
1434 UNIMPLEMENTED_DBGBREAK();
1435 }
1436
1437 VOID
1438 FASTCALL
1439 KiCallbackReturnHandler(IN PKTRAP_FRAME TrapFrame)
1440 {
1441 UNIMPLEMENTED_DBGBREAK();
1442 }
1443
1444 DECLSPEC_NORETURN
1445 VOID
1446 FASTCALL
1447 KiRaiseAssertionHandler(IN PKTRAP_FRAME TrapFrame)
1448 {
1449 /* Save trap frame */
1450 KiEnterTrap(TrapFrame);
1451
1452 /* Decrement EIP to point to the INT2C instruction (2 bytes, not 1 like INT3) */
1453 TrapFrame->Eip -= 2;
1454
1455 /* Dispatch the exception */
1456 KiDispatchException0Args(STATUS_ASSERTION_FAILURE,
1457 TrapFrame->Eip,
1458 TrapFrame);
1459 }
1460
1461 DECLSPEC_NORETURN
1462 VOID
1463 FASTCALL
1464 KiDebugServiceHandler(IN PKTRAP_FRAME TrapFrame)
1465 {
1466 /* Save trap frame */
1467 KiEnterTrap(TrapFrame);
1468
1469 /* Increment EIP to skip the INT3 instruction */
1470 TrapFrame->Eip++;
1471
1472 /* Continue with the common handler */
1473 KiDebugHandler(TrapFrame, TrapFrame->Eax, TrapFrame->Ecx, TrapFrame->Edx);
1474 }
1475
1476
1477 FORCEINLINE
1478 VOID
1479 KiDbgPreServiceHook(ULONG SystemCallNumber, PULONG_PTR Arguments)
1480 {
1481 #if DBG && !defined(_WINKD_)
1482 if (SystemCallNumber >= 0x1000 && KeWin32PreServiceHook)
1483 KeWin32PreServiceHook(SystemCallNumber, Arguments);
1484 #endif
1485 }
1486
1487 FORCEINLINE
1488 ULONG_PTR
1489 KiDbgPostServiceHook(ULONG SystemCallNumber, ULONG_PTR Result)
1490 {
1491 #if DBG && !defined(_WINKD_)
1492 if (SystemCallNumber >= 0x1000 && KeWin32PostServiceHook)
1493 return KeWin32PostServiceHook(SystemCallNumber, Result);
1494 #endif
1495 return Result;
1496 }
1497
1498 DECLSPEC_NORETURN
1499 VOID
1500 FORCEINLINE
1501 KiSystemCall(IN PKTRAP_FRAME TrapFrame,
1502 IN PVOID Arguments)
1503 {
1504 PKTHREAD Thread;
1505 PKSERVICE_TABLE_DESCRIPTOR DescriptorTable;
1506 ULONG Id, Offset, StackBytes, Result;
1507 PVOID Handler;
1508 ULONG SystemCallNumber = TrapFrame->Eax;
1509
1510 /* Get the current thread */
1511 Thread = KeGetCurrentThread();
1512
1513 /* Set debug header */
1514 KiFillTrapFrameDebug(TrapFrame);
1515
1516 /* Chain trap frames */
1517 TrapFrame->Edx = (ULONG_PTR)Thread->TrapFrame;
1518
1519 /* No error code */
1520 TrapFrame->ErrCode = 0;
1521
1522 /* Save previous mode */
1523 TrapFrame->PreviousPreviousMode = Thread->PreviousMode;
1524
1525 /* Save the SEH chain and terminate it for now */
1526 TrapFrame->ExceptionList = KeGetPcr()->NtTib.ExceptionList;
1527 KeGetPcr()->NtTib.ExceptionList = EXCEPTION_CHAIN_END;
1528
1529 /* Default to debugging disabled */
1530 TrapFrame->Dr7 = 0;
1531
1532 /* Check if the frame was from user mode */
1533 if (TrapFrame->SegCs & MODE_MASK)
1534 {
1535 /* Check for active debugging */
1536 if (KeGetCurrentThread()->Header.DebugActive & 0xFF)
1537 {
1538 /* Handle debug registers */
1539 KiHandleDebugRegistersOnTrapEntry(TrapFrame);
1540 }
1541 }
1542
1543 /* Set thread fields */
1544 Thread->TrapFrame = TrapFrame;
1545 Thread->PreviousMode = KiUserTrap(TrapFrame);
1546
1547 /* Enable interrupts */
1548 _enable();
1549
1550 /* Decode the system call number */
1551 Offset = (SystemCallNumber >> SERVICE_TABLE_SHIFT) & SERVICE_TABLE_MASK;
1552 Id = SystemCallNumber & SERVICE_NUMBER_MASK;
1553
1554 /* Get descriptor table */
1555 DescriptorTable = (PVOID)((ULONG_PTR)Thread->ServiceTable + Offset);
1556
1557 /* Validate the system call number */
1558 if (__builtin_expect(Id >= DescriptorTable->Limit, 0))
1559 {
1560 /* Check if this is a GUI call */
1561 if (!(Offset & SERVICE_TABLE_TEST))
1562 {
1563 /* Fail the call */
1564 Result = STATUS_INVALID_SYSTEM_SERVICE;
1565 goto ExitCall;
1566 }
1567
1568 /* Convert us to a GUI thread -- must wrap in ASM to get new EBP */
1569 Result = KiConvertToGuiThread();
1570
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);
1574
1575 if (!NT_SUCCESS(Result))
1576 {
1577 /* Set the last error and fail */
1578 //SetLastWin32Error(RtlNtStatusToDosError(Result));
1579 goto ExitCall;
1580 }
1581
1582 /* Validate the system call number again */
1583 if (Id >= DescriptorTable->Limit)
1584 {
1585 /* Fail the call */
1586 Result = STATUS_INVALID_SYSTEM_SERVICE;
1587 goto ExitCall;
1588 }
1589 }
1590
1591 /* Check if this is a GUI call */
1592 if (__builtin_expect(Offset & SERVICE_TABLE_TEST, 0))
1593 {
1594 /* Get the batch count and flush if necessary */
1595 if (NtCurrentTeb()->GdiBatchCount) KeGdiFlushUserBatch();
1596 }
1597
1598 /* Increase system call count */
1599 KeGetCurrentPrcb()->KeSystemCalls++;
1600
1601 /* FIXME: Increase individual counts on debug systems */
1602 //KiIncreaseSystemCallCount(DescriptorTable, Id);
1603
1604 /* Get stack bytes */
1605 StackBytes = DescriptorTable->Number[Id];
1606
1607 /* Probe caller stack */
1608 if (__builtin_expect((Arguments < (PVOID)MmUserProbeAddress) && !(KiUserTrap(TrapFrame)), 0))
1609 {
1610 /* Access violation */
1611 UNIMPLEMENTED_FATAL();
1612 }
1613
1614 /* Call pre-service debug hook */
1615 KiDbgPreServiceHook(SystemCallNumber, Arguments);
1616
1617 /* Get the handler and make the system call */
1618 Handler = (PVOID)DescriptorTable->Base[Id];
1619 Result = KiSystemCallTrampoline(Handler, Arguments, StackBytes);
1620
1621 /* Call post-service debug hook */
1622 Result = KiDbgPostServiceHook(SystemCallNumber, Result);
1623
1624 /* Make sure we're exiting correctly */
1625 KiExitSystemCallDebugChecks(Id, TrapFrame);
1626
1627 /* Restore the old trap frame */
1628 ExitCall:
1629 Thread->TrapFrame = (PKTRAP_FRAME)TrapFrame->Edx;
1630
1631 /* Exit from system call */
1632 KiServiceExit(TrapFrame, Result);
1633 }
1634
1635 DECLSPEC_NORETURN
1636 VOID
1637 FASTCALL
1638 KiSystemServiceHandler(IN PKTRAP_FRAME TrapFrame,
1639 IN PVOID Arguments)
1640 {
1641 /* Call the shared handler (inline) */
1642 KiSystemCall(TrapFrame, Arguments);
1643 }
1644
1645 DECLSPEC_NORETURN
1646 VOID
1647 FASTCALL
1648 KiFastCallEntryHandler(IN PKTRAP_FRAME TrapFrame,
1649 IN PVOID Arguments)
1650 {
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;
1658 __writeeflags(0x2);
1659
1660 /* Arguments are actually 2 frames down (because of the double indirection) */
1661 Arguments = (PVOID)(TrapFrame->HardwareEsp + 8);
1662
1663 /* Call the shared handler (inline) */
1664 KiSystemCall(TrapFrame, Arguments);
1665 }
1666
1667 /*
1668 * @implemented
1669 */
1670 VOID
1671 NTAPI
1672 Kei386EoiHelper(VOID)
1673 {
1674 /* We should never see this call happening */
1675 ERROR_FATAL("Mismatched NT/HAL version");
1676 }
1677
1678 /* EOF */