Reputation: 10794
OK, say that my application is emitting (x86) instructions into memory, making the page executable, etc. Is there a 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 a way to:
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?
Upvotes: 7
Views: 1253
Reputation: 792
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.
Upvotes: 6
Reputation: 30790
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
Upvotes: 0
Reputation: 131112
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.
Upvotes: 0
Reputation: 116411
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.
Upvotes: 2