Terminating a process from its own thread causes KERNEL_APC_PENDING_DURING_EXIT

I want to terminate a process when i am already in the context of a thread of that process. The below scenarios reflect this:

  • Terminating parent process from CreateProcessNotification routine using ZwOpenProcess() and ZwTerminateProcess().
  • Terminating current process from Image load notification routine using ZwOpenProcess() and ZwTerminateProcess().

I checked the threads’s KernelApcDisable and its -1. Who disables the APC ? System?
In both the above scenarios i am hit with KERNEL_APC_PENDING_DURING_EXIT and arguments :
Arguments:
Arg1: 00000000, The address of the APC found pending during exit.
Arg2: 0000ffff, The thread’s APC disable count
Arg3: 00000000, The current IRQL
Arg4: 00000001

Why does this happen and How can I terminate the process in each scenario?

Well, CreateProcessNotify is called with normal kernel APCs disabled. For the docs for the callback function:

The operating system calls the driver’s process-notify routine at PASSIVE_LEVEL inside a critical region with normal kernel APCs disabled.

If you don’t want to allow the process to start, use CreateProcessNotifyEx and just set the Status member of the PS_CREATE_NOTIFY_INFO structure to a non-success value and that’ll prevent the process from starting. Done!

Peter

@“Peter_Viscarola_(OSR)” said:
Well, CreateProcessNotify is called with normal kernel APCs disabled. For the docs for the callback function:

The operating system calls the driver’s process-notify routine at PASSIVE_LEVEL inside a critical region with normal kernel APCs disabled.

If you don’t want to allow the process to start, use CreateProcessNotifyEx and just set the Status member of the PS_CREATE_NOTIFY_INFO structure to a non-success value and that’ll prevent the process from starting. Done!

Peter

That would help terminating(rather not allowing creation) of process in whose create routine i am. What if i want to terminate the parent? The process create routine is in the context of parent process, hence hitting the wall of not able to terminate if apc is disabled. Also what if i want to terminate the process from LoadImageNotification routine?

What if i want to terminate the parent? The process create routine is in the context of parent process, hence hitting the wall
of not able to terminate if apc is disabled.

Probably, from the userland helper, rather than from the kernel-mode driver? Just a thought…

Anton Bassov