.NET Inside Out Part 27 – Rerouting a running thread to some other method

This is the twentieth seventh part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

Today we are going to grab an existing running thread and make it run some other code.

Let’s take this:

We have a thread which executes some infinite loop. We’d like to make it jump out of that loop and do something else. How can we do that?

The trick is to modify its instruction pointer register. We can’t do it from the same process directly as we need to debug it so we’ll use CDB for that. Obviously, this can be done manually if needed:

How does it work? We first run CDB and dump threads to get the native thread id from the output of the !threads command. There are other ways to do so but this one is the most reliable.

Next, we run CDB again. This time it switches to thread, modifies its rip register and then exists.

The problem with this approach is that once we modify the thread it becomes unreliable. We don’t know if the stack is correct or whether we can safely exit the method. Ideally, we’d like to kill the thread. We’ll discuss this aspect in some later part.