8 // Thread Dispatcher Header DebugActive Mask
10 #define DR_MASK(x) (1 << (x))
11 #define DR_REG_MASK 0x4F
14 // INT3 is 1 byte long
16 #define KD_BREAKPOINT_TYPE UCHAR
17 #define KD_BREAKPOINT_SIZE sizeof(UCHAR)
18 #define KD_BREAKPOINT_VALUE 0xCC
21 // Macros for getting and setting special purpose registers in portable code
23 #define KeGetContextPc(Context) \
26 #define KeSetContextPc(Context, ProgramCounter) \
27 ((Context)->Eip = (ProgramCounter))
29 #define KeGetTrapFramePc(TrapFrame) \
32 #define KiGetLinkedTrapFrame(x) \
33 (PKTRAP_FRAME)((x)->Edx)
35 #define KeGetContextReturnRegister(Context) \
38 #define KeSetContextReturnRegister(Context, ReturnValue) \
39 ((Context)->Eax = (ReturnValue))
42 // Macro to get trap and exception frame from a thread stack
44 #define KeGetTrapFrame(Thread) \
45 (PKTRAP_FRAME)((ULONG_PTR)((Thread)->InitialStack) - \
46 sizeof(KTRAP_FRAME) - \
49 #define KeGetExceptionFrame(Thread) \
53 // Macro to get context switches from the PRCB
54 // All architectures but x86 have it in the PRCB's KeContextSwitches
56 #define KeGetContextSwitches(Prcb) \
57 CONTAINING_RECORD(Prcb, KIPCR, PrcbData)->ContextSwitches
60 // Macro to get the second level cache size field name which differs between
61 // CISC and RISC architectures, as the former has unified I/D cache
63 #define KiGetSecondLevelDCacheSize() ((PKIPCR)KeGetPcr())->SecondLevelCacheSize
66 // Returns the Interrupt State from a Trap Frame.
67 // ON = TRUE, OFF = FALSE
69 #define KeGetTrapFrameInterruptState(TrapFrame) \
70 BooleanFlagOn((TrapFrame)->EFlags, EFLAGS_INTERRUPT_MASK)
73 // Flags for exiting a trap
75 #define KTE_SKIP_PM_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipPreviousMode = TRUE } }).Bits)
76 #define KTE_SKIP_SEG_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipSegments = TRUE } }).Bits)
77 #define KTE_SKIP_VOL_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipVolatiles = TRUE } }).Bits)
79 typedef union _KTRAP_EXIT_SKIP_BITS
83 UCHAR SkipPreviousMode
:1;
85 UCHAR SkipVolatiles
:1;
89 } KTRAP_EXIT_SKIP_BITS
, *PKTRAP_EXIT_SKIP_BITS
;
93 // Flags used by the VDM/V8086 emulation engine for determining instruction prefixes
95 #define PFX_FLAG_ES 0x00000100
96 #define PFX_FLAG_CS 0x00000200
97 #define PFX_FLAG_SS 0x00000400
98 #define PFX_FLAG_DS 0x00000800
99 #define PFX_FLAG_FS 0x00001000
100 #define PFX_FLAG_GS 0x00002000
101 #define PFX_FLAG_OPER32 0x00004000
102 #define PFX_FLAG_ADDR32 0x00008000
103 #define PFX_FLAG_LOCK 0x00010000
104 #define PFX_FLAG_REPNE 0x00020000
105 #define PFX_FLAG_REP 0x00040000
110 // All VDM/V8086 opcode emulators have the same FASTCALL function definition.
111 // We need to keep 2 parameters while the original ASM implementation uses 4:
112 // TrapFrame, PrefixFlags, Eip, InstructionSize;
114 // We pass the trap frame, and prefix flags, in our two parameters.
116 // We then realize that since the smallest prefix flag is 0x100, this gives us
117 // a count of up to 0xFF. So we OR in the instruction size with the prefix flags
119 // We further realize that we always have access to EIP from the trap frame, and
120 // that if we want the *current instruction* EIP, we simply have to add the
121 // instruction size *MINUS ONE*, and that gives us the EIP we should be looking
122 // at now, so we don't need to use the stack to push this parameter.
124 // We actually only care about the *current instruction* EIP in one location,
125 // so although it may be slightly more expensive to re-calculate the EIP one
126 // more time, this way we don't redefine ALL opcode handlers to have 3 parameters,
127 // which would be forcing stack usage in all other scenarios.
129 #define KiVdmSetVdmEFlags(x) InterlockedOr((PLONG)KiNtVdmState, (x));
130 #define KiVdmClearVdmEFlags(x) InterlockedAnd((PLONG)KiNtVdmState, ~(x))
131 #define KiCallVdmHandler(x) KiVdmOpcode##x(TrapFrame, Flags)
132 #define KiCallVdmPrefixHandler(x) KiVdmOpcodePrefix(TrapFrame, Flags | x)
133 #define KiVdmUnhandledOpcode(x) \
136 KiVdmOpcode##x(IN PKTRAP_FRAME TrapFrame, \
139 /* Not yet handled */ \
145 C_ASSERT(NPX_FRAME_LENGTH
== sizeof(FX_SAVE_AREA
));
150 typedef struct _KV86_FRAME
155 } KV86_FRAME
, *PKV86_FRAME
;
158 // Virtual Stack Frame
160 typedef struct _KV8086_STACK_FRAME
162 KTRAP_FRAME TrapFrame
;
163 FX_SAVE_AREA NpxArea
;
165 } KV8086_STACK_FRAME
, *PKV8086_STACK_FRAME
;
168 // Registers an interrupt handler with an IDT vector
172 KeRegisterInterruptHandler(IN ULONG Vector
,
177 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
180 // Get the entry from the HAL
182 Entry
= HalVectorToIDTEntry(Vector
);
183 Address
= PtrToUlong(Handler
);
188 Pcr
->IDT
[Entry
].ExtendedOffset
= (USHORT
)(Address
>> 16);
189 Pcr
->IDT
[Entry
].Offset
= (USHORT
)Address
;
193 // Returns the registered interrupt handler for a given IDT vector
197 KeQueryInterruptHandler(IN ULONG Vector
)
199 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
203 // Get the entry from the HAL
205 Entry
= HalVectorToIDTEntry(Vector
);
208 // Read the entry from the IDT
210 return (PVOID
)(((Pcr
->IDT
[Entry
].ExtendedOffset
<< 16) & 0xFFFF0000) |
211 (Pcr
->IDT
[Entry
].Offset
& 0xFFFF));
215 // Invalidates the TLB entry for a specified address
219 KeInvalidateTlbEntry(IN PVOID Address
)
221 /* Invalidate the TLB entry for this address */
227 KeFlushProcessTb(VOID
)
229 /* Flush the TLB by resetting CR3 */
230 __writecr3(__readcr3());
235 KeGetCurrentThread(VOID
)
237 /* Return the current thread */
238 return ((PKIPCR
)KeGetPcr())->PrcbData
.CurrentThread
;
243 KiRundownThread(IN PKTHREAD Thread
)
246 /* Check if this is the NPX Thread */
247 if (KeGetCurrentPrcb()->NpxThread
== Thread
)
250 KeGetCurrentPrcb()->NpxThread
= NULL
;
272 KiGetCacheInformation(VOID
);
282 KiIsNpxErrataPresent(
288 KiSetProcessorType(VOID
);
292 KiGetFeatureBits(VOID
);
296 KiThreadStartup(VOID
);
300 Ke386GetGdtEntryThread(
303 IN PKGDTENTRY Descriptor
309 IN FLOATING_SAVE_AREA
*SaveArea
315 IN PKTRAP_FRAME TrapFrame
320 Ki386SetupAndExitToV86Mode(
332 Ki386EnableGlobalPage(
333 IN
volatile ULONG_PTR Context
338 KiI386PentiumLockErrataFixup(
356 KiAmdK6InitializeMTRR(
362 KiRestoreFastSyscallReturnState(
380 Ki386EnableXMMIExceptions(
387 IN PKTRAP_FRAME TrapFrame
393 IN PKTRAP_FRAME TrapFrame
,
399 Ki386HandleOpcodeV86(
400 IN PKTRAP_FRAME TrapFrame
407 IN PKTRAP_FRAME TrapFrame
412 Ki386BiosCallReturnAddress(
413 IN PKTRAP_FRAME TrapFrame
419 IN PKTRAP_FRAME TrapFrame
425 KiDispatchExceptionFromTrapFrame(
427 IN ULONG_PTR Address
,
428 IN ULONG ParameterCount
,
429 IN ULONG_PTR Parameter1
,
430 IN ULONG_PTR Parameter2
,
431 IN ULONG_PTR Parameter3
,
432 IN PKTRAP_FRAME TrapFrame
436 // Global x86 only Kernel data
438 extern PVOID Ki386IopmSaveArea
;
439 extern ULONG KeI386EFlagsAndMaskV86
;
440 extern ULONG KeI386EFlagsOrMaskV86
;
441 extern BOOLEAN KeI386VirtualIntExtensions
;
442 extern KIDTENTRY KiIdt
[MAXIMUM_IDTVECTOR
];
443 extern KDESCRIPTOR KiIdtDescriptor
;
444 extern BOOLEAN KiI386PentiumLockErrataPresent
;
445 extern ULONG KeI386NpxPresent
;
446 extern ULONG KeI386XMMIPresent
;
447 extern ULONG KeI386FxsrPresent
;
448 extern ULONG KiMXCsrMask
;
449 extern ULONG KeI386CpuType
;
450 extern ULONG KeI386CpuStep
;
451 extern ULONG Ke386CacheAlignment
;
452 extern ULONG KiFastSystemCallDisable
;
453 extern UCHAR KiDebugRegisterTrapOffsets
[9];
454 extern UCHAR KiDebugRegisterContextOffsets
[9];
455 extern DECLSPEC_NORETURN VOID __cdecl
KiTrap02(VOID
);
456 extern VOID __cdecl
KiTrap08(VOID
);
457 extern VOID __cdecl
KiTrap13(VOID
);
458 extern VOID __cdecl
KiFastCallEntry(VOID
);
459 extern VOID NTAPI
ExpInterlockedPopEntrySListFault(VOID
);
460 extern VOID NTAPI
ExpInterlockedPopEntrySListResume(VOID
);
461 extern VOID __cdecl
CopyParams(VOID
);
462 extern VOID __cdecl
ReadBatch(VOID
);
463 extern VOID __cdecl
FrRestore(VOID
);
464 extern CHAR KiSystemCallExitBranch
[];
465 extern CHAR KiSystemCallExit
[];
466 extern CHAR KiSystemCallExit2
[];
471 #include "../trap_x.h"
474 // Returns a thread's FPU save area
478 KiGetThreadNpxArea(IN PKTHREAD Thread
)
480 return (PFX_SAVE_AREA
)((ULONG_PTR
)Thread
->InitialStack
- sizeof(FX_SAVE_AREA
));
484 // Sanitizes a selector
488 Ke386SanitizeSeg(IN ULONG Cs
,
489 IN KPROCESSOR_MODE Mode
)
492 // Check if we're in kernel-mode, and force CPL 0 if so.
493 // Otherwise, force CPL 3.
495 return ((Mode
== KernelMode
) ?
496 (Cs
& (0xFFFF & ~RPL_MASK
)) :
497 (RPL_MASK
| (Cs
& 0xFFFF)));
505 Ke386SanitizeFlags(IN ULONG Eflags
,
506 IN KPROCESSOR_MODE Mode
)
509 // Check if we're in kernel-mode, and sanitize EFLAGS if so.
510 // Otherwise, also force interrupt mask on.
512 return ((Mode
== KernelMode
) ?
513 (Eflags
& (EFLAGS_USER_SANITIZE
| EFLAGS_INTERRUPT_MASK
)) :
514 (EFLAGS_INTERRUPT_MASK
| (Eflags
& EFLAGS_USER_SANITIZE
)));
518 // Gets a DR register from a CONTEXT structure
522 KiDrFromContext(IN ULONG Dr
,
525 return *(PVOID
*)((ULONG_PTR
)Context
+ KiDebugRegisterContextOffsets
[Dr
]);
529 // Gets a DR register from a KTRAP_FRAME structure
533 KiDrFromTrapFrame(IN ULONG Dr
,
534 IN PKTRAP_FRAME TrapFrame
)
536 return (PVOID
*)((ULONG_PTR
)TrapFrame
+ KiDebugRegisterTrapOffsets
[Dr
]);
540 // Sanitizes a Debug Register
544 Ke386SanitizeDr(IN PVOID DrAddress
,
545 IN KPROCESSOR_MODE Mode
)
548 // Check if we're in kernel-mode, and return the address directly if so.
549 // Otherwise, make sure it's not inside the kernel-mode address space.
550 // If it is, then clear the address.
552 return ((Mode
== KernelMode
) ? DrAddress
:
553 (DrAddress
<= MM_HIGHEST_USER_ADDRESS
) ? DrAddress
: 0);
557 // Exception with no arguments
562 KiDispatchException0Args(IN NTSTATUS Code
,
563 IN ULONG_PTR Address
,
564 IN PKTRAP_FRAME TrapFrame
)
566 /* Helper for exceptions with no arguments */
567 KiDispatchExceptionFromTrapFrame(Code
, Address
, 0, 0, 0, 0, TrapFrame
);
571 // Exception with one argument
576 KiDispatchException1Args(IN NTSTATUS Code
,
577 IN ULONG_PTR Address
,
579 IN PKTRAP_FRAME TrapFrame
)
581 /* Helper for exceptions with no arguments */
582 KiDispatchExceptionFromTrapFrame(Code
, Address
, 1, P1
, 0, 0, TrapFrame
);
586 // Exception with two arguments
591 KiDispatchException2Args(IN NTSTATUS Code
,
592 IN ULONG_PTR Address
,
595 IN PKTRAP_FRAME TrapFrame
)
597 /* Helper for exceptions with no arguments */
598 KiDispatchExceptionFromTrapFrame(Code
, Address
, 2, P1
, P2
, 0, TrapFrame
);
602 // Performs a system call
606 * This sequence does a RtlCopyMemory(Stack - StackBytes, Arguments, StackBytes)
607 * and then calls the function associated with the system call.
609 * It's done in assembly for two reasons: we need to muck with the stack,
610 * and the call itself restores the stack back for us. The only way to do
611 * this in C is to do manual C handlers for every possible number of args on
612 * the stack, and then have the handler issue a call by pointer. This is
613 * wasteful since it'll basically push the values twice and require another
614 * level of call indirection.
616 * The ARM kernel currently does this, but it should probably be changed
617 * later to function like this as well.
623 KiSystemCallTrampoline(IN PVOID Handler
,
632 "movl %%esp, %%edi\n"
642 : "%esp", "%esi", "%edi"
646 #elif defined(_MSC_VER)
649 KiSystemCallTrampoline(IN PVOID Handler
,
664 /* Return with result in EAX */
667 #error Unknown Compiler
672 // Checks for pending APCs
676 KiCheckForApcDelivery(IN PKTRAP_FRAME TrapFrame
)
681 /* Check for V8086 or user-mode trap */
682 if ((TrapFrame
->EFlags
& EFLAGS_V86_MASK
) || (KiUserTrap(TrapFrame
)))
685 Thread
= KeGetCurrentThread();
688 /* Turn off the alerted state for kernel mode */
689 Thread
->Alerted
[KernelMode
] = FALSE
;
691 /* Are there pending user APCs? */
692 if (!Thread
->ApcState
.UserApcPending
) break;
694 /* Raise to APC level and enable interrupts */
695 OldIrql
= KfRaiseIrql(APC_LEVEL
);
699 KiDeliverApc(UserMode
, NULL
, TrapFrame
);
701 /* Restore IRQL and disable interrupts once again */
702 KfLowerIrql(OldIrql
);
709 // Converts a base thread to a GUI thread
714 KiConvertToGuiThread(VOID
)
720 * Converting to a GUI thread safely updates ESP in-place as well as the
721 * current Thread->TrapFrame and EBP when KeSwitchKernelStack is called.
723 * However, PsConvertToGuiThread "helpfully" restores EBP to the original
724 * caller's value, since it is considered a nonvolatile register. As such,
725 * as soon as we're back after the conversion and we try to store the result
726 * which will probably be in some stack variable (EBP-based), we'll crash as
727 * we are touching the de-allocated non-expanded stack.
729 * Thus we need a way to update our EBP before EBP is touched, and the only
730 * way to guarantee this is to do the call itself in assembly, use the EAX
731 * register to store the result, fixup EBP, and then let the C code continue
739 "call _PsConvertToGuiThread@0\n"
743 : "=r"(Result
), "=r"(StackFrame
)
745 : "%esp", "%ecx", "%edx", "memory"
749 #elif defined(_MSC_VER)
752 KiConvertToGuiThread(VOID
);
754 #error Unknown Compiler
758 // Switches from boot loader to initial kernel stack
762 KiSwitchToBootStack(IN ULONG_PTR InitialStack
)
764 /* We have to switch to a new stack before continuing kernel initialization */
771 "jmp _KiSystemStartupBootStack@0\n"
774 "i"(NPX_FRAME_LENGTH
+ KTRAP_FRAME_ALIGN
+ KTRAP_FRAME_LENGTH
),
775 "i"(CR0_EM
| CR0_TS
| CR0_MP
)
778 #elif defined(_MSC_VER)
779 VOID NTAPI
KiSystemStartupBootStack(VOID
);
782 mov esp
, InitialStack
783 sub esp
, (NPX_FRAME_LENGTH
+ KTRAP_FRAME_ALIGN
+ KTRAP_FRAME_LENGTH
)
784 push (CR0_EM
| CR0_TS
| CR0_MP
)
785 jmp KiSystemStartupBootStack
788 #error Unknown Compiler
793 // Emits the iret instruction for C code
800 #if defined(__GNUC__)
805 #elif defined(_MSC_VER)
811 #error Unsupported compiler
817 // Normally this is done by the HAL, but on x86 as an optimization, the kernel
818 // initiates the end by calling back into the HAL and exiting the trap here.
822 KiEndInterrupt(IN KIRQL Irql
,
823 IN PKTRAP_FRAME TrapFrame
)
825 /* Disable interrupts and end the interrupt */
827 HalEndSystemInterrupt(Irql
, TrapFrame
);
829 /* Exit the interrupt */
830 KiEoiHelper(TrapFrame
);
840 extern ULONGLONG BootCyclesEnd
, BootCycles
;
841 BootCyclesEnd
= __rdtsc();
842 DbgPrint("Boot took %I64d cycles!\n", BootCyclesEnd
- BootCycles
);
843 DbgPrint("Interrupts: %d System Calls: %d Context Switches: %d\n",
844 KeGetCurrentPrcb()->InterruptCount
,
845 KeGetCurrentPrcb()->KeSystemCalls
,
846 KeGetContextSwitches(KeGetCurrentPrcb()));
851 KiGetUserModeStackAddress(void)
853 return &(KeGetCurrentThread()->TrapFrame
->HardwareEsp
);