Saturday, July 21, 2012

Calling User code from Windows Kernel Mode

Code running in kernel mode in theory has unrestricted access to the whole address psace and so it could invoke code running in user mode.  However, doing so requires first picking a thread to run the code in, transitioning the CPU mode back to user mode, and setting up the user-mode context of the thread to reflect the call parameters.  Fortunately, calling user mode code is typically only required by OS itself and for driver, only in the context of a device IOCTL initiated by a user-mode thread.

A standard way for system execute code in the context of a given user-mode thread is to send an asynchronous procedure call (APC) to that thread.  This is how thread suspension works in Windows: the kernel simply sends an APC to the target thread and asks it to execute a function to wait on its internal thread semaphore object, causing it to beconme suspended.  APC also used in many other scenarios such as I/O completion and thread pool callback routines.

No comments: