System.Reflection.Emit.ILGenerator.Emit(System.Reflection.Emit.OpCode, System.Reflection.MethodInfo)

Here are the examples of the csharp api System.Reflection.Emit.ILGenerator.Emit(System.Reflection.Emit.OpCode, System.Reflection.MethodInfo) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

542 Examples 7

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<IDataRecord, T> CreateTypeSerializerHandler<T>(MemberMapper mapper, IDataRecord record)
        {
            var type = typeof(T);
            var methodName = $"Serializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, type, new Type[] { typeof(IDataRecord) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder local = generator.DeclareLocal(type);
            var dataInfos = new DataReaderCellInfo[record.FieldCount];
            for (int i = 0; i < record.FieldCount; i++)
            {
                var dataname = record.GetName(i);
                var datatype = record.GetFieldType(i);
                var typename = record.GetDataTypeName(i);
                dataInfos[i] = new DataReaderCellInfo(i, typename, datatype, dataname);
            }
            if (dataInfos.Length == 1 && (type.IsValueType || type == typeof(string) || type == typeof(object)))
            {
                var dataInfo = dataInfos.First();
                var convertMethod = mapper.FindConvertMethod(type, dataInfo.DataType);
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, 0);
                if (convertMethod.IsVirtual)
                    generator.Emit(OpCodes.Callvirt, convertMethod);
                else
                    generator.Emit(OpCodes.Call, convertMethod);
                if (type == typeof(object) && convertMethod.ReturnType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, convertMethod.ReturnType);
                }
                generator.Emit(OpCodes.Stloc, local);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
            var constructor = mapper.FindConstructor(type);
            if (constructor.GetParameters().Length > 0)
            {
                var parameters = constructor.GetParameters();
                var locals = new LocalBuilder[parameters.Length];
                for (int i = 0; i < locals.Length; i++)
                {
                    locals[i] = generator.DeclareLocal(parameters[i].ParameterType);
                }
                for (int i = 0; i < locals.Length; i++)
                {
                    var item = mapper.FindConstructorParameter(dataInfos, parameters[i]);
                    if (item == null)
                    {
                        continue;
                    }
                    var convertMethod = mapper.FindConvertMethod(parameters[i].ParameterType, item.DataType);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldc_I4, item.Ordinal);
                    if (convertMethod.IsVirtual)
                        generator.Emit(OpCodes.Callvirt, convertMethod);
                    else
                        generator.Emit(OpCodes.Call, convertMethod);
                    generator.Emit(OpCodes.Stloc, locals[i]);
                }
                for (int i = 0; i < locals.Length; i++)
                {
                    generator.Emit(OpCodes.Ldloc, locals[i]);
                }
                generator.Emit(OpCodes.Newobj, constructor);
                generator.Emit(OpCodes.Stloc, local);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
            else
            {
                var properties = type.GetProperties();
                generator.Emit(OpCodes.Newobj, constructor);
                generator.Emit(OpCodes.Stloc, local);
                foreach (var item in dataInfos)
                {
                    var property = mapper.FindMember(properties, item) as PropertyInfo;
                    if (property == null)
                    {
                        continue;
                    }
                    var convertMethod = mapper.FindConvertMethod(property.PropertyType, item.DataType);
                    if (convertMethod == null)
                    {
                        continue;
                    }
                    int i = record.GetOrdinal(item.DataName);
                    generator.Emit(OpCodes.Ldloc, local);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldc_I4, i);
                    if (convertMethod.IsVirtual)
                        generator.Emit(OpCodes.Callvirt, convertMethod);
                    else
                        generator.Emit(OpCodes.Call, convertMethod);
                    generator.Emit(OpCodes.Callvirt, property.GetSetMethod());
                }
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
        }

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<object, Dictionary<string, object>> CreateTypeDeserializerHandler(Type type)
        {
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var methodName = $"{type.Name}Deserializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, typeof(Dictionary<string, object>), new Type[] { typeof(object) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder enreplacedyLocal1 = generator.DeclareLocal(typeof(Dictionary<string, object>));
            LocalBuilder enreplacedyLocal2 = generator.DeclareLocal(type);
            generator.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
            generator.Emit(OpCodes.Stloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclreplaced, type);
            generator.Emit(OpCodes.Stloc, enreplacedyLocal2);
            foreach (var item in properties)
            {
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
                generator.Emit(OpCodes.Ldstr, item.Name);
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal2);
                generator.Emit(OpCodes.Callvirt, item.GetGetMethod());
                if (item.PropertyType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, item.PropertyType);
                }
                var addMethod = typeof(Dictionary<string, object>).GetMethod(nameof(Dictionary<string, object>.Add), new Type[] { typeof(string), typeof(object) });
                generator.Emit(OpCodes.Callvirt, addMethod);
            }
            generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<object, Dictionary<string, object>>)) as Func<object, Dictionary<string, object>>;
        }

19 View Source File : EmitHelper.cs
License : MIT License
Project Creator : 1996v

