views:

400

answers:

5

Ok, say that my application is emitting (x86) instructions into memory, making the page executable, etc. Is there any way of altering the method stub of an un-JITted method to point to my emitted instruction stream?

E.g.:

Suppose I have created an x86 instruction stream in memory, which does something arbitrary. Now, further suppose that I have a method 'int Target()'. I haven't called it yet, so it hasn't been compiled. Is there any way to:

  1. Get the pointer to Target's stub
  2. Make it point to my emitted instruction stream.

I realise that practically every single security feature of .Net is designed to prevent hijacking like this. But is it possible through, say, the hosting API?

+7  A: 

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!

leppie
I recalled it had 'IL rewriting' somewhere.
leppie
Yeah. I was just about to say that. It looks like it's IL only.
TraumaPony
+1  A: 

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.

Brian Rasmussen
A: 

In addition to being able to use ICorProfiler and rewriting your method before it jits, you could use ICorDebug (MDBG has managed interfaced). Set a breakpoint, when the breakpoint hits set the next statement to your intercepting code. All of this process can be done from code but is really intrusive and you will need a "watcher" process to coordinate this.

Another thing worth looking at is the PostSharp project which gives you entry and exit methods if you apply attributes.

Sam Saffron
A: 

I wouldn't try and mess directly with the memory and I'm not sure it's even possible instead you can use the profiler API - there are a few examples out there but no real documentation. Have a look at MSDN magazine article - Rewrite MSIL Code on the Fly with the .NET Framework Profiling API

Dror Helper
+3  A: 

yes you can do!

Hook getJit method of mscorjit. And you will be asked everytime anymethod require Jitting. you can pass whatever you want. Some .net protectors works like this.

Kuldip Saini