public void AssertValidMethod(MethodInfo method)
 {
     if (method.ReturnType != preBuildContextType
         || method.GetParameterTypes().SingleOrDefaultIfMore() != preBuildContextType)
     {
         throw new InvalidMethodSignature(GetType(), method, preBuildContextType);
     }
 }
        internal static void GenerateMethodForDelegateCall(this TypeBuilder dynamicType, MethodInfo method, FieldBuilder field, MethodInfo onUnhandledException)
        {
            var il = dynamicType.CreateMethod(method);

            // the target object has a property or field that matches the signature we're looking for.
            // let's use that.

            var delegateType = WrappedDelegate.GetFuncOrActionType(method.GetParameterTypes(), method.ReturnType);

            il.LoadThis();
            il.LoadField(field);
            for (var i = 0; i < method.GetParameterTypes().Length; i++) {
                il.LoadArgument(i + 1);
            }
            il.CallVirutal(delegateType.GetMethod("Invoke"));
            il.Return();
        }
Example #3
0
        internal static bool IsDelegateAssignableFromMethod(this Type delegateType, MethodInfo methodInfo) {
            if (delegateType == null || methodInfo == null) {
                return false;
            }

            // are the return types the same?
            if (methodInfo.ReturnType != delegateType.GetDelegateReturnType() && !methodInfo.ReturnType.IsAssignableFrom(delegateType.GetDelegateReturnType())) {
                return false;
            }

            if (!delegateType.GetDelegateParameterTypes().SequenceEqual(methodInfo.GetParameterTypes(), AssignableTypeComparer.Instance)) {
                return false;
            }
            return true;
        }
Example #4
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
        {
            if (methodInfo == null)
                throw new ArgumentNullException("methodInfo");

            if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
                throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");

            Contract.EndContractBlock();

            int stackchange = 0;
            int tk = GetMethodToken(methodInfo, optionalParameterTypes, false);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // Push the return value if there is one.
            if (methodInfo.ReturnType != typeof(void))
                stackchange++;
            // Pop the parameters.
            Type[] parameters = methodInfo.GetParameterTypes();
            if (parameters != null)
                stackchange -= parameters.Length;

            // Pop the this parameter if the method is non-static and the
            // instruction is not newobj.
            if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
                stackchange--;
            // Pop the optional parameters off the stack.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            UpdateStackSize(opcode, stackchange);

            RecordTokenFixup();
            PutInteger4(tk);
        }
Example #5
0
        internal static void GenerateMethodForDirectCall(this TypeBuilder dynamicType, MethodInfo method, FieldBuilder backingField, MethodInfo instanceMethod, MethodInfo onUnhandledException)
        {
            var il = dynamicType.CreateMethod(method);
            // the target object has a method that matches.
            // let's use that.

            var hasReturn = method.ReturnType != typeof(void);
            var hasOue = onUnhandledException != null;

            var exit = il.DefineLabel();
            var setDefaultReturn = il.DefineLabel();

            var ret = hasReturn ? il.DeclareLocal(method.ReturnType) : null;
            var exc = hasOue ? il.DeclareLocal(typeof(Exception)) : null;

            il.BeginExceptionBlock();

            il.LoadThis();
            il.LoadField(backingField);

            var imTypes = instanceMethod.GetParameterTypes();
            var dmTypes = method.GetParameterTypes();

            for (var i = 0; i < dmTypes.Length; i++)
            {
                il.LoadArgument(i + 1);

                // if the types are assignable,
                if (imTypes[i].IsAssignableFrom(dmTypes[i]))
                {
                    // it assigns straight across.
                }
                else
                {
                    // it doesn't, we'll ducktype it.
                    if (dmTypes[i].GetTypeInfo().IsPrimitive)
                    {
                        // box it first?
                        il.Emit(OpCodes.Box, dmTypes[i]);
                    }
                    il.Call(AsMethod.MakeGenericMethod(imTypes[i]));
                }
            }

            // call the actual method implementation
            il.CallVirtual(instanceMethod);

            if (hasReturn)
            {
                // copy the return value in the return
                // check to see if we need to ducktype the return value here.
                if (method.ReturnType.IsAssignableFrom(instanceMethod.ReturnType))
                {
                    // it can store it directly.
                }
                else
                {
                    // it doesn't assign directly, let's ducktype it.
                    if (instanceMethod.ReturnType.GetTypeInfo().IsPrimitive)
                    {
                        il.Emit(OpCodes.Box, instanceMethod.ReturnType);
                    }
                    il.Call(AsMethod.MakeGenericMethod(method.ReturnType));
                }
                il.StoreLocation(ret);
            }
            else
            {
                // this method isn't returning anything.
                if (instanceMethod.ReturnType != typeof(void))
                {
                    // pop the return value because the generated method is void and the
                    // method we called actually gave us a result.
                    il.Emit(OpCodes.Pop);
                }
            }
            il.Emit(OpCodes.Leave_S, exit);

            il.BeginCatchBlock(typeof(Exception));
            if (hasOue)
            {
                // we're going to call the handler.
                il.StoreLocation(exc.LocalIndex);
                il.LoadArgument(0);
                il.Emit(OpCodes.Ldstr, instanceMethod.ToSignatureString());
                il.LoadLocation(exc.LocalIndex);
                il.Call(onUnhandledException);
                il.Emit(OpCodes.Leave_S, setDefaultReturn);
            }
            else
            {
                // suppress the exception quietly
                il.Emit(OpCodes.Pop);
                il.Emit(OpCodes.Leave_S, setDefaultReturn);
            }
            il.EndExceptionBlock();

            // if we can't return the appropriate value, we're returning default(T)
            il.MarkLabel(setDefaultReturn);
            SetDefaultReturnValue(il, method.ReturnType);
            il.Return();

            // looks like we're returning the value that we got back from the implementation.
            il.MarkLabel(exit);
            if (hasReturn)
            {
                il.LoadLocation(ret.LocalIndex);
            }

            il.Return();
        }