public static void EmitCall(this ILGenerator il, MethodInfo methodInfo)
        {
            if (methodInfo.IsFinal || !methodInfo.IsVirtual)
            {
                il.Emit(OpCodes.Call, methodInfo);
            }
            else
            {
                il.Emit(OpCodes.Callvirt, methodInfo);
            }
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallOneMethodInSerialize(MethodBuilder serialize, MethodInfo method)
        {
            ILGenerator il = serialize.GetILGenerator();
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Call, method);
            il.Emit(OpCodes.Ret);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallSerializeDelegate(MethodBuilder serializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = serializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Call, typeof(Serialize<>).MakeGenericType(genericType).GetMethod(nameof(Serialize<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallOneMethodInDeserialize(MethodBuilder deserialize, MethodInfo method)
        {
            ILGenerator il = deserialize.GetILGenerator();
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, method);
            il.Emit(OpCodes.Ret);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallOneStaticFieldMethodInDeserialize(MethodBuilder deserialize, FieldInfo fieldInfo, MethodInfo method)
        {
            ILGenerator il = deserialize.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Callvirt, method);
            il.Emit(OpCodes.Ret);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallDeserializeDelegate(MethodBuilder deserializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = deserializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(Deserialize<>).MakeGenericType(genericType).GetMethod(nameof(Deserialize<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallOneMethodInSize(MethodBuilder serialize, MethodInfo method)
        {
            ILGenerator il = serialize.GetILGenerator();
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, method);
            il.Emit(OpCodes.Ret);
        }

19 View Source File : TypeBuildHelper.cs
License : MIT License
Project Creator : 1996v

public static void CallSizeDelegate(MethodBuilder serializeMethod, Type genericType, FieldInfo fieldInfo)
        {
            ILGenerator il = serializeMethod.GetILGenerator();
            il.Emit(OpCodes.Ldsfld, fieldInfo);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(Size<>).MakeGenericType(genericType).GetMethod(nameof(Size<int>.Invoke)));
            il.Emit(OpCodes.Ret);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
        {
            // Generate the "FindMethodHandleOfDynamicMethod" delegate.
            DynamicMethod findMethodHandle = new DynamicMethod(
                nameof(FindMethodHandleOfDynamicMethod),
                typeof(RuntimeMethodHandle),
                new[] { typeof(DynamicMethod) },
                typeof(DynamicMethod), true);

            ILGenerator il = findMethodHandle.GetILGenerator(16);

            il.Emit(OpCodes.Ldarg_0);

            MethodInfo getMethodDescriptor = typeof(DynamicMethod)
                .GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);

            if (getMethodDescriptor != null)
            {
                il.Emit(OpCodes.Callvirt, getMethodDescriptor);
            }
            else
            {
                FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
                                     ?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
                                     ?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);

                il.Emit(OpCodes.Ldfld, handleField);
            }

            il.Emit(OpCodes.Ret);

            return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
                as Func<DynamicMethod, RuntimeMethodHandle>;
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

private static Func<RuntimeMethodHandle, IntPtr> MakeGetFunctionPointer()
        {
            // Generate the "GetFunctionPointer" delegate.
            DynamicMethod getFunctionPointer = new DynamicMethod(
                nameof(GetFunctionPointer),
                typeof(IntPtr),
                new[] { typeof(RuntimeMethodHandle) },
                typeof(RuntimeMethodHandle), true);

            ILGenerator il = getFunctionPointer.GetILGenerator(16);

            il.Emit(OpCodes.Ldarga_S, (short)0);
            il.Emit(OpCodes.Call, typeof(RuntimeMethodHandle).GetMethod(nameof(GetFunctionPointer), PUBLIC_INSTANCE));
            il.Emit(OpCodes.Ret);

            return getFunctionPointer.CreateDelegate(typeof(Func<RuntimeMethodHandle, IntPtr>))
                as Func<RuntimeMethodHandle, IntPtr>;
        }

19 View Source File : Redirection.Reactive.cs
License : MIT License
Project Creator : 71

private static MethodRedirection CreateDynamicRedirection(MethodBase method, out int id)
        {
            // Make id
            do
            {
                id = ObservingRedirectionsIdGenerator.Next();
            }
            while (ObservingRedirections.ContainsKey(id));

            // Creates an array containing all parameter types
            int diff = method.IsStatic ? 0 : 1;

            ParameterInfo[] originalParameters = method.GetParameters();
            Type[] originalParameterTypes = new Type[originalParameters.Length + diff];

            if (diff == 1 /* !method.IsStatic */)
                originalParameterTypes[0] = method.DeclaringType;

            for (int i = 0; i < originalParameters.Length; i++)
            {
                originalParameterTypes[i + diff] = originalParameters[i].ParameterType;
            }

            // Create an identical method
            bool isCtor = method is ConstructorInfo;
            Type returnType = isCtor ? typeof(void) : ((MethodInfo)method).ReturnType;

            DynamicMethod dyn = new DynamicMethod(
                name:              method.Name,
                attributes:        MethodAttributes.Public | MethodAttributes.Static,
                callingConvention: CallingConventions.Standard,
                returnType:        returnType,
                parameterTypes:    originalParameterTypes,
                owner:             method.DeclaringType,
                skipVisibility:    true);

            // Make the method call the observable
            ILGenerator il = dyn.GetILGenerator();
            {
                // This is in a block to make every more readable,
                // the following comments describe what's happening in the generated method.

                // Emit "this", or "null"
                if (method.IsStatic)
                {
                    il.Emit(OpCodes.Ldnull);
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_0);

                    if (method.DeclaringType.GetTypeInfo().IsValueType)
                    {
                        il.Emit(OpCodes.Ldobj, method.DeclaringType);
                        il.Emit(OpCodes.Box, method.DeclaringType);
                    }
                }

                // Create an array containing all parameters
                il.Emit(OpCodes.Ldc_I4, originalParameters.Length);
                il.Emit(OpCodes.Newarr, typeof(object));

                for (int i = 0; i < originalParameters.Length; i++)
                {
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Ldarg, i + diff);

                    Type parameterType = originalParameterTypes[i + diff];

                    if (parameterType.GetTypeInfo().IsValueType)
                        il.Emit(OpCodes.Box, parameterType);

                    il.Emit(OpCodes.Stelem_Ref);
                }

                // Array is still on stack (thanks to dup)
                // Emit id
                il.Emit(OpCodes.Ldc_I4, id);

                // Call "hook" method
                il.Emit(OpCodes.Call, typeof(Redirection).GetMethod(nameof(OnInvoked), BindingFlags.Static | BindingFlags.NonPublic));

                // Return returned result
                // (But first, cast it if needed)
                if (returnType == typeof(void))
                    il.Emit(OpCodes.Pop);
                else if (returnType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Unbox_Any, returnType);
                else if (returnType != typeof(object))
                    il.Emit(OpCodes.Castclreplaced, returnType);

                il.Emit(OpCodes.Ret);
            }

            // Return the redirection
            return new MethodRedirection(method, dyn, false);
        }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

private static Func<DynamicMethod, RuntimeMethodHandle> MakeFindMethodHandleOfDynamicMethod()
            {
                // Generate the "FindMethodHandleOfDynamicMethod" delegate.
                DynamicMethod findMethodHandle = new DynamicMethod(
                    nameof(FindMethodHandleOfDynamicMethod),
                    typeof(RuntimeMethodHandle),
                    new[] { typeof(DynamicMethod) },
                    typeof(DynamicMethod), true);

                ILGenerator il = findMethodHandle.GetILGenerator(16);

                il.Emit(OpCodes.Ldarg_0);

                MethodInfo getMethodDescriptor = typeof(DynamicMethod)
                    .GetMethod("GetMethodDescriptor", NON_PUBLIC_INSTANCE);

                if (getMethodDescriptor != null)
                {
                    il.Emit(OpCodes.Callvirt, getMethodDescriptor);
                }
                else
                {
                    FieldInfo handleField = typeof(DynamicMethod).GetField("m_method", NON_PUBLIC_INSTANCE)
                                         ?? typeof(DynamicMethod).GetField("mhandle", NON_PUBLIC_INSTANCE)
                                         ?? typeof(DynamicMethod).GetField("m_methodHandle", NON_PUBLIC_INSTANCE);

                    il.Emit(OpCodes.Ldfld, handleField);
                }

                il.Emit(OpCodes.Ret);

                return findMethodHandle.CreateDelegate(typeof(Func<DynamicMethod, RuntimeMethodHandle>))
                    as Func<DynamicMethod, RuntimeMethodHandle>;
            }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

private static Func<MethodBase, RuntimeMethodHandle> MakeGetMethodHandle()
            {
                // Generate the "GetMethodHandle" delegate.
                DynamicMethod getMethodHandle = new DynamicMethod(
                    nameof(GetMethodHandle),
                    typeof(RuntimeMethodHandle),
                    new[] { typeof(MethodBase) },
                    typeof(RuntimeMethodHandle), true);

                ILGenerator il = getMethodHandle.GetILGenerator(16);

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, typeof(MethodBase).GetProperty("MethodHandle", PUBLIC_INSTANCE).GetMethod);
                il.Emit(OpCodes.Ret);

                return getMethodHandle.CreateDelegate(typeof(Func<MethodBase, RuntimeMethodHandle>))
                    as Func<MethodBase, RuntimeMethodHandle>;
            }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

private static Func<RuntimeMethodHandle, IntPtr> MakeGetFunctionPointer()
            {
                // Generate the "GetFunctionPointer" delegate.
                DynamicMethod getFunctionPointer = new DynamicMethod(
                    nameof(GetFunctionPointer),
                    typeof(IntPtr),
                    new[] { typeof(RuntimeMethodHandle) },
                    typeof(RuntimeMethodHandle), true);

                ILGenerator il = getFunctionPointer.GetILGenerator(16);

                il.Emit(OpCodes.Ldarga_S, (short)0);
                il.Emit(OpCodes.Call, typeof(RuntimeMethodHandle).GetMethod(nameof(GetFunctionPointer), PUBLIC_INSTANCE));
                il.Emit(OpCodes.Ret);

                return getFunctionPointer.CreateDelegate(typeof(Func<RuntimeMethodHandle, IntPtr>))
                    as Func<RuntimeMethodHandle, IntPtr>;
            }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

private static Func<MethodBase, RuntimeMethodHandle> MakeGetMethodHandle()
        {
            // Generate the "GetMethodHandle" delegate.
            DynamicMethod getMethodHandle = new DynamicMethod(
                nameof(GetMethodHandle),
                typeof(RuntimeMethodHandle),
                new[] { typeof(MethodBase) },
                typeof(RuntimeMethodHandle), true);

            ILGenerator il = getMethodHandle.GetILGenerator(16);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Callvirt, typeof(MethodBase).GetProperty("MethodHandle", PUBLIC_INSTANCE).GetMethod);
            il.Emit(OpCodes.Ret);

            return getMethodHandle.CreateDelegate(typeof(Func<MethodBase, RuntimeMethodHandle>))
                as Func<MethodBase, RuntimeMethodHandle>;
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

internal static Func<IDataReader, T> ReaderToObject(IDataReader rdr)
        {
            MethodInfo rdrGetValueMethod = rdr.GetType().GetMethod("get_Item", new Type[] { typeof(int) });

            Type[] args = { typeof(IDataReader) };
            DynamicMethod method = new DynamicMethod("DynamicRead" + Guid.NewGuid().ToString(), typeof(T), args, typeof(Repository<T>).Module, true);
            ILGenerator il = method.GetILGenerator();

            LocalBuilder result = il.DeclareLocal(typeof(T)); //loc_0
            il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Stloc_0, result); //Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.

            Label tryBlock = il.BeginExceptionBlock();

            LocalBuilder valueCopy = il.DeclareLocal(typeof(object)); //declare local variable to store object value. loc_1

            il.DeclareLocal(typeof(int)); //declare local variable to store index //loc_2
            il.Emit(OpCodes.Ldc_I4_0); //load 0 in index
            il.Emit(OpCodes.Stloc_2); //pop and save to local variable loc 2

            //get FieldInfo of all properties
            TableAttribute tableInfo = EnreplacedyCache.Get(typeof(T));

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                tableInfo.Columns.TryGetValue(rdr.GetName(i), out ColumnAttribute columnInfo);

                if (columnInfo != null && columnInfo.SetMethod != null)
                {
                    Label endIfLabel = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0);//load the argument. Loads the argument at index 0 onto the evaluation stack.
                    il.Emit(OpCodes.Ldc_I4, i); //push field index as int32 to the stack. Pushes a supplied value of type int32 onto the evaluation stack as an int32.
                    il.Emit(OpCodes.Dup);//copy value
                    il.Emit(OpCodes.Stloc_2);//pop and save value to loc 2
                    il.Emit(OpCodes.Callvirt, rdrGetValueMethod); //Call rdr[i] method - Calls a late - bound method on an object, pushing the return value onto the evaluation stack.

                    //TODO: dynamic location using valueCopyLocal
                    il.Emit(OpCodes.Stloc_1); //pop the value and push in stack location 1
                    il.Emit(OpCodes.Ldloc_1); //load the variable in location 1

                    il.Emit(OpCodes.Isinst, typeof(DBNull)); //check whether value is null - Tests whether an object reference (type O) is an instance of a particular clreplaced.
                    il.Emit(OpCodes.Brtrue, endIfLabel); //go to end block if value is null

                    il.Emit(OpCodes.Ldloc_0); //load T result
                    il.Emit(OpCodes.Ldloc_1); //TODO: dynamic location using valueCopyLocal

                    //when Enum are without number values
                    if (columnInfo.Property.PropertyType.IsEnum)
                    {
                        Type numericType = Enum.GetUnderlyingType(columnInfo.Property.PropertyType);
                        if (rdr.GetFieldType(i) == typeof(string))
                        {
                            LocalBuilder stringEnumLocal = il.DeclareLocal(typeof(string));

                            il.Emit(OpCodes.Castclreplaced, typeof(string)); // stack is now [...][string]
                            il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
                            il.Emit(OpCodes.Ldtoken, columnInfo.Property.PropertyType); // stack is now [...][enum-type-token]
                            il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null);// stack is now [...][enum-type]
                            il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
                            il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
                            il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
                            il.Emit(OpCodes.Unbox_Any, columnInfo.Property.PropertyType); // stack is now [...][typed-value]
                        }
                        else
                        {
                            ConvertValueToEnum(il, rdr.GetFieldType(i), columnInfo.Property.PropertyType, numericType);
                        }
                    }
                    else if (columnInfo.Property.PropertyType.IsValueType)
                        il.Emit(OpCodes.Unbox_Any, rdr.GetFieldType(i)); //type cast

                    // for nullable type fields
                    if (columnInfo.Property.PropertyType.IsGenericType && columnInfo.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        var underlyingType = Nullable.GetUnderlyingType(columnInfo.Property.PropertyType);
                        il.Emit(OpCodes.Newobj, columnInfo.Property.PropertyType.GetConstructor(new Type[] { underlyingType }));
                    }

                    il.Emit(OpCodes.Callvirt, columnInfo.SetMethod);
                    il.Emit(OpCodes.Nop);

                    il.MarkLabel(endIfLabel);
                }
            }

            il.BeginCatchBlock(typeof(Exception)); //begin try block. exception is in stack
            il.Emit(OpCodes.Ldloc_2); //load index
            il.Emit(OpCodes.Ldarg_0); //load argument reader
            il.Emit(OpCodes.Ldloc_1); //load value //TODO: dynamic location using valueCopyLocal
            il.EmitCall(OpCodes.Call, typeof(ReaderCache<T>).GetMethod(nameof(ReaderCache<T>.HandleException)), null); //call exception handler
            il.EndExceptionBlock();

            il.Emit(OpCodes.Ldloc, result);
            il.Emit(OpCodes.Ret);
            

            var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(IDataReader), typeof(T));
            return (Func<IDataReader, T>)method.CreateDelegate(funcType);
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static void ConvertValueToEnum(ILGenerator il, Type from, Type to, Type via)
        {
            MethodInfo op;
            if (from == (via ?? to))
            {
                il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
            }
            else if ((op = GetOperator(from, to)) != null)
            {
                // this is handy for things like decimal <===> double
                il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
                il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
            }
            else
            {
                bool handled = false;
                OpCode opCode = default;
                switch (Type.GetTypeCode(from))
                {
                    case TypeCode.Boolean:
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                        handled = true;
                        switch (Type.GetTypeCode(via ?? to))
                        {
                            case TypeCode.Byte:
                                opCode = OpCodes.Conv_Ovf_I1_Un; break;
                            case TypeCode.SByte:
                                opCode = OpCodes.Conv_Ovf_I1; break;
                            case TypeCode.UInt16:
                                opCode = OpCodes.Conv_Ovf_I2_Un; break;
                            case TypeCode.Int16:
                                opCode = OpCodes.Conv_Ovf_I2; break;
                            case TypeCode.UInt32:
                                opCode = OpCodes.Conv_Ovf_I4_Un; break;
                            case TypeCode.Boolean: // boolean is basically an int, at least at this level
                            case TypeCode.Int32:
                                opCode = OpCodes.Conv_Ovf_I4; break;
                            case TypeCode.UInt64:
                                opCode = OpCodes.Conv_Ovf_I8_Un; break;
                            case TypeCode.Int64:
                                opCode = OpCodes.Conv_Ovf_I8; break;
                            case TypeCode.Single:
                                opCode = OpCodes.Conv_R4; break;
                            case TypeCode.Double:
                                opCode = OpCodes.Conv_R8; break;
                            default:
                                handled = false;
                                break;
                        }
                        break;
                }
                if (handled)
                {
                    il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][col-typed-value]
                    il.Emit(opCode); // stack is now [target][target][typed-value]
                    if (to == typeof(bool))
                    { // compare to zero; I checked "csc" - this is the trick it uses; nice
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Ldtoken, via ?? to); // stack is now [target][target][value][member-type-token]
                    il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null); // stack is now [target][target][value][member-type]
                    il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
                    il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
                }
            }
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static Action<object, IDbCommand> AddParametersIL(object param, IDbCommand cmd)
        {
            Type pType = param.GetType();
            Type[] args = { typeof(object), typeof(IDbCommand) };

            DynamicMethod method = new DynamicMethod("DynamicAddParam" + Guid.NewGuid().ToString(), null, args, typeof(ParameterCache).Module, true);
            ILGenerator il = method.GetILGenerator();

            foreach (PropertyInfo property in pType.GetProperties())
            {
                il.Emit(OpCodes.Ldarg_1);//load the idbcommand. Loads the argument at index 0 onto the evaluation stack.

                //name
                il.Emit(OpCodes.Ldstr, property.Name);

                //dbtype
                //dynamic property will always return System.Object as property type. Get Type from the value
                Type type = GetTypeOfDynamicProperty(property, param);
                    
                if (type.IsEnum) type = Enum.GetUnderlyingType(type);

                if(TypeCache.TypeToDbType.TryGetValue(type, out DbType dbType))
                    il.Emit(OpCodes.Ldc_I4_S, (byte)dbType);
                else
                    il.Emit(OpCodes.Ldc_I4_S, (byte)DbType.String); //TODO: fix when unkown type

                //value
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, property.GetMethod);

                //box if value type
                if (property.PropertyType.IsValueType)
                    il.Emit(OpCodes.Box, property.PropertyType);

                il.Emit(OpCodes.Call, addInParameter);

                il.Emit(OpCodes.Nop);
            }
            il.Emit(OpCodes.Ret);

            var actionType = System.Linq.Expressions.Expression.GetActionType(typeof(object), typeof(IDbCommand));
            return (Action<object, IDbCommand>)method.CreateDelegate(actionType);
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : ad313

