Can we invoke a method from a class using IMetaDataImport2 in CLR profiling?

84 Views Asked by At

I'm using CLR profiling API to profile my .NET Core application.

In the method enter hook I can get the classID and metadata. Is there any way to invoke another function from that class using metadata?

E.g.: Consider the below example. In the class CommonStats When a method enter/exit hook invoked for the function ProcessRequestInternal, I need to invoke a function GetDefaultValue and save the return value.

public class CommonStats
    {
        String test = 
        private void ProcessRequestInternal(String str)
        {
           test = str;
        }
        protected override string GetDefaultValue()
        {
            if(test.StartsWith("/")) {
                return "SUCCESS";
            }
            return "FAILURE";
        }
    }
1

There are 1 best solutions below

0
Egozy On

In general, it is not recommended (and impossible through the Profiler API) to call managed code from your profiler. The way to do this is performing IL rewriting.

From https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/profiling-overview:

Although this is possible from a design perspective, the profiling API does not support managed components. A CLR profiler must be completely unmanaged. Attempts to combine managed and unmanaged code in a CLR profiler may cause access violations, program failure, or deadlocks. The managed components of the profiler will fire events back to their unmanaged components, which would subsequently call the managed components again, resulting in circular references.

The only location where a CLR profiler can call managed code safely is in the Microsoft intermediate language (MSIL) body of a method. The recommended practice for modifying the MSIL body is to use the JIT recompilation methods in the ICorProfilerCallback4 interface.

A good place to start with IL rewriting is http://www.debugthings.com/2015/09/16/rewriting-il-remotely-part1/. There is a lot of good information found in David's Broman blog, here: https://github.com/dotnet/coreclr/tree/master/Documentation/Profiling/davbr-blog-archive