https://git.reactos.org/?p=reactos.git;a=commitdiff;h=90a0e426ed7ab13331277…
commit 90a0e426ed7ab133312773f03fda77b19a8327f0
Author:     Timo Kreuzer <timo.kreuzer(a)reactos.org>
AuthorDate: Mon Mar 9 07:01:05 2020 +0100
Commit:     Timo Kreuzer <timo.kreuzer(a)reactos.org>
CommitDate: Fri May 28 11:52:42 2021 +0200
    [NTOS:KE] Add IRQL checks and fix KiInitiateUserApc
---
 ntoskrnl/ke/amd64/trap.S      | 33 +++++++++++++++++++++++++++++++++
 sdk/include/asm/trapamd64.inc | 17 +++++++++++++++++
 2 files changed, 50 insertions(+)
diff --git a/ntoskrnl/ke/amd64/trap.S b/ntoskrnl/ke/amd64/trap.S
index fffcc5d1b31..5d6e1ead384 100644
--- a/ntoskrnl/ke/amd64/trap.S
+++ b/ntoskrnl/ke/amd64/trap.S
@@ -782,6 +782,14 @@ PUBLIC KiSystemCallEntry64
     mov ds, ax
     mov es, ax
+#if DBG
+    /* Check IRQL */
+    mov rax, cr8
+    test eax, eax
+    jz KiSystemCall64Again
+    int HEX(2C)
+#endif
+
 GLOBAL_LABEL KiSystemCall64Again
     /* Call the C-handler (will enable interrupts) */
@@ -875,6 +883,27 @@ PUBLIC KiServiceExit2
 .PROC KiServiceExit2
     .ENDPROLOG
+#if DBG
+    /* Get the current IRQL and compare it to the trap frame */
+    mov rax, cr8
+    cmp byte ptr [rcx + KTRAP_FRAME_PreviousIrql], al
+    je KiServiceExit2_ok1
+    int HEX(2C)
+
+KiServiceExit2_ok1:
+    /* Check if this is a user mode exit */
+    mov ah, byte ptr [rcx + KTRAP_FRAME_SegCs]
+    test ah, 1
+    jz KiServiceExit2_kernel
+
+    /* Validate that we are at PASSIVE_LEVEL */
+    test al, al
+    jz KiServiceExit2_kernel
+    int HEX(2C)
+
+KiServiceExit2_kernel:
+#endif
+
     mov rbp, rcx
     mov rsp, rcx
@@ -1055,6 +1084,10 @@ PUBLIC KiInitiateUserApc
     /* Disable interrupts again */
     cli
+    /* Go back to PASSIVE_LEVEL */
+    mov rax, PASSIVE_LEVEL
+    mov cr8, rax
+
     /* Restore the registers from the KEXCEPTION_FRAME */
     RESTORE_EXCEPTION_STATE
diff --git a/sdk/include/asm/trapamd64.inc b/sdk/include/asm/trapamd64.inc
index a4c1b844625..eeb804ec970 100644
--- a/sdk/include/asm/trapamd64.inc
+++ b/sdk/include/asm/trapamd64.inc
@@ -116,6 +116,14 @@ MACRO(EnterTrap, Flags)
     mov es, ax
     swapgs
+#if DBG
+    /* Check IRQL */
+    mov rax, cr8
+    test rax, rax
+    jz kernel_mode_entry
+    int HEX(2c)
+#endif
+
 kernel_mode_entry:
 //    if (Flags AND TF_IRQL)
@@ -151,6 +159,7 @@ MACRO(ExitTrap, Flags)
     LOCAL kernel_mode_return
     LOCAL IntsEnabled
     LOCAL NoUserApc
+    LOCAL IrqlPassive
 #if DBG
         /* Check previous irql */
@@ -201,6 +210,14 @@ MACRO(ExitTrap, Flags)
     jnz IntsEnabled
     int HEX(2c)
 IntsEnabled:
+
+    /* Make sure we are at passive level */
+    mov rax, cr8
+    test rax, rax
+    jz IrqlPassive
+    int HEX(2C)
+
+IrqlPassive:
 #endif
     cli