private static Func<object, Dictionary<string, object>> CreateDictionaryGenerator(Type type)
        {
            var dm = new DynamicMethod($"Dictionary{Guid.NewGuid()}", typeof(Dictionary<string, object>), new[] { typeof(object) }, type, true);
            ILGenerator il = dm.GetILGenerator();
            il.DeclareLocal(typeof(Dictionary<string, object>));
            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Stloc_0);

            foreach (var item in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                string columnName = item.Name;
                il.Emit(OpCodes.Nop);
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldstr, columnName);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                if (item.PropertyType.IsValueType)
                {
                    il.Emit(OpCodes.Box, item.PropertyType);
                }
                il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
            }
            il.Emit(OpCodes.Nop);

            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);
            return (Func<object, Dictionary<string, object>>)dm.CreateDelegate(typeof(Func<object, Dictionary<string, object>>));
        }

19 View Source File : DarksVMTrampoline.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static DynamicMethod CreateTrampolineTyped(int moduleId, ulong codeAdr, uint key, DarksVMFuncSig sig, uint sigId)
        {
            var dm = new DynamicMethod("", sig.RetType, sig.ParamTypes, Unverifier.Module, true);

            var gen = dm.GetILGenerator();
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, moduleId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I8, (long) codeAdr);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) key);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) sigId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, sig.ParamTypes.Length);
            gen.Emit(System.Reflection.Emit.OpCodes.Newarr, typeof(void*));
            for(var i = 0; i < sig.ParamTypes.Length; i++)
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Dup);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                if(sig.ParamTypes[i].IsByRef)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, sig.ParamTypes[i].GetElementType());
                }
                else
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, sig.ParamTypes[i]);
                }
                var local = gen.DeclareLocal(typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Stloc, local);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, local);
                gen.Emit(System.Reflection.Emit.OpCodes.Conv_I);
                gen.Emit(System.Reflection.Emit.OpCodes.Stelem_I);
            }

            if(sig.RetType != typeof(void))
            {
                var retVar = gen.DeclareLocal(sig.RetType);
                var retRef = gen.DeclareLocal(typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, retVar);
                gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, sig.RetType);
                gen.Emit(System.Reflection.Emit.OpCodes.Stloc, retRef);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, retRef);
                gen.Emit(System.Reflection.Emit.OpCodes.Call, entryStubTyped);

                gen.Emit(System.Reflection.Emit.OpCodes.Ldloc, retVar);
            }
            else
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Ldnull);
                gen.Emit(System.Reflection.Emit.OpCodes.Call, entryStubTyped);
            }
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

            return dm;
        }

19 View Source File : DirectCall.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static MethodBase GetDirectInvocationProxy(MethodBase method)
        {
            var proxy = (MethodBase) directProxies[method];
            if(proxy != null)
                return proxy;

            lock(directProxies)
            {
                proxy = (MethodBase) directProxies[method];
                if(proxy != null)
                    return proxy;

                var parameters = method.GetParameters();
                var paramTypes = new Type[parameters.Length + (method.IsStatic ? 0 : 1)];
                for(var i = 0; i < paramTypes.Length; i++)
                    if(method.IsStatic)
                    {
                        paramTypes[i] = parameters[i].ParameterType;
                    }
                    else
                    {
                        if(i == 0)
                            paramTypes[0] = method.DeclaringType;
                        else
                            paramTypes[i] = parameters[i - 1].ParameterType;
                    }

                var retType = method is MethodInfo ? ((MethodInfo) method).ReturnType : typeof(void);
                var dm = new DynamicMethod("", retType, paramTypes, Unverifier.Module, true);
                var gen = dm.GetILGenerator();
                for(var i = 0; i < paramTypes.Length; i++)
                    if(!method.IsStatic && i == 0 && paramTypes[0].IsValueType)
                        gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, i);
                    else
                        gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                if(method is MethodInfo)
                    gen.Emit(System.Reflection.Emit.OpCodes.Call, (MethodInfo) method);
                else
                    gen.Emit(System.Reflection.Emit.OpCodes.Call, (ConstructorInfo) method);
                gen.Emit(System.Reflection.Emit.OpCodes.Ret);

                directProxies[method] = dm;
                return dm;
            }
        }

