[NTOSKRNL]
[reactos.git] / reactos / 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 (%lu) 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 else
1238 {
1239 #if 0
1240 /* Do what windows does and issue an invalid access violation */
1241 KiDispatchException2Args(KI_EXCEPTION_ACCESS_VIOLATION,
1242 TrapFrame->Eip,
1243 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1244 Cr2,
1245 TrapFrame);
1246 #endif
1247 }
1248 }
1249
1250 /* Call the access fault handler */
1251 Status = MmAccessFault(TrapFrame->ErrCode & 1,
1252 (PVOID)Cr2,
1253 TrapFrame->SegCs & MODE_MASK,
1254 TrapFrame);
1255 if (NT_SUCCESS(Status)) KiEoiHelper(TrapFrame);
1256
1257 /* Check for syscall fault */
1258 #if 0
1259 if ((TrapFrame->Eip == (ULONG_PTR)CopyParams) ||
1260 (TrapFrame->Eip == (ULONG_PTR)ReadBatch))
1261 {
1262 /* Not yet implemented */
1263 UNIMPLEMENTED_FATAL();
1264 }
1265 #endif
1266 /* Check for VDM trap */
1267 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
1268
1269 /* Either kernel or user trap (non VDM) so dispatch exception */
1270 if (Status == STATUS_ACCESS_VIOLATION)
1271 {
1272 /* This status code is repurposed so we can recognize it later */
1273 KiDispatchException2Args(KI_EXCEPTION_ACCESS_VIOLATION,
1274 TrapFrame->Eip,
1275 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1276 Cr2,
1277 TrapFrame);
1278 }
1279 else if ((Status == STATUS_GUARD_PAGE_VIOLATION) ||
1280 (Status == STATUS_STACK_OVERFLOW))
1281 {
1282 /* These faults only have two parameters */
1283 KiDispatchException2Args(Status,
1284 TrapFrame->Eip,
1285 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1286 Cr2,
1287 TrapFrame);
1288 }
1289
1290 /* Only other choice is an in-page error, with 3 parameters */
1291 KiDispatchExceptionFromTrapFrame(STATUS_IN_PAGE_ERROR,
1292 TrapFrame->Eip,
1293 3,
1294 TrapFrame->ErrCode & 2 ? TRUE : FALSE,
1295 Cr2,
1296 Status,
1297 TrapFrame);
1298 }
1299
1300 DECLSPEC_NORETURN
1301 VOID
1302 FASTCALL
1303 KiTrap0FHandler(IN PKTRAP_FRAME TrapFrame)
1304 {
1305 /* Save trap frame */
1306 KiEnterTrap(TrapFrame);
1307
1308 /* FIXME: Kill the system */
1309 UNIMPLEMENTED;
1310 KiSystemFatalException(EXCEPTION_RESERVED_TRAP, TrapFrame);
1311 }
1312
1313 DECLSPEC_NORETURN
1314 VOID
1315 FASTCALL
1316 KiTrap10Handler(IN PKTRAP_FRAME TrapFrame)
1317 {
1318 PKTHREAD Thread;
1319 PFX_SAVE_AREA SaveArea;
1320
1321 /* Save trap frame */
1322 KiEnterTrap(TrapFrame);
1323
1324 /* Check if this is the NPX thrad */
1325 Thread = KeGetCurrentThread();
1326 SaveArea = KiGetThreadNpxArea(Thread);
1327 if (Thread != KeGetCurrentPrcb()->NpxThread)
1328 {
1329 /* It isn't, enable interrupts and set delayed error */
1330 _enable();
1331 SaveArea->Cr0NpxState |= CR0_TS;
1332
1333 /* End trap */
1334 KiEoiHelper(TrapFrame);
1335 }
1336
1337 /* Otherwise, proceed with NPX fault handling */
1338 KiNpxHandler(TrapFrame, Thread, SaveArea);
1339 }
1340
1341 DECLSPEC_NORETURN
1342 VOID
1343 FASTCALL
1344 KiTrap11Handler(IN PKTRAP_FRAME TrapFrame)
1345 {
1346 /* Save trap frame */
1347 KiEnterTrap(TrapFrame);
1348
1349 /* Enable interrupts and kill the system */
1350 _enable();
1351 KiSystemFatalException(EXCEPTION_ALIGNMENT_CHECK, TrapFrame);
1352 }
1353
1354 DECLSPEC_NORETURN
1355 VOID
1356 FASTCALL
1357 KiTrap13Handler(IN PKTRAP_FRAME TrapFrame)
1358 {
1359 PKTHREAD Thread;
1360 PFX_SAVE_AREA SaveArea;
1361 ULONG Cr0, MxCsrMask, Error;
1362
1363 /* Save trap frame */
1364 KiEnterTrap(TrapFrame);
1365
1366 /* Check if this is the NPX thrad */
1367 Thread = KeGetCurrentThread();
1368 if (Thread != KeGetCurrentPrcb()->NpxThread)
1369 {
1370 /* It isn't, kill the system */
1371 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, (ULONG_PTR)Thread, 0, 0, TrapFrame);
1372 }
1373
1374 /* Get the NPX frame */
1375 SaveArea = KiGetThreadNpxArea(Thread);
1376
1377 /* Check for VDM trap */
1378 ASSERT((KiVdmTrap(TrapFrame)) == FALSE);
1379
1380 /* Check for user trap */
1381 if (!KiUserTrap(TrapFrame))
1382 {
1383 /* Kernel should not fault on XMMI */
1384 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, 0, 0, 2, TrapFrame);
1385 }
1386
1387 /* Update CR0 */
1388 Cr0 = __readcr0();
1389 Cr0 &= ~(CR0_MP | CR0_EM | CR0_TS);
1390 __writecr0(Cr0);
1391
1392 /* Save FPU state */
1393 Ke386SaveFpuState(SaveArea);
1394
1395 /* Mark CR0 state dirty */
1396 Cr0 |= NPX_STATE_NOT_LOADED;
1397 Cr0 |= SaveArea->Cr0NpxState;
1398 __writecr0(Cr0);
1399
1400 /* Update NPX state */
1401 Thread->NpxState = NPX_STATE_NOT_LOADED;
1402 KeGetCurrentPrcb()->NpxThread = NULL;
1403
1404 /* Clear the TS bit and re-enable interrupts */
1405 SaveArea->Cr0NpxState &= ~CR0_TS;
1406 _enable();
1407
1408 /* Now look at MxCsr to get the mask of errors we should care about */
1409 MxCsrMask = ~((USHORT)SaveArea->U.FxArea.MXCsr >> 7);
1410
1411 /* Get legal exceptions that software should handle */
1412 Error = (USHORT)SaveArea->U.FxArea.MXCsr & (FSW_INVALID_OPERATION |
1413 FSW_DENORMAL |
1414 FSW_ZERO_DIVIDE |
1415 FSW_OVERFLOW |
1416 FSW_UNDERFLOW |
1417 FSW_PRECISION);
1418 Error &= MxCsrMask;
1419
1420 /* Now handle any of those legal errors */
1421 if (Error & (FSW_INVALID_OPERATION |
1422 FSW_DENORMAL |
1423 FSW_ZERO_DIVIDE |
1424 FSW_OVERFLOW |
1425 FSW_UNDERFLOW |
1426 FSW_PRECISION))
1427 {
1428 /* By issuing an exception */
1429 KiDispatchException1Args(STATUS_FLOAT_MULTIPLE_TRAPS,
1430 TrapFrame->Eip,
1431 0,
1432 TrapFrame);
1433 }
1434
1435 /* Unknown XMMI fault */
1436 KeBugCheckWithTf(TRAP_CAUSE_UNKNOWN, 13, 0, 0, 1, TrapFrame);
1437 }
1438
1439 /* SOFTWARE SERVICES **********************************************************/
1440
1441 VOID
1442 FASTCALL
1443 KiGetTickCountHandler(IN PKTRAP_FRAME TrapFrame)
1444 {
1445 UNIMPLEMENTED_DBGBREAK();
1446 }
1447
1448 VOID
1449 FASTCALL
1450 KiCallbackReturnHandler(IN PKTRAP_FRAME TrapFrame)
1451 {
1452 UNIMPLEMENTED_DBGBREAK();
1453 }
1454
1455 DECLSPEC_NORETURN
1456 VOID
1457 FASTCALL
1458 KiRaiseAssertionHandler(IN PKTRAP_FRAME TrapFrame)
1459 {
1460 /* Save trap frame */
1461 KiEnterTrap(TrapFrame);
1462
1463 /* Decrement EIP to point to the INT2C instruction (2 bytes, not 1 like INT3) */
1464 TrapFrame->Eip -= 2;
1465
1466 /* Dispatch the exception */
1467 KiDispatchException0Args(STATUS_ASSERTION_FAILURE,
1468 TrapFrame->Eip,
1469 TrapFrame);
1470 }
1471
1472 DECLSPEC_NORETURN
1473 VOID
1474 FASTCALL
1475 KiDebugServiceHandler(IN PKTRAP_FRAME TrapFrame)
1476 {
1477 /* Save trap frame */
1478 KiEnterTrap(TrapFrame);
1479
1480 /* Increment EIP to skip the INT3 instruction */
1481 TrapFrame->Eip++;
1482
1483 /* Continue with the common handler */
1484 KiDebugHandler(TrapFrame, TrapFrame->Eax, TrapFrame->Ecx, TrapFrame->Edx);
1485 }
1486
1487
1488 FORCEINLINE
1489 VOID
1490 KiDbgPreServiceHook(ULONG SystemCallNumber, PULONG_PTR Arguments)
1491 {
1492 #if DBG && !defined(_WINKD_)
1493 if (SystemCallNumber >= 0x1000 && KeWin32PreServiceHook)
1494 KeWin32PreServiceHook(SystemCallNumber, Arguments);
1495 #endif
1496 }
1497
1498 FORCEINLINE
1499 ULONG_PTR
1500 KiDbgPostServiceHook(ULONG SystemCallNumber, ULONG_PTR Result)
1501 {
1502 #if DBG && !defined(_WINKD_)
1503 if (SystemCallNumber >= 0x1000 && KeWin32PostServiceHook)
1504 return KeWin32PostServiceHook(SystemCallNumber, Result);
1505 #endif
1506 return Result;
1507 }
1508
1509 DECLSPEC_NORETURN
1510 VOID
1511 FORCEINLINE
1512 KiSystemCall(IN PKTRAP_FRAME TrapFrame,
1513 IN PVOID Arguments)
1514 {
1515 PKTHREAD Thread;
1516 PKSERVICE_TABLE_DESCRIPTOR DescriptorTable;
1517 ULONG Id, Offset, StackBytes, Result;
1518 PVOID Handler;
1519 ULONG SystemCallNumber = TrapFrame->Eax;
1520
1521 /* Get the current thread */
1522 Thread = KeGetCurrentThread();
1523
1524 /* Set debug header */
1525 KiFillTrapFrameDebug(TrapFrame);
1526
1527 /* Chain trap frames */
1528 TrapFrame->Edx = (ULONG_PTR)Thread->TrapFrame;
1529
1530 /* No error code */
1531 TrapFrame->ErrCode = 0;
1532
1533 /* Save previous mode */
1534 TrapFrame->PreviousPreviousMode = Thread->PreviousMode;
1535
1536 /* Save the SEH chain and terminate it for now */
1537 TrapFrame->ExceptionList = KeGetPcr()->NtTib.ExceptionList;
1538 KeGetPcr()->NtTib.ExceptionList = EXCEPTION_CHAIN_END;
1539
1540 /* Default to debugging disabled */
1541 TrapFrame->Dr7 = 0;
1542
1543 /* Check if the frame was from user mode */
1544 if (TrapFrame->SegCs & MODE_MASK)
1545 {
1546 /* Check for active debugging */
1547 if (KeGetCurrentThread()->Header.DebugActive & 0xFF)
1548 {
1549 /* Handle debug registers */
1550 KiHandleDebugRegistersOnTrapEntry(TrapFrame);
1551 }
1552 }
1553
1554 /* Set thread fields */
1555 Thread->TrapFrame = TrapFrame;
1556 Thread->PreviousMode = KiUserTrap(TrapFrame);
1557
1558 /* Enable interrupts */
1559 _enable();
1560
1561 /* Decode the system call number */
1562 Offset = (SystemCallNumber >> SERVICE_TABLE_SHIFT) & SERVICE_TABLE_MASK;
1563 Id = SystemCallNumber & SERVICE_NUMBER_MASK;
1564
1565 /* Get descriptor table */
1566 DescriptorTable = (PVOID)((ULONG_PTR)Thread->ServiceTable + Offset);
1567
1568 /* Validate the system call number */
1569 if (__builtin_expect(Id >= DescriptorTable->Limit, 0))
1570 {
1571 /* Check if this is a GUI call */
1572 if (!(Offset & SERVICE_TABLE_TEST))
1573 {
1574 /* Fail the call */
1575 Result = STATUS_INVALID_SYSTEM_SERVICE;
1576 goto ExitCall;
1577 }
1578
1579 /* Convert us to a GUI thread -- must wrap in ASM to get new EBP */
1580 Result = KiConvertToGuiThread();
1581
1582 /* Reload trap frame and descriptor table pointer from new stack */
1583 TrapFrame = *(volatile PVOID*)&Thread->TrapFrame;
1584 DescriptorTable = (PVOID)(*(volatile ULONG_PTR*)&Thread->ServiceTable + Offset);
1585
1586 if (!NT_SUCCESS(Result))
1587 {
1588 /* Set the last error and fail */
1589 //SetLastWin32Error(RtlNtStatusToDosError(Result));
1590 goto ExitCall;
1591 }
1592
1593 /* Validate the system call number again */
1594 if (Id >= DescriptorTable->Limit)
1595 {
1596 /* Fail the call */
1597 Result = STATUS_INVALID_SYSTEM_SERVICE;
1598 goto ExitCall;
1599 }
1600 }
1601
1602 /* Check if this is a GUI call */
1603 if (__builtin_expect(Offset & SERVICE_TABLE_TEST, 0))
1604 {
1605 /* Get the batch count and flush if necessary */
1606 if (NtCurrentTeb()->GdiBatchCount) KeGdiFlushUserBatch();
1607 }
1608
1609 /* Increase system call count */
1610 KeGetCurrentPrcb()->KeSystemCalls++;
1611
1612 /* FIXME: Increase individual counts on debug systems */
1613 //KiIncreaseSystemCallCount(DescriptorTable, Id);
1614
1615 /* Get stack bytes */
1616 StackBytes = DescriptorTable->Number[Id];
1617
1618 /* Probe caller stack */
1619 if (__builtin_expect((Arguments < (PVOID)MmUserProbeAddress) && !(KiUserTrap(TrapFrame)), 0))
1620 {
1621 /* Access violation */
1622 UNIMPLEMENTED_FATAL();
1623 }
1624
1625 /* Call pre-service debug hook */
1626 KiDbgPreServiceHook(SystemCallNumber, Arguments);
1627
1628 /* Get the handler and make the system call */
1629 Handler = (PVOID)DescriptorTable->Base[Id];
1630 Result = KiSystemCallTrampoline(Handler, Arguments, StackBytes);
1631
1632 /* Call post-service debug hook */
1633 Result = KiDbgPostServiceHook(SystemCallNumber, Result);
1634
1635 /* Make sure we're exiting correctly */
1636 KiExitSystemCallDebugChecks(Id, TrapFrame);
1637
1638 /* Restore the old trap frame */
1639 ExitCall:
1640 Thread->TrapFrame = (PKTRAP_FRAME)TrapFrame->Edx;
1641
1642 /* Exit from system call */
1643 KiServiceExit(TrapFrame, Result);
1644 }
1645
1646 DECLSPEC_NORETURN
1647 VOID
1648 FASTCALL
1649 KiSystemServiceHandler(IN PKTRAP_FRAME TrapFrame,
1650 IN PVOID Arguments)
1651 {
1652 /* Call the shared handler (inline) */
1653 KiSystemCall(TrapFrame, Arguments);
1654 }
1655
1656 DECLSPEC_NORETURN
1657 VOID
1658 FASTCALL
1659 KiFastCallEntryHandler(IN PKTRAP_FRAME TrapFrame,
1660 IN PVOID Arguments)
1661 {
1662 /* Set up a fake INT Stack and enable interrupts */
1663 TrapFrame->HardwareSegSs = KGDT_R3_DATA | RPL_MASK;
1664 TrapFrame->HardwareEsp = (ULONG_PTR)Arguments;
1665 TrapFrame->EFlags = __readeflags() | EFLAGS_INTERRUPT_MASK;
1666 TrapFrame->SegCs = KGDT_R3_CODE | RPL_MASK;
1667 TrapFrame->Eip = SharedUserData->SystemCallReturn;
1668 TrapFrame->SegFs = KGDT_R3_TEB | RPL_MASK;
1669 __writeeflags(0x2);
1670
1671 /* Arguments are actually 2 frames down (because of the double indirection) */
1672 Arguments = (PVOID)(TrapFrame->HardwareEsp + 8);
1673
1674 /* Call the shared handler (inline) */
1675 KiSystemCall(TrapFrame, Arguments);
1676 }
1677
1678 /*
1679 * @implemented
1680 */
1681 VOID
1682 NTAPI
1683 Kei386EoiHelper(VOID)
1684 {
1685 /* We should never see this call happening */
1686 ERROR_FATAL("Mismatched NT/HAL version");
1687 }
1688
1689 /* EOF */