Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical usages of MethodRental Class?

According to MSDN MethodRental Class allows to change method body of dynamic modules. However because of its limitations I cannot think of practical usages for it. Google did not help me either.

Any ideas what the class can be used for?

like image 684
Giorgi Avatar asked May 17 '10 09:05

Giorgi


2 Answers

This is similar in spirit to ICorProfilerCallback::JITCompilationStarted when paired with ICorProfilerInfo::SetILFunctionBody, but with more constraints. The ICorProfiler* classes can be used to do runtime instrumentation for almost any managed method. There are profilers and debuggers that use these to collect information about a running process.

You could use MethodRental to instrument code for diagnostic purposes. Some examples:

  • Function enter/exit would give you an execution trace that you could use to derive profiling data from.
  • Instrumenting synchronization primitives can help you diagnose race conditions.
  • Instrumenting basic blocks can help you determine code coverage.

You could also use MethodRental to enhance the functionality of existing code. Aspect-oriented programming comes to mind. You could 'weave' in security, logging, or other cross-cutting design concerns into existing code. This would require some other facility (XML, a C# library) to express your aspects, however.

Finally, you could use MethodRental to "detour" existing code, i.e. intercept method calls to create a kind of runtime polymorphism. For example, if you have client code that uses some dynamically-generated class RegistryStore to get some configuration via GetConfig, you could rewrite the method's IL to change the implementation of RegistryStore.GetConfig to use the filesystem instead. You could do this without having to change the client code.

like image 164
Chris Schmich Avatar answered Oct 24 '22 11:10

Chris Schmich


Not sure what limitations you mean. Clearly this can only work on dynamically generated methods, produced by MethodBuilder. Class methods that were JIT compiled from IL loaded from an assembly cannot be replaced.

A use case would be implementing a runtime for a dynamic language that supports altering the methods of already defined classes (monkey patching). Languages like Ruby, Python, Javascript etc.

like image 38
Hans Passant Avatar answered Oct 24 '22 12:10

Hans Passant