Is there a way to trick the .NET JIT compiler into running another method?

This is possible via the Profiling API. I have never used it, but it is used for a similar purpose in TypeMock.

Edit: I think there was a nice posting on the MSDN blogs, will go hunt for it.

Edit 2: Doh, first hit!


Yes, you can do it!

Hook the getJit method of mscorjit. And you will be asked every time if any method require jitting. You can pass whatever you want.

Some .NET protectors works like this.


As you say this is not easy and it may not even be possible. If I remember correctly the code will include the address of the JIT compiler for a method, that hasn't been compiled. So when you try to call this method, the JIT compiler will do its job and insert the address to the newly compiled method. If you can change this address, you may be able to insert a call to your own code. How you would do this undetected is beyond me. I certainly hope the CLR will detect this kind of tampering.

I don't think the Profiling API will help you in this case (as suggested by Leppie), as you're not trying to modify MSIL. If you think otherwise this article may be of use as it describes what you must do to implement what TypeMock is doing.