19 View Source File : DirectCall.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static TypedInvocation GetTypedInvocationProxy(MethodBase method, OpCode opCode, Type constrainType)
        {
            Hashtable table;
            object key;
            if(constrainType == null)
            {
                key = new KeyValuePair<MethodBase, OpCode>(method, opCode);
                table = typedProxies;
            }
            else
            {
                key = new KeyValuePair<MethodBase, Type>(method, constrainType);
                table = constrainedProxies;
            }

            var proxy = (TypedInvocation) table[key];
            if(proxy != null)
                return proxy;

            lock(typedProxies)
            {
                proxy = (TypedInvocation) table[key];
                if(proxy != null)
                    return proxy;

                var parameters = method.GetParameters();
                Type[] paramTypes;
                if(opCode != System.Reflection.Emit.OpCodes.Newobj)
                {
                    paramTypes = new Type[parameters.Length + (method.IsStatic ? 0 : 1) + 1];
                    for(var i = 0; i < paramTypes.Length - 1; i++)
                        if(method.IsStatic)
                        {
                            paramTypes[i] = parameters[i].ParameterType;
                        }
                        else
                        {
                            if(i == 0)
                                if(constrainType != null)
                                    paramTypes[0] = constrainType.MakeByRefType();
                                else if(method.DeclaringType.IsValueType)
                                    paramTypes[0] = method.DeclaringType.MakeByRefType();
                                else
                                    paramTypes[0] = method.DeclaringType;
                            else
                                paramTypes[i] = parameters[i - 1].ParameterType;
                        }
                }
                else
                {
                    paramTypes = new Type[parameters.Length + 1];
                    for(var i = 0; i < paramTypes.Length - 1; i++) paramTypes[i] = parameters[i].ParameterType;
                }

                var retType = method is MethodInfo ? ((MethodInfo) method).ReturnType : typeof(void);
                if(opCode == System.Reflection.Emit.OpCodes.Newobj)
                    retType = method.DeclaringType;
                var dm = new DynamicMethod("", typeof(object), new[] {typeof(DarksVMContext), typeof(IReference[]), typeof(Type[])},
                    Unverifier.Module, true);
                var gen = dm.GetILGenerator();

                for(var i = 0; i < paramTypes.Length - 1; i++)
                {
                    var paramType = paramTypes[i];
                    var isByRef = paramType.IsByRef;
                    if(isByRef)
                        paramType = paramType.GetElementType();

                    var typedRefLocal = gen.DeclareLocal(typeof(TypedReference));
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, typedRefLocal);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);

                    gen.Emit(System.Reflection.Emit.OpCodes.Callvirt, refToTypedRef);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, typedRefLocal);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);
                    gen.Emit(System.Reflection.Emit.OpCodes.Call, castTypedRef);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldloc, typedRefLocal);
                    gen.Emit(System.Reflection.Emit.OpCodes.Refanyval, paramType);

                    if(!isByRef)
                        gen.Emit(System.Reflection.Emit.OpCodes.Ldobj, paramType);
                }

                if(constrainType != null)
                    gen.Emit(System.Reflection.Emit.OpCodes.Constrained, constrainType);

                if(method is MethodInfo)
                    gen.Emit(opCode, (MethodInfo) method);
                else
                    gen.Emit(opCode, (ConstructorInfo) method);

                if(retType.IsByRef)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, retType.GetElementType());
                    gen.Emit(System.Reflection.Emit.OpCodes.Newobj, newTypedRef);
                }
                else if(retType == typeof(void))
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldnull);
                }
                else if(retType.IsValueType)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Box, retType);
                }

                gen.Emit(System.Reflection.Emit.OpCodes.Ret);

                proxy = (TypedInvocation) dm.CreateDelegate(typeof(TypedInvocation));
                table[key] = proxy;
                return proxy;
            }
        }

19 View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static bool BuildExceptionDispatchInfo(Type type)
        {
            try
            {
                var capture = type.GetMethod("Capture");
                var thr = type.GetMethod("Throw");

                var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)});
                var ilGen = dm.GetILGenerator();
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, capture);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, thr);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ret);

                rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
            }
            catch
            {
                return false;
            }
            return true;
        }

19 View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static bool BuildInternalPreserve(Type type)
        {
            try
            {
                const BindingFlags fl = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
                var at = (string) typeof(Environment).InvokeMember("GetResourceString", fl, null, null, new object[] {"Word_At"});

                var preserve = type.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
                var field = type.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
                var stackTrace = type.GetProperty("StackTrace", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
                var fmt = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object), typeof(object)});

                var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)}, true);
                var ilGen = dm.GetILGenerator();
                var lbl = ilGen.DefineLabel();
                var lbl2 = ilGen.DefineLabel();
                var lbl3 = ilGen.DefineLabel();

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Callvirt, stackTrace);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Br, lbl3);
                ilGen.MarkLabel(lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.MarkLabel(lbl3);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, preserve);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brfalse, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldstr,
                    "{1}" + Environment.NewLine + "   " + at + " DarksVM.Load() [{0}]" + Environment.NewLine);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, fmt);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);


                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                ilGen.MarkLabel(lbl);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
            return true;
        }

19 View Source File : DarksVMTrampoline.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static DynamicMethod CreateTrampolineNormal(int moduleId, ulong codeAdr, uint key, DarksVMFuncSig sig, uint sigId)
        {
            var dm = new DynamicMethod("", sig.RetType, sig.ParamTypes, Unverifier.Module, true);

            var gen = dm.GetILGenerator();
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, moduleId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I8, (long) codeAdr);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) key);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) sigId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, sig.ParamTypes.Length);
            gen.Emit(System.Reflection.Emit.OpCodes.Newarr, typeof(object));
            for(var i = 0; i < sig.ParamTypes.Length; i++)
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Dup);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                if(sig.ParamTypes[i].IsValueType)
                    gen.Emit(System.Reflection.Emit.OpCodes.Box, sig.ParamTypes[i]);
                gen.Emit(System.Reflection.Emit.OpCodes.Stelem_Ref);
            }

            gen.Emit(System.Reflection.Emit.OpCodes.Call, entryStubNormal);

            if(sig.RetType == typeof(void))
                gen.Emit(System.Reflection.Emit.OpCodes.Pop);
            else if(sig.RetType.IsValueType)
                gen.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, sig.RetType);
            else
                gen.Emit(System.Reflection.Emit.OpCodes.Castclreplaced, sig.RetType);

            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

            return dm;
        }

19 View Source File : TypeExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TArg, TRes> CreateFunc<TArg, TRes>(TypeInfo callInfo, string methodName, TypeInfo argInfo, TypeInfo resInfo)
        {
            var typeConstructor = resInfo.GetConstructor(Type.EmptyTypes);
            if (typeConstructor == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有无参构造函数");
            var innerMethod = callInfo.GetMethod(methodName);
            if (innerMethod == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有名称为{methodName}的方法");
            if (innerMethod.ReturnType != resInfo)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}返回值不为{resInfo.FullName}");
            var args = innerMethod.GetParameters();
            if (args.Length != 1)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}参数不是一个");
            if (args[0].ParameterType != argInfo)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}唯一参数不为{argInfo.FullName}");
            //构造匿名方法
            var callMethod = new DynamicMethod(methodName, typeof(TRes), new[] { typeof(TArg) });
            //构造动态IL(方法内部实现)
            var il = callMethod.GetILGenerator();
            il.Emit(OpCodes.Nop);
            //1 参数类型转换
            il.Emit(OpCodes.Ldarg, 0);
            il.Emit(OpCodes.Castclreplaced, argInfo);
            var arg = il.DeclareLocal(argInfo);
            il.Emit(OpCodes.Stloc, arg);
            //2 调用对象构造
            il.Emit(OpCodes.Newobj, typeConstructor);
            var call = il.DeclareLocal(callInfo);
            il.Emit(OpCodes.Stloc, call);
            //3 方法调用
            il.Emit(OpCodes.Ldloc, call);
            il.Emit(OpCodes.Ldloc, arg);
            il.Emit(OpCodes.Callvirt, innerMethod);
            var ret = il.DeclareLocal(innerMethod.ReturnType);
            //4 返回值转换
            il.Emit(OpCodes.Stloc, ret);
            il.Emit(OpCodes.Ldloc, ret);
            il.Emit(OpCodes.Castclreplaced, typeof(TRes).GetTypeInfo());
            var res = il.DeclareLocal(resInfo);
            //5 返回
            il.Emit(OpCodes.Stloc, res);
            il.Emit(OpCodes.Ldloc, res);
            il.Emit(OpCodes.Ret);
            //返回动态委托
            return callMethod.CreateDelegate(typeof(Func<TArg, TRes>)) as Func<TArg, TRes>;
        }

