1 #ifndef __NTOSKRNL_INCLUDE_INTERNAL_I386_KE_H
2 #define __NTOSKRNL_INCLUDE_INTERNAL_I386_KE_H
10 // Thread Dispatcher Header DebugActive Mask
12 #define DR_MASK(x) (1 << (x))
13 #define DR_REG_MASK 0x4F
15 #define IMAGE_FILE_MACHINE_ARCHITECTURE IMAGE_FILE_MACHINE_I386
18 // INT3 is 1 byte long
20 #define KD_BREAKPOINT_TYPE UCHAR
21 #define KD_BREAKPOINT_SIZE sizeof(UCHAR)
22 #define KD_BREAKPOINT_VALUE 0xCC
25 // Macros for getting and setting special purpose registers in portable code
27 #define KeGetContextPc(Context) \
30 #define KeSetContextPc(Context, ProgramCounter) \
31 ((Context)->Eip = (ProgramCounter))
33 #define KeGetTrapFramePc(TrapFrame) \
36 #define KiGetLinkedTrapFrame(x) \
37 (PKTRAP_FRAME)((x)->Edx)
39 #define KeGetContextReturnRegister(Context) \
42 #define KeSetContextReturnRegister(Context, ReturnValue) \
43 ((Context)->Eax = (ReturnValue))
46 // Macro to get trap and exception frame from a thread stack
48 #define KeGetTrapFrame(Thread) \
49 (PKTRAP_FRAME)((ULONG_PTR)((Thread)->InitialStack) - \
50 sizeof(KTRAP_FRAME) - \
53 #define KeGetExceptionFrame(Thread) \
57 // Macro to get context switches from the PRCB
58 // All architectures but x86 have it in the PRCB's KeContextSwitches
60 #define KeGetContextSwitches(Prcb) \
61 CONTAINING_RECORD(Prcb, KIPCR, PrcbData)->ContextSwitches
64 // Returns the Interrupt State from a Trap Frame.
65 // ON = TRUE, OFF = FALSE
67 #define KeGetTrapFrameInterruptState(TrapFrame) \
68 BooleanFlagOn((TrapFrame)->EFlags, EFLAGS_INTERRUPT_MASK)
71 // Flags for exiting a trap
73 #define KTE_SKIP_PM_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipPreviousMode = TRUE } }).Bits)
74 #define KTE_SKIP_SEG_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipSegments = TRUE } }).Bits)
75 #define KTE_SKIP_VOL_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipVolatiles = TRUE } }).Bits)
77 typedef union _KTRAP_EXIT_SKIP_BITS
81 UCHAR SkipPreviousMode
:1;
83 UCHAR SkipVolatiles
:1;
87 } KTRAP_EXIT_SKIP_BITS
, *PKTRAP_EXIT_SKIP_BITS
;
91 // Flags used by the VDM/V8086 emulation engine for determining instruction prefixes
93 #define PFX_FLAG_ES 0x00000100
94 #define PFX_FLAG_CS 0x00000200
95 #define PFX_FLAG_SS 0x00000400
96 #define PFX_FLAG_DS 0x00000800
97 #define PFX_FLAG_FS 0x00001000
98 #define PFX_FLAG_GS 0x00002000
99 #define PFX_FLAG_OPER32 0x00004000
100 #define PFX_FLAG_ADDR32 0x00008000
101 #define PFX_FLAG_LOCK 0x00010000
102 #define PFX_FLAG_REPNE 0x00020000
103 #define PFX_FLAG_REP 0x00040000
108 // All VDM/V8086 opcode emulators have the same FASTCALL function definition.
109 // We need to keep 2 parameters while the original ASM implementation uses 4:
110 // TrapFrame, PrefixFlags, Eip, InstructionSize;
112 // We pass the trap frame, and prefix flags, in our two parameters.
114 // We then realize that since the smallest prefix flag is 0x100, this gives us
115 // a count of up to 0xFF. So we OR in the instruction size with the prefix flags
117 // We further realize that we always have access to EIP from the trap frame, and
118 // that if we want the *current instruction* EIP, we simply have to add the
119 // instruction size *MINUS ONE*, and that gives us the EIP we should be looking
120 // at now, so we don't need to use the stack to push this parameter.
122 // We actually only care about the *current instruction* EIP in one location,
123 // so although it may be slightly more expensive to re-calculate the EIP one
124 // more time, this way we don't redefine ALL opcode handlers to have 3 parameters,
125 // which would be forcing stack usage in all other scenarios.
127 #define KiVdmSetVdmEFlags(x) InterlockedOr((PLONG)KiNtVdmState, (x));
128 #define KiVdmClearVdmEFlags(x) InterlockedAnd((PLONG)KiNtVdmState, ~(x))
129 #define KiCallVdmHandler(x) KiVdmOpcode##x(TrapFrame, Flags)
130 #define KiCallVdmPrefixHandler(x) KiVdmOpcodePrefix(TrapFrame, Flags | x)
131 #define KiVdmUnhandledOpcode(x) \
134 KiVdmOpcode##x(IN PKTRAP_FRAME TrapFrame, \
137 /* Not yet handled */ \
143 C_ASSERT(NPX_FRAME_LENGTH
== sizeof(FX_SAVE_AREA
));
148 typedef struct _KV86_FRAME
153 } KV86_FRAME
, *PKV86_FRAME
;
156 // Virtual Stack Frame
158 typedef struct _KV8086_STACK_FRAME
160 KTRAP_FRAME TrapFrame
;
161 FX_SAVE_AREA NpxArea
;
163 } KV8086_STACK_FRAME
, *PKV8086_STACK_FRAME
;
166 // Registers an interrupt handler with an IDT vector
170 KeRegisterInterruptHandler(IN ULONG Vector
,
175 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
178 // Get the entry from the HAL
180 Entry
= HalVectorToIDTEntry(Vector
);
181 Address
= PtrToUlong(Handler
);
186 Pcr
->IDT
[Entry
].ExtendedOffset
= (USHORT
)(Address
>> 16);
187 Pcr
->IDT
[Entry
].Offset
= (USHORT
)Address
;
191 // Returns the registered interrupt handler for a given IDT vector
195 KeQueryInterruptHandler(IN ULONG Vector
)
197 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
201 // Get the entry from the HAL
203 Entry
= HalVectorToIDTEntry(Vector
);
206 // Read the entry from the IDT
208 return (PVOID
)(((Pcr
->IDT
[Entry
].ExtendedOffset
<< 16) & 0xFFFF0000) |
209 (Pcr
->IDT
[Entry
].Offset
& 0xFFFF));
213 // Invalidates the TLB entry for a specified address
217 KeInvalidateTlbEntry(IN PVOID Address
)
219 /* Invalidate the TLB entry for this address */
225 KeFlushProcessTb(VOID
)
227 /* Flush the TLB by resetting CR3 */
228 __writecr3(__readcr3());
233 KeGetCurrentThread(VOID
)
235 /* Return the current thread */
236 return ((PKIPCR
)KeGetPcr())->PrcbData
.CurrentThread
;
241 KiRundownThread(IN PKTHREAD Thread
)
244 /* Check if this is the NPX Thread */
245 if (KeGetCurrentPrcb()->NpxThread
== Thread
)
248 KeGetCurrentPrcb()->NpxThread
= NULL
;
270 KiGetCacheInformation(VOID
);
280 KiIsNpxErrataPresent(
286 KiSetProcessorType(VOID
);
290 KiGetFeatureBits(VOID
);
294 KiThreadStartup(VOID
);
298 Ke386GetGdtEntryThread(
301 IN PKGDTENTRY Descriptor
307 IN FLOATING_SAVE_AREA
*SaveArea
313 IN PKTRAP_FRAME TrapFrame
318 Ki386SetupAndExitToV86Mode(
330 Ki386EnableGlobalPage(
331 IN
volatile ULONG_PTR Context
336 KiI386PentiumLockErrataFixup(
354 KiAmdK6InitializeMTRR(
360 KiRestoreFastSyscallReturnState(
378 Ki386EnableXMMIExceptions(
385 IN PKTRAP_FRAME TrapFrame
391 IN PKTRAP_FRAME TrapFrame
,
397 Ki386HandleOpcodeV86(
398 IN PKTRAP_FRAME TrapFrame
405 IN PKTRAP_FRAME TrapFrame
410 Ki386BiosCallReturnAddress(
411 IN PKTRAP_FRAME TrapFrame
417 IN PKTRAP_FRAME TrapFrame
423 KiDispatchExceptionFromTrapFrame(
425 IN ULONG_PTR Address
,
426 IN ULONG ParameterCount
,
427 IN ULONG_PTR Parameter1
,
428 IN ULONG_PTR Parameter2
,
429 IN ULONG_PTR Parameter3
,
430 IN PKTRAP_FRAME TrapFrame
434 // Global x86 only Kernel data
436 extern PVOID Ki386IopmSaveArea
;
437 extern ULONG KeI386EFlagsAndMaskV86
;
438 extern ULONG KeI386EFlagsOrMaskV86
;
439 extern BOOLEAN KeI386VirtualIntExtensions
;
440 extern KIDTENTRY KiIdt
[MAXIMUM_IDTVECTOR
];
441 extern KDESCRIPTOR KiIdtDescriptor
;
442 extern ULONG Ke386GlobalPagesEnabled
;
443 extern BOOLEAN KiI386PentiumLockErrataPresent
;
444 extern ULONG KeI386NpxPresent
;
445 extern ULONG KeI386XMMIPresent
;
446 extern ULONG KeI386FxsrPresent
;
447 extern ULONG KiMXCsrMask
;
448 extern ULONG KeI386CpuType
;
449 extern ULONG KeI386CpuStep
;
450 extern ULONG Ke386CacheAlignment
;
451 extern ULONG KiFastSystemCallDisable
;
452 extern UCHAR KiDebugRegisterTrapOffsets
[9];
453 extern UCHAR KiDebugRegisterContextOffsets
[9];
454 extern VOID __cdecl
KiTrap02(VOID
);
455 extern VOID __cdecl
KiTrap08(VOID
);
456 extern VOID __cdecl
KiTrap13(VOID
);
457 extern VOID __cdecl
KiFastCallEntry(VOID
);
458 extern VOID NTAPI
ExpInterlockedPopEntrySListFault(VOID
);
459 extern VOID __cdecl
CopyParams(VOID
);
460 extern VOID __cdecl
ReadBatch(VOID
);
461 extern VOID __cdecl
FrRestore(VOID
);
462 extern CHAR KiSystemCallExitBranch
[];
463 extern CHAR KiSystemCallExit
[];
464 extern CHAR KiSystemCallExit2
[];
469 #include "../trap_x.h"
472 // Returns a thread's FPU save area
476 KiGetThreadNpxArea(IN PKTHREAD Thread
)
478 return (PFX_SAVE_AREA
)((ULONG_PTR
)Thread
->InitialStack
- sizeof(FX_SAVE_AREA
));
482 // Sanitizes a selector
486 Ke386SanitizeSeg(IN ULONG Cs
,
487 IN KPROCESSOR_MODE Mode
)
490 // Check if we're in kernel-mode, and force CPL 0 if so.
491 // Otherwise, force CPL 3.
493 return ((Mode
== KernelMode
) ?
494 (Cs
& (0xFFFF & ~RPL_MASK
)) :
495 (RPL_MASK
| (Cs
& 0xFFFF)));
503 Ke386SanitizeFlags(IN ULONG Eflags
,
504 IN KPROCESSOR_MODE Mode
)
507 // Check if we're in kernel-mode, and sanitize EFLAGS if so.
508 // Otherwise, also force interrupt mask on.
510 return ((Mode
== KernelMode
) ?
511 (Eflags
& (EFLAGS_USER_SANITIZE
| EFLAGS_INTERRUPT_MASK
)) :
512 (EFLAGS_INTERRUPT_MASK
| (Eflags
& EFLAGS_USER_SANITIZE
)));
516 // Gets a DR register from a CONTEXT structure
520 KiDrFromContext(IN ULONG Dr
,
523 return *(PVOID
*)((ULONG_PTR
)Context
+ KiDebugRegisterContextOffsets
[Dr
]);
527 // Gets a DR register from a KTRAP_FRAME structure
531 KiDrFromTrapFrame(IN ULONG Dr
,
532 IN PKTRAP_FRAME TrapFrame
)
534 return (PVOID
*)((ULONG_PTR
)TrapFrame
+ KiDebugRegisterTrapOffsets
[Dr
]);
538 // Sanitizes a Debug Register
542 Ke386SanitizeDr(IN PVOID DrAddress
,
543 IN KPROCESSOR_MODE Mode
)
546 // Check if we're in kernel-mode, and return the address directly if so.
547 // Otherwise, make sure it's not inside the kernel-mode address space.
548 // If it is, then clear the address.
550 return ((Mode
== KernelMode
) ? DrAddress
:
551 (DrAddress
<= MM_HIGHEST_USER_ADDRESS
) ? DrAddress
: 0);
555 // Exception with no arguments
560 KiDispatchException0Args(IN NTSTATUS Code
,
561 IN ULONG_PTR Address
,
562 IN PKTRAP_FRAME TrapFrame
)
564 /* Helper for exceptions with no arguments */
565 KiDispatchExceptionFromTrapFrame(Code
, Address
, 0, 0, 0, 0, TrapFrame
);
569 // Exception with one argument
574 KiDispatchException1Args(IN NTSTATUS Code
,
575 IN ULONG_PTR Address
,
577 IN PKTRAP_FRAME TrapFrame
)
579 /* Helper for exceptions with no arguments */
580 KiDispatchExceptionFromTrapFrame(Code
, Address
, 1, P1
, 0, 0, TrapFrame
);
584 // Exception with two arguments
589 KiDispatchException2Args(IN NTSTATUS Code
,
590 IN ULONG_PTR Address
,
593 IN PKTRAP_FRAME TrapFrame
)
595 /* Helper for exceptions with no arguments */
596 KiDispatchExceptionFromTrapFrame(Code
, Address
, 2, P1
, P2
, 0, TrapFrame
);
600 // Performs a system call
604 KiSystemCallTrampoline(IN PVOID Handler
,
611 * This sequence does a RtlCopyMemory(Stack - StackBytes, Arguments, StackBytes)
612 * and then calls the function associated with the system call.
614 * It's done in assembly for two reasons: we need to muck with the stack,
615 * and the call itself restores the stack back for us. The only way to do
616 * this in C is to do manual C handlers for every possible number of args on
617 * the stack, and then have the handler issue a call by pointer. This is
618 * wasteful since it'll basically push the values twice and require another
619 * level of call indirection.
621 * The ARM kernel currently does this, but it should probably be changed
622 * later to function like this as well.
628 "movl %%esp, %%edi\n"
638 : "%esp", "%esi", "%edi"
645 // Checks for pending APCs
649 KiCheckForApcDelivery(IN PKTRAP_FRAME TrapFrame
)
654 /* Check for V8086 or user-mode trap */
655 if ((TrapFrame
->EFlags
& EFLAGS_V86_MASK
) || (KiUserTrap(TrapFrame
)))
658 Thread
= KeGetCurrentThread();
661 /* Turn off the alerted state for kernel mode */
662 Thread
->Alerted
[KernelMode
] = FALSE
;
664 /* Are there pending user APCs? */
665 if (!Thread
->ApcState
.UserApcPending
) break;
667 /* Raise to APC level and enable interrupts */
668 OldIrql
= KfRaiseIrql(APC_LEVEL
);
672 KiDeliverApc(UserMode
, NULL
, TrapFrame
);
674 /* Restore IRQL and disable interrupts once again */
675 KfLowerIrql(OldIrql
);
682 // Converts a base thread to a GUI thread
686 KiConvertToGuiThread(VOID
)
692 * Converting to a GUI thread safely updates ESP in-place as well as the
693 * current Thread->TrapFrame and EBP when KeSwitchKernelStack is called.
695 * However, PsConvertToGuiThread "helpfully" restores EBP to the original
696 * caller's value, since it is considered a nonvolatile register. As such,
697 * as soon as we're back after the conversion and we try to store the result
698 * which will probably be in some stack variable (EBP-based), we'll crash as
699 * we are touching the de-allocated non-expanded stack.
701 * Thus we need a way to update our EBP before EBP is touched, and the only
702 * way to guarantee this is to do the call itself in assembly, use the EAX
703 * register to store the result, fixup EBP, and then let the C code continue
711 "call _PsConvertToGuiThread@0\n"
715 : "=r"(Result
), "=r"(StackFrame
)
717 : "%esp", "%ecx", "%edx"
724 // Switches from boot loader to initial kernel stack
728 KiSwitchToBootStack(IN ULONG_PTR InitialStack
)
730 /* We have to switch to a new stack before continuing kernel initialization */
736 "jmp _KiSystemStartupBootStack@0\n"
739 "i"(NPX_FRAME_LENGTH
+ KTRAP_FRAME_ALIGN
+ KTRAP_FRAME_LENGTH
),
740 "i"(CR0_EM
| CR0_TS
| CR0_MP
)
746 // Normally this is done by the HAL, but on x86 as an optimization, the kernel
747 // initiates the end by calling back into the HAL and exiting the trap here.
751 KiEndInterrupt(IN KIRQL Irql
,
752 IN PKTRAP_FRAME TrapFrame
)
754 /* Disable interrupts and end the interrupt */
756 HalEndSystemInterrupt(Irql
, TrapFrame
);
758 /* Exit the interrupt */
759 KiEoiHelper(TrapFrame
);
769 extern ULONGLONG BootCyclesEnd
, BootCycles
;
770 BootCyclesEnd
= __rdtsc();
771 DbgPrint("Boot took %I64d cycles!\n", BootCyclesEnd
- BootCycles
);
772 DbgPrint("Interrupts: %d System Calls: %d Context Switches: %d\n",
773 KeGetCurrentPrcb()->InterruptCount
,
774 KeGetCurrentPrcb()->KeSystemCalls
,
775 KeGetContextSwitches(KeGetCurrentPrcb()));
779 #endif /* __NTOSKRNL_INCLUDE_INTERNAL_I386_KE_H */