How to monitor context switch in windows 7?

1.2k Views Asked by At

How can I monitor process/thread context switch using either kernel driver or API hooking in windows 7 ? I want to log the register values when a process (for e.g., internet explorer) goes into the resume/suspend state at the time of context switch.

1

There are 1 best solutions below

2
Χpẘ On

The answer somewhat depends on what you want to accomplish and what restrictions you have.

I think you first need to narrow the scope somewhat over what the OP says. In particular "resume/suspend" aren't well enough defined to know what you want. In fact Windows doesn't have a "suspend process" API. Procmon suspends processes by suspending all the threads in a process.

I suspect you mean when a process switch occurs. A process switch doesn't occur without a thread switch. So what you may want to know is when a thread owned by process X is switched to a thread owned by IE (to use your example), and when a thread owned by IE is switched to a thread owned by some other process.

The simplest way I can think of is to use a kernel debugger (Windbg, KD) and set a breakpoint on the kernel function that switches threads. I don't remember what that function is offhand but you could disassemble any number of kernel APIs (eg WaitForSingleEvent) to see what they do when they need to block. They have to pass control to the thread dispatcher. Or simpler maybe, just look at at the stack dump of all the threads in the system process (get help on !process to see the option). Many of them will be in the dispatcher.

If you want to log thread switches you could write some debugger functions to 1) check if a process switch into/out of IE occurred 2) to log the data some how. However using the debugger won't be practical if you want to capture all the thread switches in an IE session. It would be far too slow.

Another possibility is Event Tracing for Windows (ETW). ETW is a big topic, so google for it. Look specifically for tracing of kernel of events: 1) how to turn on ETW for kernel dispatch events 2) how to capture the events to a file and 3) how to view/process the events in the file. You may have to write a program to postprocess the events to extract the ones you're interested in.

Finally you could google for Windows Kernel Hooking or similar. Microsoft has made hooking kernel APIs harder in later versions of windows - I don't know exactly what they did in Win7 versus Vista versus Win8, but you'll need to keep that in mind as your google. I do recall some kernel hooking activities coming out of Microsoft Research a number of years ago.

If you do find APIs to hook kernel APIs you'll be in for some driver development, unless you can also find a framework that lets you control everything from user mode.

You may have better results asking this on a site devoted to driver development, kernel hacking, etc. I know OSR has a pretty good set of resources, including message boards.

Good luck.