19 View Source File : TypeExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TRes> CreateFunc<TRes>(TypeInfo callInfo, string methodName, TypeInfo resInfo)
        {
            var typeConstructor = resInfo.GetConstructor(Type.EmptyTypes);
            if (typeConstructor == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有无参构造函数");
            var innerMethod = callInfo.GetMethod(methodName);
            if (innerMethod == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有名称为{methodName}的方法");
            if (innerMethod.ReturnType != resInfo)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}返回值不为{resInfo.FullName}");
            var args = innerMethod.GetParameters();
            if (args.Length > 0)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}参数不为空");
            //构造匿名方法
            var callMethod = new DynamicMethod(methodName, typeof(TRes), null);
            //构造动态IL(方法内部实现)
            var il = callMethod.GetILGenerator();
            il.Emit(OpCodes.Nop);
            //1 调用对象构造
            il.Emit(OpCodes.Newobj, typeConstructor);
            var call = il.DeclareLocal(callInfo);
            il.Emit(OpCodes.Stloc, call);
            //3 方法调用
            il.Emit(OpCodes.Ldloc, call);
            il.Emit(OpCodes.Callvirt, innerMethod);
            var ret = il.DeclareLocal(innerMethod.ReturnType);
            //4 返回值转换
            il.Emit(OpCodes.Stloc, ret);
            il.Emit(OpCodes.Ldloc, ret);
            il.Emit(OpCodes.Castclreplaced, typeof(TRes).GetTypeInfo());
            var res = il.DeclareLocal(resInfo);
            //5 返回
            il.Emit(OpCodes.Stloc, res);
            il.Emit(OpCodes.Ldloc, res);
            il.Emit(OpCodes.Ret);
            //返回动态委托
            return callMethod.CreateDelegate(typeof(Func<TRes>)) as Func<TRes>;
        }

19 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TRes> CreateFunc<TRes>(TypeInfo callInfo, string methodName, TypeInfo resInfo)
        {
            ConstructorInfo constructor = callInfo.GetConstructor(Type.EmptyTypes);
            if (constructor == (ConstructorInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有无参构造函数");
            MethodInfo method = callInfo.GetMethod(methodName);
            if (method == (MethodInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有名称为" + methodName + "的方法");
            if (method.ReturnType != (Type)resInfo)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "返回值不为" + resInfo.FullName);
            if ((uint)method.GetParameters().Length > 0U)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "参数不为空");
            DynamicMethod dynamicMethod = new DynamicMethod(methodName, typeof(TRes), (Type[])null);
            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Nop);
            ilGenerator.Emit(OpCodes.Newobj, constructor);
            LocalBuilder local1 = ilGenerator.DeclareLocal((Type)callInfo);
            ilGenerator.Emit(OpCodes.Stloc, local1);
            ilGenerator.Emit(OpCodes.Ldloc, local1);
            ilGenerator.Emit(OpCodes.Callvirt, method);
            LocalBuilder local2 = ilGenerator.DeclareLocal(method.ReturnType);
            ilGenerator.Emit(OpCodes.Stloc, local2);
            ilGenerator.Emit(OpCodes.Ldloc, local2);
            ilGenerator.Emit(OpCodes.Castclreplaced, (Type)typeof(TRes).GetTypeInfo());
            LocalBuilder local3 = ilGenerator.DeclareLocal((Type)resInfo);
            ilGenerator.Emit(OpCodes.Stloc, local3);
            ilGenerator.Emit(OpCodes.Ldloc, local3);
            ilGenerator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<TRes>)) as Func<TRes>;
        }

19 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TArg, TRes> CreateFunc<TArg, TRes>(TypeInfo callInfo, string methodName, TypeInfo argInfo, TypeInfo resInfo)
        {
            ConstructorInfo constructor = callInfo.GetConstructor(Type.EmptyTypes);
            if (constructor == (ConstructorInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有无参构造函数");
            MethodInfo method = callInfo.GetMethod(methodName);
            if (method == (MethodInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有名称为" + methodName + "的方法");
            if (method.ReturnType != (Type)resInfo)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "返回值不为" + resInfo.FullName);
            ParameterInfo[] parameters = method.GetParameters();
            if (parameters.Length != 1)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "参数不是一个");
            if (parameters[0].ParameterType != (Type)argInfo)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "唯一参数不为" + argInfo.FullName);
            DynamicMethod dynamicMethod = new DynamicMethod(methodName, typeof(TRes), new Type[1]
            {
        typeof (TArg)
            });
            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Nop);
            ilGenerator.Emit(OpCodes.Ldarg, 0);
            ilGenerator.Emit(OpCodes.Castclreplaced, (Type)argInfo);
            LocalBuilder local1 = ilGenerator.DeclareLocal((Type)argInfo);
            ilGenerator.Emit(OpCodes.Stloc, local1);
            ilGenerator.Emit(OpCodes.Newobj, constructor);
            LocalBuilder local2 = ilGenerator.DeclareLocal((Type)callInfo);
            ilGenerator.Emit(OpCodes.Stloc, local2);
            ilGenerator.Emit(OpCodes.Ldloc, local2);
            ilGenerator.Emit(OpCodes.Ldloc, local1);
            ilGenerator.Emit(OpCodes.Callvirt, method);
            LocalBuilder local3 = ilGenerator.DeclareLocal(method.ReturnType);
            ilGenerator.Emit(OpCodes.Stloc, local3);
            ilGenerator.Emit(OpCodes.Ldloc, local3);
            ilGenerator.Emit(OpCodes.Castclreplaced, (Type)typeof(TRes).GetTypeInfo());
            LocalBuilder local4 = ilGenerator.DeclareLocal((Type)resInfo);
            ilGenerator.Emit(OpCodes.Stloc, local4);
            ilGenerator.Emit(OpCodes.Ldloc, local4);
            ilGenerator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<TArg, TRes>)) as Func<TArg, TRes>;
        }

19 View Source File : ILGeneratorExtensions.cs
License : MIT License
Project Creator : akaskela

public static void CallMethod(this ILGenerator generator, MethodInfo methodInfo)
        {
            if (methodInfo.IsFinal || !methodInfo.IsVirtual)
            {
                generator.Emit(OpCodes.Call, methodInfo);
            }
            else
            {
                generator.Emit(OpCodes.Callvirt, methodInfo);
            }
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : albahari

public static Func<object, object> GenDynamicProp (PropertyInfo prop)
		{
			//return x => prop.GetValue (x);
			DynamicMethod dynMeth;
			if (prop.DeclaringType.IsInterface)
				dynMeth = new DynamicMethod ("", typeof (object), new[] { typeof (object) });
			else
				dynMeth = new DynamicMethod ("", typeof (object), new[] { typeof (object) }, prop.DeclaringType);
			ILGenerator gen = dynMeth.GetILGenerator ();
			gen.Emit (OpCodes.Ldarg_0);

			if (prop.DeclaringType.IsValueType)
			{
				gen.DeclareLocal (prop.DeclaringType);
				gen.Emit (OpCodes.Unbox_Any, prop.DeclaringType);
				gen.Emit (OpCodes.Stloc_0);
				gen.Emit (OpCodes.Ldloca_S, 0);
				gen.Emit (OpCodes.Call, prop.GetGetMethod (true));
			}
			else
			{
				gen.Emit (OpCodes.Castclreplaced, prop.DeclaringType);
				gen.Emit (OpCodes.Callvirt, prop.GetGetMethod (true));
			}
			if (prop.PropertyType.IsValueType) gen.Emit (OpCodes.Box, prop.PropertyType);
			gen.Emit (OpCodes.Ret);
			return (Func<object, object>)dynMeth.CreateDelegate (typeof (Func<object, object>));
		}

19 View Source File : Instruction.cs
License : MIT License
Project Creator : alexanderkyte

public override void Emit (IEnumerator<WebreplacedemblyInstruction> cursor, ILGenerator ilgen, WebreplacedemblyCodeParser top_level)
		{
			String method;
			switch (Opcode) {
				case 0x28:
					method = "Load32Bitreplacedigned32";
					break;
				case 0x29:
					method = "Load64Bitreplacedigned64";
					break;
				case 0x2a:
					method = "LoadSingle";
					break;
				case 0x2b:
					method = "LoadDouble";
					break;
				case 0x2c:
					method = "LoadSigned8Bitreplacedigned32";
					break;
				case 0x2d:
					method = "LoadUnsigned8Bitreplacedigned32";
					break;
				case 0x2e:
					method = "LoadSigned16Bitreplacedigned32";
					break;
				case 0x2f:
					method = "LoadUnsigned16Bitreplacedigned32";
					break;
				case 0x30:
					method = "LoadSigned8Bitreplacedigned64";
					break;
				case 0x31:
					method = "LoadUnsigned8Bitreplacedigned64";
					break;
				case 0x32:
					method = "LoadSigned16Bitreplacedigned64";
					break;
				case 0x33:
					method = "LoadUnsigned16Bitreplacedigned64";
					break;
				case 0x34:
					method = "LoadSigned32Bitreplacedigned64";
					break;
				case 0x35:
					method = "LoadUnsigned32Bitreplacedigned64";
					break;

				case 0x36:
					method = "Store32BitFrom32";
					break;
				case 0x37:
					method = "Store64BitFrom32";
					break;
				case 0x38:
					method = "StoreSingle";
					break;
				case 0x39:
					method = "StoreDouble";
					break;

				case 0x3a:
					method = "Store8BitFrom32";
					break;
				case 0x3b:
					method = "Store16BitFrom32";
					break;
				case 0x3c:
					method = "Store8BitFrom64";
					break;
				case 0x3d:
					method = "Store16BitFrom64";
					break;
				case 0x3e:
					method = "Store32BitFrom64";
					break;

				case 0x3f:
					method = "CurrentMemory";
					break;
				case 0x40:
					method = "GrowMemory";
					break;
				default:
					throw new Exception (String.Format("Should not be reached: {0:X}", Opcode));
			}

			// Our opcode has an offset to apply to this address on top of the stack
			// FIXME: we ignore alignment
			ilgen.Emit (OpCodes.Ldc_I4, Convert.ToInt32 (offset));
			ilgen.Emit (OpCodes.Add);

			// Now we want to set ourselves up for a call
			var method_info = typeof (WebreplacedemblyModule).GetMethod (method, BindingFlags.Instance | BindingFlags.NonPublic);
			if (method_info == null)
				throw new Exception (String.Format("Could not find {0} in runtime", method));
			var call_types = new List<Type> ();

			foreach (var param_info in method_info.GetParameters ())
				call_types.Add (param_info.ParameterType);

			ShiftThisArgToFront (ilgen, call_types.ToArray ());
			ilgen.Emit(OpCodes.Call, method_info);

			return;
		}

19 View Source File : DynamicEnumResolver.cs
License : Apache License 2.0
Project Creator : allenai

private static TypeInfo BuildType(Type enumType)
        {
            Type underlyingType = Enum.GetUnderlyingType(enumType);
            Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(enumType);

            using (MonoProtection.EnterRefEmitLock())
            {
                TypeBuilder typeBuilder = Dynamicreplacedembly.Value.DefineType("MessagePack.Formatters." + enumType.FullName.Replace(".", "_") + "Formatter" + Interlocked.Increment(ref nameSequence), TypeAttributes.Public | TypeAttributes.Sealed, null, new[] { formatterType });

                // void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options);
                {
                    MethodBuilder method = typeBuilder.DefineMethod(
                        "Serialize",
                        MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
                        null,
                        new Type[] { typeof(MessagePackWriter).MakeByRefType(), enumType, typeof(MessagePackSerializerOptions) });

                    ILGenerator il = method.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Call, typeof(MessagePackWriter).GetRuntimeMethod(nameof(MessagePackWriter.Write), new[] { underlyingType }));
                    il.Emit(OpCodes.Ret);
                }

                // T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options);
                {
                    MethodBuilder method = typeBuilder.DefineMethod(
                        "Deserialize",
                        MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.Virtual,
                        enumType,
                        new Type[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) });

                    ILGenerator il = method.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Call, typeof(MessagePackReader).GetRuntimeMethod("Read" + underlyingType.Name, Type.EmptyTypes));
                    il.Emit(OpCodes.Ret);
                }

                return typeBuilder.CreateTypeInfo();
            }
        }

