Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the code injection in the .net (as programming skill)?

In most common sense of course "it is a method to influence the behavior of a program in a way its authors did not intend" (wiki).

Then all reflection and typebuilder using techniques also can be named with "code injection" but nobody do this.

When I was always thinking that "code injection" is something about "runtime": like starting thread in another process to get some interesting data, I have surprised how Reflexil understands this: "convert C# instructions into IL on 'desing time', save edited assembly and replace old assembly with new" (10% that I miss something).

So now I'm interesting what techniques in the .NET are named with "code injection" term?

BTW. I'm interesting to know: is it possible to replace a "pointer to the virtual method" in the "virtual method table" of very-very private, several times nested, system class, with pointer to my own method at run time. Pure code injection from my understanding.

like image 971
Roman Pokrovskij Avatar asked Nov 30 '25 17:11

Roman Pokrovskij


2 Answers

Code injection in .NET is quite difficult. Mostly because code doesn't exist until the last possible moment. A fraction of a second before it starts executing, generated by the JIT compiler.

Practical approaches uses IL rewriting, common in AOP for example. This happens off-line, before the program even starts to execute. This isn't really 'injection' anymore, you physically change the program on disk.

There is an inline IL rewriting technique, it uses the unmanaged profiler interfaces. Pretty impractical, a magazine article that documents the approach is available here. It is quite dated, the profiler API has changed quite a bit since then. Never heard of a tool that uses this.

like image 108
Hans Passant Avatar answered Dec 02 '25 11:12

Hans Passant


Aspect-Oriented Programming (AOP) uses code injection to intercept method calls.

like image 34
Robert Harvey Avatar answered Dec 02 '25 10:12

Robert Harvey