Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Mono.Cecil modify code already loaded in the AppDomain?

I want to add some behavior to a certain class at runtime. I know how to subclass at runtime using Reflection.Emit but that's not enough. Depending on some external configuration I need to inject opcodes in a method on a type T so all classes that inherit from it automatically gain this behavior. (I can't use the .NET Profiling API).

Can something like this be done with Mono.Cecil?

If it isn't possible to modify code on a loaded assembly, it is fine If I can make the modifications before the assembly is loaded and then load the modified assembly in memory, but I don't know how I can control assembly loading.

like image 789
Thiago Padilha Avatar asked May 02 '10 20:05

Thiago Padilha


2 Answers

Nope, Cecil can not modify a loaded assembly. You have to instrument assemblies before they are actually loaded.

You don't have much control over how assemblies are resolved. You can hook into AppDomain.AssemblyResolve if you hide the assemblies in a private folder of yours, and instrument then before loading them.

like image 193
Jb Evain Avatar answered Nov 04 '22 01:11

Jb Evain


As JB Says above- You can create a Resolve Event handler - which would be like PSeudoHooking. And before the assembly is loaded, you make your changes, and then once the changes are done, the Resolve Assembly then continues on to load the changed assembly.

I use this method for resolving Embedded Dll's from Memory Streams.

like image 1
J Rolleston Avatar answered Nov 04 '22 01:11

J Rolleston