19 View Source File : DynamicUnionResolver.cs
License : Apache License 2.0
Project Creator : allenai

private static void BuildSerialize(Type type, UnionAttribute[] infos, MethodBuilder method, FieldBuilder typeToKeyAndJumpMap, ILGenerator il)
        {
            // if(value == null) return WriteNil
            Label elseBody = il.DefineLabel();
            Label notFoundType = il.DefineLabel();

            il.EmitLdarg(2);
            il.Emit(OpCodes.Brtrue_S, elseBody);
            il.Emit(OpCodes.Br, notFoundType);
            il.MarkLabel(elseBody);

            // IFormatterResolver resolver = options.Resolver;
            LocalBuilder localResolver = il.DeclareLocal(typeof(IFormatterResolver));
            il.EmitLdarg(3);
            il.EmitCall(getResolverFromOptions);
            il.EmitStloc(localResolver);

            LocalBuilder keyPair = il.DeclareLocal(typeof(KeyValuePair<int, int>));

            il.EmitLoadThis();
            il.EmitLdfld(typeToKeyAndJumpMap);
            il.EmitLdarg(2);
            il.EmitCall(objectGetType);
            il.EmitCall(getTypeHandle);
            il.EmitLdloca(keyPair);
            il.EmitCall(typeMapDictionaryTryGetValue);
            il.Emit(OpCodes.Brfalse, notFoundType);

            // writer.WriteArrayHeader(2, false);
            il.EmitLdarg(1);
            il.EmitLdc_I4(2);
            il.EmitCall(MessagePackWriterTypeInfo.WriteArrayHeader);

            // writer.Write(keyPair.Key)
            il.EmitLdarg(1);
            il.EmitLdloca(keyPair);
            il.EmitCall(intIntKeyValuePairGetKey);
            il.EmitCall(MessagePackWriterTypeInfo.WriteInt32);

            Label loopEnd = il.DefineLabel();

            // switch-case (offset += resolver.GetFormatter.Serialize(with cast)
            var switchLabels = infos.Select(x => new { Label = il.DefineLabel(), Attr = x }).ToArray();
            il.EmitLdloca(keyPair);
            il.EmitCall(intIntKeyValuePairGetValue);
            il.Emit(OpCodes.Switch, switchLabels.Select(x => x.Label).ToArray());
            il.Emit(OpCodes.Br, loopEnd); // default

            foreach (var item in switchLabels)
            {
                il.MarkLabel(item.Label);
                il.EmitLdloc(localResolver);
                il.Emit(OpCodes.Call, getFormatterWithVerify.MakeGenericMethod(item.Attr.SubType));

                il.EmitLdarg(1);
                il.EmitLdarg(2);
                if (item.Attr.SubType.GetTypeInfo().IsValueType)
                {
                    il.Emit(OpCodes.Unbox_Any, item.Attr.SubType);
                }
                else
                {
                    il.Emit(OpCodes.Castclreplaced, item.Attr.SubType);
                }

                il.EmitLdarg(3);
                il.Emit(OpCodes.Callvirt, getSerialize(item.Attr.SubType));

                il.Emit(OpCodes.Br, loopEnd);
            }

            // return;
            il.MarkLabel(loopEnd);
            il.Emit(OpCodes.Ret);

            // else, return WriteNil
            il.MarkLabel(notFoundType);
            il.EmitLdarg(1);
            il.EmitCall(MessagePackWriterTypeInfo.WriteNil);
            il.Emit(OpCodes.Ret);
        }

19 View Source File : MSILGenerator.cs
License : MIT License
Project Creator : aloneguid

private void GenerateCollector(ILGenerator il, Type clreplacedType,
         DataField f,
         MethodInfo getValueMethod,
         MethodInfo addToListMethod,
         MethodInfo addRepLevelMethod,
         TypeConversion conversion)
      {
         //arg 0 - collection of clreplacedes, clr objects
         //arg 1 - data items (typed list)
         //arg 2 - repereplacedions (optional)
         //arg 3 - max repereplacedion level

         //make collection a local variable
         LocalBuilder collection = il.DeclareLocal(clreplacedType);
         il.Emit(Ldarg_0);
         il.Emit(Stloc, collection.LocalIndex);

         using (il.ForEachLoop(clreplacedType, collection, out LocalBuilder currentElement))
         {
            if (f.IsArray)
            {
               //reset repereplacedion level to 0
               LocalBuilder rl = il.DeclareLocal(typeof(int));
               il.Emit(Ldc_I4_0);
               il.StLoc(rl);

               //currentElement is a nested array in this case
               LocalBuilder array = il.DeclareLocal(typeof(object));

               //get array and put into arrayElement
               il.Emit(Ldloc, currentElement.LocalIndex);
               il.Emit(Callvirt, getValueMethod);
               il.Emit(Stloc, array.LocalIndex);

               //enumerate this array
               using (il.ForEachLoop(f.ClrNullableIfHasNullsType, array, out LocalBuilder arrayElement))
               {
                  //store in destination list
                  il.CallVirt(addToListMethod, Ldarg_1, arrayElement);

                  //add repereplacedion level
                  il.CallVirt(addRepLevelMethod, Ldarg_2, rl);

                  //set repereplacedion level to max
                  il.Emit(Ldarg_3);
                  il.StLoc(rl);
               }
            }
            else
            {
               //hold item
               LocalBuilder item = il.DeclareLocal(f.ClrNullableIfHasNullsType);

               //get current value, converting if necessary
               il.Emit(Ldloc, currentElement.LocalIndex);
               il.Emit(Callvirt, getValueMethod);
               if (conversion != null)
               {
                  conversion.Emit(il);
               }
               il.Emit(Stloc, item.LocalIndex);

               //store in destination list
               il.Emit(Ldarg_1);
               il.Emit(Ldloc, item.LocalIndex);
               il.Emit(Callvirt, addToListMethod);
            }
         }

         il.Emit(Ldc_I4_0);
         il.Emit(Ret);
      }

19 View Source File : MSILGenerator.cs
License : MIT License
Project Creator : aloneguid

private void Generatereplacedigner(ILGenerator il, Type clreplacedType, DataField field,
         MethodInfo setValueMethod,
         MethodInfo getDataMethod,
         MethodInfo getRepsMethod,
         TypeConversion conversion)
      {
         //arg 0 - DataColumn
         //arg 1 - clreplaced intances array (Array)

         if (field.IsArray)
         {
            LocalBuilder repItem = il.DeclareLocal(typeof(int));
            LocalBuilder dce = il.DeclareLocal(typeof(DataColumnEnumerator));

            //we will use DataColumnEnumerator for complex types

            //create an instance of it
            il.Emit(Ldarg_0); //constructor argument
            il.Emit(Newobj, typeof(DataColumnEnumerator).GetTypeInfo().DeclaredConstructors.First());
            il.StLoc(dce);

            LocalBuilder ci = il.DeclareLocal(typeof(int)); //clreplaced index
            LocalBuilder clreplacedInstance = il.DeclareLocal(clreplacedType); //clreplaced instance

            using (il.ForEachLoopFromEnumerator(typeof(object), dce, out LocalBuilder element))
            {
               //element should be an array for simple repeatables

               //get clreplaced instance by index
               il.GetArrayElement(Ldarg_1, ci, true, typeof(Array), clreplacedInstance);

               //replacedign data item to clreplaced property
               il.CallVirt(setValueMethod, clreplacedInstance, element);

               il.Increment(ci);
            }
         }
         else
         {
            //get values
            LocalBuilder data = il.DeclareLocal(typeof(Array));
            il.CallVirt(getDataMethod, Ldarg_0);
            il.StLoc(data);

            //get length of values
            LocalBuilder dataLength = il.DeclareLocal(typeof(int));
            il.GetArrayLength(data, dataLength);

            LocalBuilder dataItem = il.DeclareLocal(field.ClrNullableIfHasNullsType);  //current value
            bool dataIsRef = field.HasNulls && !field.ClrNullableIfHasNullsType.IsSystemNullable();

            LocalBuilder clreplacedInstance = il.DeclareLocal(clreplacedType);

            using (il.ForLoop(dataLength, out LocalBuilder iData))
            {
               //get data value
               il.GetArrayElement(data, iData, dataIsRef, field.ClrNullableIfHasNullsType, dataItem);

               //get clreplaced instance
               il.GetArrayElement(Ldarg_1, iData, true, clreplacedType, clreplacedInstance);

               il.LdLoc(clreplacedInstance);

               //convert if necessary
               if (conversion != null)
               {
                  il.LdLoc(dataItem);
                  conversion.Emit(il);
               }
               else
               {
                  il.Emit(Ldloc, dataItem.LocalIndex);
               }

               //replacedign data item to clreplaced property
               il.Emit(Callvirt, setValueMethod);
            }
         }

         il.Emit(Ret);
      }