Example #6
0
 internal static ILGenerator CreateMethod(this TypeBuilder dynamicType, MethodInfo method)
 {
     return dynamicType.CreateMethod(method.Name, method.ReturnType, method.GetParameterTypes());
 }
        [System.Security.SecuritySafeCritical]  // auto-generated
        public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
        {
            if (methodInfo == null)
                throw new ArgumentNullException(nameof(methodInfo));

            if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
                throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));

            if (methodInfo.ContainsGenericParameters)
                throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));

            if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
                throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
            Contract.EndContractBlock();

            int tk;
            int stackchange = 0;

            tk = GetMemberRefToken(methodInfo, optionalParameterTypes);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // Push the return value if there is one.
            if (methodInfo.ReturnType != typeof(void))
                stackchange++;
            // Pop the parameters.
            stackchange -= methodInfo.GetParameterTypes().Length;
            // Pop the this parameter if the method is non-static and the
            // instruction is not newobj.
            if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
                stackchange--;
            // Pop the optional parameters off the stack.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            UpdateStackSize(opcode, stackchange);

            PutInteger4(tk);
        }
Example #8
0
		static bool MethodMatch (MethodInfo candidate, MethodInfo method)
		{
			if (candidate.Name != method.Name)
				return false;

			if (!HasExtensionAttribute (candidate))
				return false;

			var parameters = method.GetParameterTypes ();

			if (parameters.Length != candidate.GetParameters ().Length)
				return false;

			if (method.IsGenericMethod) {
				if (!candidate.IsGenericMethod)
					return false;

				if (candidate.GetGenericArguments ().Length != method.GetGenericArguments ().Length)
					return false;

				candidate = candidate.MakeGenericMethodFrom (method);
			}

			if (!TypeMatch (candidate.ReturnType, method.ReturnType))
				return false;

			var candidate_parameters = candidate.GetParameterTypes ();

			if (candidate_parameters [0] != GetComparableType (parameters [0]))
				return false;

			for (int i = 1; i < candidate_parameters.Length; ++i)
				if (!TypeMatch (candidate_parameters [i], parameters [i]))
					return false;

			return true;
		}
 public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
 {
     if (methodInfo == null)
     {
         throw new ArgumentNullException("methodInfo");
     }
     if ((!opcode.Equals(OpCodes.Call) && !opcode.Equals(OpCodes.Callvirt)) && !opcode.Equals(OpCodes.Newobj))
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");
     }
     int stackchange = 0;
     int num2 = this.GetMethodToken(methodInfo, optionalParameterTypes, false);
     this.EnsureCapacity(7);
     this.InternalEmit(opcode);
     if (methodInfo.ReturnType != typeof(void))
     {
         stackchange++;
     }
     Type[] parameterTypes = methodInfo.GetParameterTypes();
     if (parameterTypes != null)
     {
         stackchange -= parameterTypes.Length;
     }
     if ((!(methodInfo is SymbolMethod) && !methodInfo.IsStatic) && !opcode.Equals(OpCodes.Newobj))
     {
         stackchange--;
     }
     if (optionalParameterTypes != null)
     {
         stackchange -= optionalParameterTypes.Length;
     }
     this.UpdateStackSize(opcode, stackchange);
     this.RecordTokenFixup();
     this.PutInteger4(num2);
 }
        public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) {
            int         tk;
            int         stackchange = 0;

            if (methodInfo == null)
                throw new ArgumentNullException("methodInfo");

            if (methodInfo.ContainsGenericParameters)
                throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");

            if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
                throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");

            tk = GetMemberRefToken(methodInfo, optionalParameterTypes);

            EnsureCapacity(7);
            InternalEmit(opcode);

            // The opcode must be one of call, callvirt, or newobj.
            BCLDebug.Assert(opcode.Equals(OpCodes.Call) ||
                            opcode.Equals(OpCodes.Callvirt) ||
                            opcode.Equals(OpCodes.Newobj),
                            "Unexpected opcode passed to EmitCall.");
            
            // Push the return value if there is one.
            if (methodInfo.ReturnType != typeof(void))
                stackchange++;
            // Pop the parameters.
            stackchange -= methodInfo.GetParameterTypes().Length;
            // Pop the this parameter if the method is non-static and the
            // instruction is not newobj.
            if (!(methodInfo is SymbolMethod) && methodInfo.IsStatic == false && !(opcode.Equals(OpCodes.Newobj)))
                stackchange--;
            // Pop the optional parameters off the stack.
            if (optionalParameterTypes != null)
                stackchange -= optionalParameterTypes.Length;
            UpdateStackSize(opcode, stackchange);

            m_length = PutInteger4(tk, m_length, m_ILStream);
        }
