A basic proxy for intercepting method calls (Part –2)

In my previous post , i introduced a basic proxy that intercepts methods. But what is missing in the proxy is that it does not consider method arguments and can not handle return types. In this post, i will enhance the proxy to support exactly those.

First of all, i modified the IIntercept.Intercept() to accept IInvocaiton interface. The interface is pretty simple and it consists of an arguments array and a method that will be used to set the return value from interceptor.

  1. /// <summary>
  2.     /// Contains Invocation details.
  3.     /// </summary>
  4.     public interface IInvocation
  5.     {
  6.         /// <summary>
  7.         /// Gets the invocation arguments.
  8.         /// </summary>
  9.         object[] Arguments { get; }
  10.         /// <summary>
  11.         /// Sets the return value.
  12.         /// </summary>
  13.         /// <param name="value"></param>
  14.         void SetReturn(object value);
  15.     }

 

Internally, the interface is implemented with a class named MethodInovcation , where the arguments  and return type is passed through the constructor. As, arguments will be passed dynamically during method call, I first declared a  LocalBuilder that will actually take the arguments and wrap it around an array of objects which will be then passed to the constructor. Therefore, i created an extension method that will emit the necessary IL from method’s argument types.

 

  1. LocalBuilder args = ilGenerator.DeclareLocal(typeof(object[]));
  2.  
  3. ilGenerator.Emit(OpCodes.Ldc_I4_S, parameterTypes.Length);
  4. ilGenerator.Emit(OpCodes.Newarr, typeof(object));
  5. ilGenerator.Emit(OpCodes.Stloc, args);
  6.  
  7. if (parameterTypes.Length > 0)
  8. {
  9.     ilGenerator.Emit(OpCodes.Ldloc, args);
  10.  
  11.     for (int index = 0; index < parameterTypes.Length; index++)
  12.     {
  13.         ilGenerator.Emit(OpCodes.Ldc_I4_S, index);
  14.         ilGenerator.Emit(OpCodes.Ldarg, index + 1);
  15.  
  16.         Type parameterType = parameterTypes[index];
  17.  
  18.         if (parameterType.IsValueType || parameterType.IsGenericParameter)
  19.             ilGenerator.Emit(OpCodes.Box, parameterType);
  20.  
  21.         ilGenerator.Emit(OpCodes.Stelem_Ref);
  22.         ilGenerator.Emit(OpCodes.Ldloc, args);
  23.     }
  24.  
  25.     ilGenerator.Emit(OpCodes.Stloc, args);
  26. }
   

The OpCodes.NewArray instruction declares an array from the target with the length pushed on the top of evaluation(EV) stack. The most interesting part in this code is how  to take an argument and assign that to our array . OpCodes.Stelem_Ref actually assigns the value from the top of evaluation stack to the index that is mentioned through Opcodes.Ldc_I4_S where OpCodes.Larg [ 1 .. n ] pushes the argument to the top of EV stack.Outside the declaring of LocalBuilder through extension looks like:

  1. LocalBuilder locParameters = ilGenerator.DeclareParameters(paramTypes);

Here, we also need to declare a variable that will contain the instance of MethodInvocation

  1. LocalBuilder locMethodInvocation = ilGenerator.DeclareLocal(typeof (MethodInvocation));

Just before Intereptor.Intercept() is called (Let’s assume it from previous post), the following code is added.

  1. ilGenerator.Emit(OpCodes.Ldloc, locParameters);
  2. ilGenerator.Emit(OpCodes.Ldtoken, methodInfo.ReturnType);
  3. ilGenerator.EmitCall(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle"), null);
  4. ilGenerator.Emit(OpCodes.Newobj, typeof(MethodInvocation).GetConstructor( new []
  5. {
  6.   typeof(object[]), typeof(Type)
  7. }));
  8. ilGenerator.Emit(OpCodes.Stloc, locMethodInvocation);
  9. ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);

 

Another interesting part is how we dynamically pass the method’s return value from interceptor. OpCodes.Ldtoken loads the type’s token from which by calling GetTypeFromHandle  the type is resolved in runtime and passed to the constructor.If you ever used an IL dissembler to look under the hood, you find it pretty common. Once, the extra lines are added to existing basic proxy , its time to check if things are doing just fine. To simplify, method will be called with an integer which will be returned by the interceptor.

  1. var proxy = new Proxy(typeof(TestClass));
  2.             var test = (TestClass) proxy.Create(new BasicInterceptor());
  3.  
  4.             int result = test.TestCall(1);
  5.  
  6.             if (result != 1)
  7.                 throw new Exception("result should equal 1");

Thus, the existing basic interceptor will covert into following :

  1. public class BasicInterceptor : IInterceptor
  2.     {
  3.         public void Intercept(IInvocation invocation)
  4.         {
  5.             System.Console.WriteLine("Intercepted");
  6.  
  7.             invocation.SetReturn(invocation.Arguments[0]);
  8.         }
  9.     }

We are setting the return from the argument that is passed in. As previously the MethodInvocation is assigned to a local variable,after the interception the value is get and unboxed(value type/enum should be unboxed from object).

  1. if (methodInfo.ReturnType != typeof(void))
  2. {
  3.     ilGenerator.Emit(OpCodes.Ldloc, locMethodInvocation);
  4.     ilGenerator.Emit(OpCodes.Callvirt, typeof(MethodInvocation).GetMethod("get_ReturnValue"));
  5.  
  6.     if (methodInfo.ReturnType.IsValueType ||
  7.         methodInfo.ReturnType.IsEnum)
  8.     {
  9.         ilGenerator.Emit(OpCodes.Unbox, methodInfo.ReturnType);
  10.         ilGenerator.Emit(OpCodes.Ldobj, methodInfo.ReturnType);
  11.     }
  12. }

The snippet is placed just before OpCodes.Ret. The OpCodes.Callvirt calls the ReturnValue property from MehodInvocation where the value is set and pushes on the top of EV stack. OpCodes.Ret returns with whatever the value is on the top of EV stack. The top has to be empty for void calls therefore an extra check is added.

Also, for value types we just can’t put null on EV stack, we will definitely end up with an “JIT encountered and internal limitation” error. Therefore, return value in MethodInvocation should go through the following check which is equivalent to default(value) call.

  1. if (returnValue == null && returnType.IsValueType)
  2. {
  3.     returnValue = Activator.CreateInstance(returnType);
  4. }

 

Finally, there are plenty of things that are missing in the proxy comparing to real ones but gives out a good example for playing with MSIL. The updated proxy can be downloaded from here .

Happy coding.

Edit : Removed the download , please check the latest post for one.

No Comments