19 View Source File : MSILGenerator.cs
License : MIT License
Project Creator : aloneguid

public override void Emit(ILGenerator il)
         {
            il.Emit(OpCodes.Call, method);
         }

19 View Source File : ILExtensions.cs
License : MIT License
Project Creator : aloneguid

public static IDisposable ForEachLoopFromEnumerator(this ILGenerator il, Type elementType, LocalBuilder enumerator, out LocalBuilder currentElement)
      {
         Label lMoveNext = il.DefineLabel();
         Label lWork = il.DefineLabel();
         currentElement = il.DeclareLocal(elementType);

#if DEBUG
         il.EmitWriteLine("foreach-begin");
#endif

         //immediately move to "move next" to start enumeration
         il.Emit(Br, lMoveNext);

         //iteration work block
         il.MarkLabel(lWork);
#if DEBUG
         il.EmitWriteLine("  foreach-loop");
#endif

         //get current element
         il.Emit(Ldloc, enumerator.LocalIndex);
         il.Emit(Callvirt, getCurrentMethod);
         il.Emit(Unbox_Any, elementType);
         il.Emit(Stloc, currentElement.LocalIndex);

         return il.After(() =>
         {
            //"move next" block
            il.MarkLabel(lMoveNext);
            il.Emit(Ldloc, enumerator.LocalIndex);  //load enumerator as an argument
            il.Emit(Callvirt, moveNextMethod);
            il.Emit(Brtrue, lWork);   //if result is true, go to lWork

            //otherwise, dispose enumerator and exit
            //il.Emit(Ldloc, enumerator.LocalIndex);
            //il.Emit(Callvirt, disposeMethod);
#if DEBUG
            il.EmitWriteLine("foreach-end");
#endif
         });
      }

19 View Source File : ILExtensions.cs
License : MIT License
Project Creator : aloneguid

public static IDisposable ForEachLoop(this ILGenerator il, Type elementType, LocalBuilder collection, out LocalBuilder currentElement)
      {
         Label lMoveNext = il.DefineLabel();
         Label lWork = il.DefineLabel();
         currentElement = il.DeclareLocal(elementType);

         //get collection enumerator
         LocalBuilder enumerator = il.DeclareLocal(typeof(IEnumerator));
#if DEBUG
         il.EmitWriteLine("foreach-begin");
#endif
         il.Emit(Ldloc, collection.LocalIndex);
         il.Emit(Callvirt, getEnumeratorMethod);
         il.Emit(Stloc, enumerator.LocalIndex);

         //immediately move to "move next" to start enumeration
         il.Emit(Br, lMoveNext);

         //iteration work block
         il.MarkLabel(lWork);
#if DEBUG
         il.EmitWriteLine("  foreach-loop");
#endif

         //get current element
         il.Emit(Ldloc, enumerator.LocalIndex);
         il.Emit(Callvirt, getCurrentMethod);
         il.Emit(Unbox_Any, elementType);
         il.Emit(Stloc, currentElement.LocalIndex);

         return il.After(() =>
         {
            //"move next" block
            il.MarkLabel(lMoveNext);
            il.Emit(Ldloc, enumerator.LocalIndex);  //load enumerator as an argument
            il.Emit(Callvirt, moveNextMethod);
            il.Emit(Brtrue, lWork);   //if result is true, go to lWork

            //otherwise, dispose enumerator and exit
            //il.Emit(Ldloc, enumerator.LocalIndex);
            //il.Emit(Callvirt, disposeMethod);
#if DEBUG
            il.EmitWriteLine("foreach-end");
#endif
         });
      }

19 View Source File : ILExtensions.cs
License : MIT License
Project Creator : aloneguid

public static void CallVirt(this ILGenerator il, MethodInfo method, params object[] parameters)
      {
         if(parameters != null)
         {
            foreach(object param in parameters)
            {
               switch (param)
               {
                  case OpCode oc:
                     il.Emit(oc);
                     break;
                  case LocalBuilder lb:
                     il.Emit(Ldloc, lb.LocalIndex);
                     break;
                  default:
                     throw new NotSupportedException("don't know how to treat parameter " + param?.GetType());
               }
            }
         }

         il.Emit(Callvirt, method);
      }

19 View Source File : InterfaceProxyBuilder.cs
License : MIT License
Project Creator : amazingalek

private void CreateProxyMethodBody(MethodBuilder methodBuilder, MethodInfo target, FieldBuilder instanceField, Type[] argTypes)
		{
			var il = methodBuilder.GetILGenerator();

			// load target instance
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldfld, instanceField);

			// invoke target method on instance
			for (var i = 0; i < argTypes.Length; i++)
			{
				il.Emit(OpCodes.Ldarg, i + 1);
			}
			il.Emit(OpCodes.Call, target);

			// return result
			il.Emit(OpCodes.Ret);
		}

19 View Source File : Accessor.cs
License : MIT License
Project Creator : andruzzzhka

private static (Getter, Setter) MakeAccessors(string propName)
        {
            var prop = typeof(T).GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            if (prop == null)
                throw new MissingMemberException(typeof(T).Name, propName);

            var getM = prop.GetGetMethod(true);
            var setM = prop.GetSetMethod(true);
            Getter getter = null;
            Setter setter = null;

            if (typeof(T).IsValueType)
            {
                if (getM != null)
                    getter = (Getter)Delegate.CreateDelegate(typeof(Getter), getM);
                if (setM != null)
                    setter = (Setter)Delegate.CreateDelegate(typeof(Setter), setM);
            }
            else
            {
                if (getM != null)
                {
                    var dyn = new DynamicMethod($"<>_get__{propName}", typeof(U), new[] { typeof(T).MakeByRefType() }, typeof(PropertyAccessor<T, U>), true);
                    var il = dyn.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldind_Ref);
                    il.Emit(OpCodes.Tailcall);
                    il.Emit(getM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, getM);
                    il.Emit(OpCodes.Ret);
                    getter = (Getter)dyn.CreateDelegate(typeof(Getter));
                }
                if (setM != null)
                {
                    var dyn = new DynamicMethod($"<>_set__{propName}", typeof(void), new[] { typeof(T).MakeByRefType(), typeof(U) }, typeof(PropertyAccessor<T, U>), true);
                    var il = dyn.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldind_Ref);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Tailcall);
                    il.Emit(setM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, setM);
                    il.Emit(OpCodes.Ret);
                    setter = (Setter)dyn.CreateDelegate(typeof(Setter));
                }
            }

            return (getter, setter);
        }

19 View Source File : DynamicParameters.cs
License : MIT License
Project Creator : anet-team