Example #11
0
        private static Setter CreateSetter(MethodInfo method)
        {
            var dm = CreateDynamicSetterMethod();

            Type returnType = method.GetParameterTypes()[0];
            ILGenerator il = dm.GetILGenerator();
            il.DeclareLocal(returnType);

            il.Emit(OpCodes.Ldarg_1);
            EmitHelper.UnboxOrCast(il, returnType);
            il.Emit(OpCodes.Stloc_0);

            il.Emit(OpCodes.Ldarg_0);
            EmitHelper.UnboxOrCast(il, method.DeclaringType);
            il.Emit(OpCodes.Ldloc_0);

            if (method.IsFinal)
                il.Emit(OpCodes.Call, method);
            else
                il.Emit(OpCodes.Callvirt, method);

            il.Emit(OpCodes.Ret);

            return dm.CreateDelegate(typeof(Setter)) as Setter;
        }
 private static MethodBuilder DefineExplicitInterfaceMethod(this TypeBuilder typeBuilder, MethodInfo method)
 {
     var builder = typeBuilder.DefineMethod($"{method.DeclaringType.FullName}.{method.Name}",
         MethodAttributes.Private | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual,
         method.CallingConvention, method.ReturnType, method.GetParameterTypes().ToArray());
     if (method.IsGenericMethod)
     {
         builder.DefineGeneric(method);
     }
     typeBuilder.DefineMethodOverride(builder, method);
     return builder;
 }
 private static MethodBuilder DefineOverrideMethod(this TypeBuilder typeBuilder, MethodInfo method)
 {
     var builder = typeBuilder.DefineMethod(method.Name, method.GetAttributes(), method.CallingConvention, method.ReturnType, method.GetParameterTypes().ToArray());
     if (method.IsGenericMethod)
     {
         return builder.DefineGeneric(method);
     }
     return builder;
 }
        private static void MethodIntercept(ILGenerator ilGenerator, MethodInfo methodInfo, IInterceptor[] interceptors, LocalBuilder[] local,
            bool[] boolean, Action<ILGenerator> method)
        {
            var methodInterceptors = interceptors.GetMethodInterceptor();
            if (!methodInterceptors.Any())
            {
                method(ilGenerator);
                return;
            }
            var invocationType = InternalDynamicTypeProvider.CreateType<IMethodInvocation>();
            var returnParameterType = InternalDynamicTypeProvider.CreateType<IReturnParameter>();

            var parameterType = InternalDynamicTypeProvider.CreateType<IParameter>();
            var setParameters = invocationType.GetMethod("set_Parameters");
            var setParameterValue = parameterType.GetMethod("set_Value");
            var getParameterValue = parameterType.GetMethod("get_Value");
            var setParameterName = parameterType.GetMethod("set_Name");
            var setParameterInfo = parameterType.GetMethod("set_ParameterInfo");
            var getParameterName = typeof(ParameterInfo).GetMethod("get_Name");
            var getCurrentParameter = typeof(InterceptorExtends).GetMethod("GetCurrentParameter");

            var setReturnParameter = invocationType.GetMethod("set_ReturnParameter");
            var getReturnValue = returnParameterType.GetMethod("get_Value");
            var setReturnType = returnParameterType.GetMethod("set_ReturnType");
            var setReturnValue = returnParameterType.GetMethod("set_Value");
            var returnParameterLocal = ilGenerator.DeclareLocal(returnParameterType);
            var getReturnType = typeof(MethodInfo).GetMethod("get_ReturnType");
            var setInterceptedMethod = invocationType.GetMethod("set_InterceptedMethod");
            var setInterceptedType = invocationType.GetMethod("set_InterceptedType");
            var setInterceptedInstance = invocationType.GetMethod("set_InterceptedInstance");
            var getExecutedHandled = invocationType.GetMethod("get_ExecutedHandled");
            var getGetMethodInterceptor = typeof(InterceptorExtends).GetMethod("GetMethodInterceptor");
            var getGetExecutedMethodInterceptor = typeof(InterceptorExtends).GetMethod("GetExecutedMethodInterceptor");
            var onMethodExecuting = typeof(IMethodInterceptor).GetMethod("OnMethodExecuting");
            var onMethodExecuted = typeof(IMethodInterceptor).GetMethod("OnMethodExecuted");
            var interceptorLocal = ilGenerator.DeclareLocal(typeof(IMethodInterceptor[]));
            var executedInterceptorLocal = ilGenerator.DeclareLocal(typeof(IMethodInterceptor[]));


            var parametersLocal = ilGenerator.DeclareLocal(typeof(IParameter[]));
         


            var invocationLocal = ilGenerator.DeclareLocal(invocationType);
            var endLable = ilGenerator.DefineLabel();
            ilGenerator.LoadLocal(local[0]).Call(getGetMethodInterceptor).StoreLocal(interceptorLocal);
            ilGenerator.LoadLocal(local[0]).Call(getGetExecutedMethodInterceptor).StoreLocal(executedInterceptorLocal);
            ilGenerator.New(invocationType.GetConstructor(Type.EmptyTypes)).StoreLocal(invocationLocal);
            ilGenerator.LoadLocal(invocationLocal).LoadLocal(local[1]).Callvirt(setInterceptedMethod);
            ilGenerator.LoadLocal(invocationLocal).LoadLocal(local[2]).Callvirt(setInterceptedType);
            ilGenerator.LoadLocal(invocationLocal).This().Callvirt(setInterceptedInstance);
            ilGenerator.New(returnParameterType.GetConstructor(Type.EmptyTypes)).StoreLocal(returnParameterLocal);
            if (boolean[0]) ilGenerator.LoadLocal(returnParameterLocal).LoadLocal(local[1]).Callvirt(getReturnType).Callvirt(setReturnType);
            else ilGenerator.LoadLocal(returnParameterLocal).Typeof(typeof(void)).Callvirt(setReturnType);
            ilGenerator.LoadLocal(invocationLocal).LoadLocal(returnParameterLocal).Callvirt(setReturnParameter);

            ilGenerator.NewArray(typeof(IParameter), methodInfo.GetParameters().Length).StoreLocal(parametersLocal);
            ilGenerator.ForEach(methodInfo.GetParameterTypes(), (il, arg, i) =>
            {
                var argLocal = ilGenerator.DeclareLocal(parameterType);
                ilGenerator.New(parameterType.GetConstructor(Type.EmptyTypes)).StoreLocal(argLocal);
                ilGenerator.LoadLocal(argLocal).LoadArgument(i + 1).Box(arg).Callvirt(setParameterValue);
                ilGenerator.LoadLocal(argLocal).LoadLocal(local[1]).LoadInt(i).Call(getCurrentParameter).Callvirt(setParameterInfo);
                ilGenerator.LoadLocal(argLocal).LoadLocal(local[1]).LoadInt(i).Call(getCurrentParameter).Callvirt(getParameterName).Callvirt(setParameterName);
                ilGenerator.LoadLocal(parametersLocal).LoadInt(i).LoadLocal(argLocal).SetArrayItemRef();
            });
            ilGenerator.LoadLocal(invocationLocal).LoadLocal(parametersLocal).Callvirt(setParameters);

            ilGenerator.ForEach(methodInterceptors, (_, interceptor, index) =>
            _.LoadLocal(interceptorLocal).LoadArrayItem(index).LoadLocal(invocationLocal)
            .Callvirt(onMethodExecuting).LoadLocal(invocationLocal).Callvirt(getExecutedHandled).False(endLable));

            ilGenerator.ForEach(methodInfo.GetParameterTypes(), (il, arg, i) =>
            {
                ilGenerator.LoadLocal(parametersLocal).LoadArrayItem(i).Callvirt(getParameterValue).UnBox(arg).StroeArgument(i + 1);
            });
            method(ilGenerator);


            if (boolean[0]) ilGenerator.LoadLocal(returnParameterLocal).LoadLocal(local[3]).Callvirt(setReturnValue);
            ilGenerator.ForEach(methodInterceptors.OrderBy(i => i.ExecutedOrder), (_, interceptor, index) =>
            _.LoadLocal(executedInterceptorLocal).LoadArrayItem(index).LoadLocal(invocationLocal).
            Callvirt(onMethodExecuted).LoadLocal(invocationLocal).Callvirt(getExecutedHandled).False(endLable));
            ilGenerator.MarkLabelFor(endLable);
            if (boolean[0]) ilGenerator.LoadLocal(returnParameterLocal).Callvirt(getReturnValue).StoreLocal(local[3]);
        }
 private static bool MethodMatch(MethodInfo candidate, MethodInfo method)
 {
     if (candidate.Name != method.Name || !HasExtensionAttribute(candidate))
     {
         return false;
     }
     var parameters = method.GetParameterTypes();
     if (parameters.Length != candidate.GetParameters().Length)
     {
         return false;
     }
     else if (method.IsGenericMethod)
     {
         if (!candidate.IsGenericMethod || candidate.GetGenericArguments().Length != method.GetGenericArguments().Length)
         {
             return false;
         }
         candidate = candidate.MakeGenericMethodFrom(method);
     }
     if (!TypeMatch(candidate.ReturnType, method.ReturnType))
     {
         return false;
     }
     var candidate_parameters = candidate.GetParameterTypes();
     if (candidate_parameters[0] != GetComparableType(parameters[0]))
     {
         return false;
     }
     for (int index = 1; index < candidate_parameters.Length; ++index)
     {
         if (!TypeMatch(candidate_parameters[index], parameters[index]))
         {
             return false;
         }
     }
     return true;
 }
 public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes)
 {
     if (methodInfo == null)
     {
         throw new ArgumentNullException("methodInfo");
     }
     if ((!opcode.Equals(OpCodes.Call) && !opcode.Equals(OpCodes.Callvirt)) && !opcode.Equals(OpCodes.Newobj))
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), "opcode");
     }
     if (methodInfo.ContainsGenericParameters)
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");
     }
     if ((methodInfo.DeclaringType != null) && methodInfo.DeclaringType.ContainsGenericParameters)
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "methodInfo");
     }
     int stackchange = 0;
     int memberRefToken = this.GetMemberRefToken(methodInfo, optionalParameterTypes);
     base.EnsureCapacity(7);
     base.InternalEmit(opcode);
     if (methodInfo.ReturnType != typeof(void))
     {
         stackchange++;
     }
     stackchange -= methodInfo.GetParameterTypes().Length;
     if ((!(methodInfo is SymbolMethod) && !methodInfo.IsStatic) && !opcode.Equals(OpCodes.Newobj))
     {
         stackchange--;
     }
     if (optionalParameterTypes != null)
     {
         stackchange -= optionalParameterTypes.Length;
     }
     base.UpdateStackSize(opcode, stackchange);
     base.PutInteger4(memberRefToken);
 }