public DynamicParameters Output<T>(T target, Expression<Func<T, object>> expression, DbType? dbType = null, int? size = null)
        {
            var failMessage = "Expression must be a property/field chain off of a(n) {0} instance";
            failMessage = string.Format(failMessage, typeof(T).Name);
            Action @throw = () => throw new InvalidOperationException(failMessage);

            // Is it even a MemberExpression?
            var lastMemberAccess = expression.Body as MemberExpression;

            if (lastMemberAccess == null
                || (!(lastMemberAccess.Member is PropertyInfo)
                    && !(lastMemberAccess.Member is FieldInfo)))
            {
                if (expression.Body.NodeType == ExpressionType.Convert
                    && expression.Body.Type == typeof(object)
                    && ((UnaryExpression)expression.Body).Operand is MemberExpression)
                {
                    // It's got to be unboxed
                    lastMemberAccess = (MemberExpression)((UnaryExpression)expression.Body).Operand;
                }
                else
                {
                    @throw();
                }
            }

            // Does the chain consist of MemberExpressions leading to a ParameterExpression of type T?
            MemberExpression diving = lastMemberAccess;
            // Retain a list of member names and the member expressions so we can rebuild the chain.
            List<string> names = new List<string>();
            List<MemberExpression> chain = new List<MemberExpression>();

            do
            {
                // Insert the names in the right order so expression
                // "Post.Author.Name" becomes parameter "PostAuthorName"
                names.Insert(0, diving?.Member.Name);
                chain.Insert(0, diving);

                var constant = diving?.Expression as ParameterExpression;
                diving = diving?.Expression as MemberExpression;

                if (constant != null && constant.Type == typeof(T))
                {
                    break;
                }
                else if (diving == null
                    || (!(diving.Member is PropertyInfo)
                        && !(diving.Member is FieldInfo)))
                {
                    @throw();
                }
            }
            while (diving != null);

            var dynamicParamName = string.Concat(names.ToArray());

            // Before we get all emitty...
            var lookup = string.Join("|", names.ToArray());

            var cache = CachedOutputSetters<T>.Cache;
            var setter = (Action<object, DynamicParameters>)cache[lookup];
            if (setter != null) goto MAKECALLBACK;

            // Come on let's build a method, let's build it, let's build it now!
            var dm = new DynamicMethod("ExpressionParam" + Guid.NewGuid().ToString(), null, new[] { typeof(object), GetType() }, true);
            var il = dm.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0); // [object]
            il.Emit(OpCodes.Castclreplaced, typeof(T));    // [T]

            // Count - 1 to skip the last member access
            var i = 0;
            for (; i < (chain.Count - 1); i++)
            {
                var member = chain[0].Member;

                if (member is PropertyInfo)
                {
                    var get = ((PropertyInfo)member).GetGetMethod(true);
                    il.Emit(OpCodes.Callvirt, get); // [Member{i}]
                }
                else // Else it must be a field!
                {
                    il.Emit(OpCodes.Ldfld, (FieldInfo)member); // [Member{i}]
                }
            }

            var paramGetter = GetType().GetMethod("Get", new Type[] { typeof(string) }).MakeGenericMethod(lastMemberAccess.Type);

            il.Emit(OpCodes.Ldarg_1); // [target] [DynamicParameters]
            il.Emit(OpCodes.Ldstr, dynamicParamName); // [target] [DynamicParameters] [ParamName]
            il.Emit(OpCodes.Callvirt, paramGetter); // [target] [value], it's already typed thanks to generic method

            // GET READY
            var lastMember = lastMemberAccess.Member;
            if (lastMember is PropertyInfo)
            {
                var set = ((PropertyInfo)lastMember).GetSetMethod(true);
                il.Emit(OpCodes.Callvirt, set); // SET
            }
            else
            {
                il.Emit(OpCodes.Stfld, (FieldInfo)lastMember); // SET
            }

            il.Emit(OpCodes.Ret); // GO

            setter = (Action<object, DynamicParameters>)dm.CreateDelegate(typeof(Action<object, DynamicParameters>));
            lock (cache)
            {
                cache[lookup] = setter;
            }

            // Queue the preparation to be fired off when adding parameters to the DbCommand
            MAKECALLBACK:
            (outputCallbacks ?? (outputCallbacks = new List<Action>())).Add(() =>
            {
                // Finally, prep the parameter and attach the callback to it
                var targetMemberType = lastMemberAccess?.Type;
                int sizeToSet = (!size.HasValue && targetMemberType == typeof(string)) ? DbString.DefaultLength : size ?? 0;

                if (parameters.TryGetValue(dynamicParamName, out ParamInfo parameter))
                {
                    parameter.ParameterDirection = parameter.AttachedParam.Direction = ParameterDirection.InputOutput;

                    if (parameter.AttachedParam.Size == 0)
                    {
                        parameter.Size = parameter.AttachedParam.Size = sizeToSet;
                    }
                }
                else
                {
                    dbType = (!dbType.HasValue)
#pragma warning disable 618
                    ? SqlMapper.LookupDbType(targetMemberType, targetMemberType?.Name, true, out SqlMapper.ITypeHandler handler)
#pragma warning restore 618
                    : dbType;

                    // CameFromTemplate property would not apply here because this new param
                    // Still needs to be added to the command
                    Add(dynamicParamName, expression.Compile().Invoke(target), null, ParameterDirection.InputOutput, sizeToSet);
                }

                parameter = parameters[dynamicParamName];
                parameter.OutputCallback = setter;
                parameter.OutputTarget = target;
            });

            return this;
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : AutoFixture

private static void BuildMethodGetHashCode<TDestination>(TypeBuilder type)
        {
            var methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
            MethodBuilder method = type.DefineMethod("GetHashCode", methodAttributes);
            method.SetReturnType(typeof(int));

            int derivedGetHashCode = 135;
            MethodInfo getHashCode = typeof(TDestination).GetTypeInfo().GetMethod(
                "GetHashCode",
                Type.EmptyTypes
            );

            ILGenerator gen = method.GetILGenerator();
            gen.DeclareLocal(typeof(int));
            
            Label label = gen.DefineLabel();
            
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Call, getHashCode);
            gen.Emit(OpCodes.Ldc_I4, derivedGetHashCode);
            gen.Emit(OpCodes.Add);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label);
            gen.MarkLabel(label);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : AutoFixture

private static void BuildMethodEquals(TypeBuilder type, FieldInfo equalsHasBeenCalled, FieldInfo comparer)
        {
            var methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
            MethodBuilder method = type.DefineMethod("Equals", methodAttributes);

            MethodInfo objectEquals = typeof(object).GetTypeInfo().GetMethod(
                "Equals",
                new[] {typeof(object)}
            );

            MethodInfo equalityComparerEquals = typeof(IEqualityComparer).GetTypeInfo().GetMethod(
                "Equals",
                new[] {typeof(object), typeof(object)}
            );
            
            method.SetReturnType(typeof(bool));
            method.SetParameters(typeof(object));
            method.DefineParameter(1, ParameterAttributes.None, "obj");
            
            ILGenerator gen = method.GetILGenerator();
            gen.DeclareLocal(typeof(bool));
            gen.DeclareLocal(typeof(bool));
            
            Label label1 = gen.DefineLabel();
            Label label2 = gen.DefineLabel();

            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, equalsHasBeenCalled);
            gen.Emit(OpCodes.Ldc_I4_0);
            gen.Emit(OpCodes.Ceq);
            gen.Emit(OpCodes.Stloc_1);
            gen.Emit(OpCodes.Ldloc_1);
            gen.Emit(OpCodes.Brtrue_S, label1);
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldc_I4_0);
            gen.Emit(OpCodes.Stfld, equalsHasBeenCalled);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Call, objectEquals);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label2);
            gen.MarkLabel(label1);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldc_I4_1);
            gen.Emit(OpCodes.Stfld, equalsHasBeenCalled);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, comparer);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Callvirt, equalityComparerEquals);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label2);
            gen.MarkLabel(label2);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : AutoFixture

private static void BuildMethodEquals(TypeBuilder type, FieldInfo comparer)
        {
            var methodAttributes = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig;
            MethodBuilder method = type.DefineMethod("Equals", methodAttributes);

            MethodInfo equals = typeof(object).GetTypeInfo().GetMethod(
                "Equals",
                new[] {typeof(object)}
            );

            method.SetReturnType(typeof(bool));
            method.SetParameters(typeof(object));

            ILGenerator gen = method.GetILGenerator();
            gen.DeclareLocal(typeof(bool));

            var label = gen.DefineLabel();

            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldfld, comparer);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(OpCodes.Callvirt, equals);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, label);
            gen.MarkLabel(label);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
        }

19 View Source File : SqlMapperExtensions.cs
License : MIT License
Project Creator : ay2015

private static void CreateProperty<T>(TypeBuilder typeBuilder, string propertyName, Type propType, MethodInfo setIsDirtyMethod, bool isIdenreplacedy)
			{
				FieldBuilder field = typeBuilder.DefineField("_" + propertyName, propType, FieldAttributes.Private);
				PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, propType, new Type[1]
				{
					propType
				});
				MethodBuilder methodBuilder = typeBuilder.DefineMethod("get_" + propertyName, MethodAttributes.FamANDreplacedem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig, propType, Type.EmptyTypes);
				ILGenerator iLGenerator = methodBuilder.GetILGenerator();
				iLGenerator.Emit(OpCodes.Ldarg_0);
				iLGenerator.Emit(OpCodes.Ldfld, field);
				iLGenerator.Emit(OpCodes.Ret);
				MethodBuilder methodBuilder2 = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.FamANDreplacedem | MethodAttributes.Family | MethodAttributes.Virtual | MethodAttributes.HideBySig, null, new Type[1]
				{
					propType
				});
				ILGenerator iLGenerator2 = methodBuilder2.GetILGenerator();
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldarg_1);
				iLGenerator2.Emit(OpCodes.Stfld, field);
				iLGenerator2.Emit(OpCodes.Ldarg_0);
				iLGenerator2.Emit(OpCodes.Ldc_I4_1);
				iLGenerator2.Emit(OpCodes.Call, setIsDirtyMethod);
				iLGenerator2.Emit(OpCodes.Ret);
				if (isIdenreplacedy)
				{
					CustomAttributeBuilder customAttribute = new CustomAttributeBuilder(typeof(KeyAttribute).GetConstructor(new Type[0]), new object[0]);
					propertyBuilder.SetCustomAttribute(customAttribute);
				}
				propertyBuilder.SetGetMethod(methodBuilder);
				propertyBuilder.SetSetMethod(methodBuilder2);
				MethodInfo method = typeof(T).GetMethod("get_" + propertyName);
				MethodInfo method2 = typeof(T).GetMethod("set_" + propertyName);
				typeBuilder.DefineMethodOverride(methodBuilder, method);
				typeBuilder.DefineMethodOverride(methodBuilder2, method2);
			}

19 View Source File : ReferenceHelpers.cs
License : MIT License
Project Creator : badamczewski

public static Action<object, Action<IntPtr>> GetPinnedPointerInit()
        {
            var dyn = new DynamicMethod("GetPinnedPtr", typeof(void), new[] { typeof(object), typeof(Action<IntPtr>) }, typeof(ReferenceHelpers).Module);
            var il = dyn.GetILGenerator();
            il.DeclareLocal(typeof(object), true);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Stloc_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Conv_I);
            il.Emit(OpCodes.Call, typeof(Action<IntPtr>).GetMethod("Invoke"));
            il.Emit(OpCodes.Ret);
            return (Action<object, Action<IntPtr>>)dyn.CreateDelegate(typeof(Action<object, Action<IntPtr>>));
        }

See More Examples