Example #1
0
        public void InvalidFilterBlock1()
        {
            DefineBasicMethod();
            ILGenerator il = il_gen;

            il.BeginExceptionBlock();
            il.BeginExceptFilterBlock();
            il.EndExceptionBlock();
        }
Example #2
0
        /// <summary>
        /// Aspect code to inject at the beginning of weaved method
        /// </summary>
        /// <param name="typeBuilder">Type Builder</param>
        /// <param name="method">Method</param>
        /// <param name="parameter">Parameter</param>
        /// <param name="il">ILGenerator</param>
        internal void BeginAspectBlock(TypeBuilder typeBuilder, MethodBase method, ParameterInfo parameter, ILGenerator il)
        {
            var meth       = method as MethodInfo;
            var returnType = meth.ReturnType;

            exLocal = returnType != typeof(void) ? il.DeclareLocal(returnType) : null;

            il.BeginExceptionBlock();
        }
Example #3
0
        public void BeginExceptionBlock()
        {
            TypeBuilder   type      = Helpers.DynamicType(TypeAttributes.NotPublic);
            MethodBuilder method    = type.DefineMethod("TestMethod", MethodAttributes.Public | MethodAttributes.Static);
            ILGenerator   generator = method.GetILGenerator();

            generator.BeginExceptionBlock();
            VerifyDeclareLocal(generator);
        }
Example #4
0
        public void TestExceptionEmitCalls()
        {
            AssemblyName    myAsmName = new AssemblyName("AdderExceptionAsm");
            AssemblyBuilder myAsmBldr = AssemblyBuilder.DefineDynamicAssembly(myAsmName, AssemblyBuilderAccess.Run);

            ModuleBuilder myModBldr  = TestLibrary.Utilities.GetModuleBuilder(myAsmBldr, "Module1");
            TypeBuilder   myTypeBldr = myModBldr.DefineType("Adder");

            MethodBuilder methodBuilder = myTypeBldr.DefineMethod("DoThrow",
                                                                  MethodAttributes.Public |
                                                                  MethodAttributes.Static,
                                                                  typeof(int), new Type[] { typeof(bool) });

            ILGenerator ilgen    = methodBuilder.GetILGenerator();
            Type        overflow = typeof(OverflowException);

            LocalBuilder tmp1      = ilgen.DeclareLocal(typeof(int));
            Label        dontThrow = ilgen.DefineLabel();

            // Begin the try block.
            Label exBlock = ilgen.BeginExceptionBlock();

            ilgen.Emit(OpCodes.Ldarg_0);
            ilgen.Emit(OpCodes.Brfalse_S, dontThrow);
            // Throw the exception now on the stack.
            ilgen.ThrowException(overflow);
            ilgen.MarkLabel(dontThrow);

            // Start the catch block for OverflowException.
            ilgen.BeginCatchBlock(overflow);

            // Since our function has to return an integer value, we'll load -1 onto
            // the stack to indicate an error, and store it in local variable tmp1.
            //
            ilgen.Emit(OpCodes.Ldc_I4_M1);
            ilgen.Emit(OpCodes.Stloc_S, tmp1);

            // End the exception handling block.

            ilgen.EndExceptionBlock();

            // Return
            ilgen.Emit(OpCodes.Ldloc_S, tmp1);
            ilgen.Emit(OpCodes.Ret);

            Type       createdType = myTypeBldr.CreateTypeInfo().AsType();
            MethodInfo md          = createdType.GetMethod("DoThrow");

            // Throw
            int ret = (int)md.Invoke(null, new object[] { true });

            Assert.Equal(-1, ret);

            // Don't Throw
            ret = (int)md.Invoke(null, new object[] { false });
            Assert.Equal(0, ret);
        }
Example #5
0
        public static void EmitTryFinally(this ILGenerator il, Action tryBody, Action finallyBody)
        {
            var block = il.BeginExceptionBlock();

            tryBody();
            il.Emit(OpCodes.Leave_S, block);
            il.BeginFinallyBlock();
            finallyBody();
            il.EndExceptionBlock();
        }
        [Test]         // bug #81431
        public void FilterAndCatchBlock()
        {
            DefineBasicMethod();
            ILGenerator il = il_gen;

            il.BeginExceptionBlock();
            il.BeginExceptFilterBlock();
            il.BeginCatchBlock(null);
            il.BeginCatchBlock(typeof(SystemException));
        }
        public override CodeNode VisitTryFinallyNode(TryFinallyNode node)
        {
            ILGen.BeginExceptionBlock();
            Visit(node.TryNode);
            ILGen.BeginFinallyBlock();
            Visit(node.FinallyNode);
            ILGen.EndExceptionBlock();

            return(node);
        }
Example #8
0
        internal static void EmitExceptionBlock(ILGenerator il, CodeInstruction ci)
        {
            if (ci.startException > 0)
            {
                for (int i = 0; i < ci.startException; i++)
                {
                    if (HarmonyInstance.DEBUG)
                    {
                        FileLog.Log("try {\n");
                    }
                    il.BeginExceptionBlock();
                }
            }

            if (ci.endException > 0)
            {
                for (int i = 0; i < ci.endException; i++)
                {
                    if (HarmonyInstance.DEBUG)
                    {
                        FileLog.Log("}\n");
                    }
                    il.EndExceptionBlock();
                }
            }

            if (ci.isStartCatch)
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("} // try");

                    String catchLog = "catch ";

                    if (ci.catchType != null)
                    {
                        catchLog += "(" + ci.catchType.ToString() + ")";
                    }

                    FileLog.Log(catchLog + " {");
                }

                il.BeginCatchBlock(ci.catchType);
            }
            else if (ci.isStartFinally)
            {
                if (HarmonyInstance.DEBUG)
                {
                    FileLog.Log("} // try");
                    FileLog.Log("finally { ");
                }

                il.BeginFinallyBlock();
            }
        }
Example #9
0
        private void InitSerializePropertiesDelegate(Type type)
        {
            Dictionary <string, MemberInfo> properties = HproseHelper.GetProperties(type);
            DynamicMethod dynamicMethod = new DynamicMethod("$SerializeProperties",
                                                            typeofVoid,
                                                            typeofArgs,
                                                            type,
                                                            true);
            ILGenerator  gen   = dynamicMethod.GetILGenerator();
            LocalBuilder value = gen.DeclareLocal(typeofObject);
            LocalBuilder e     = gen.DeclareLocal(typeofException);

            foreach (KeyValuePair <string, MemberInfo> property in properties)
            {
                PropertyInfo propertyInfo = (PropertyInfo)property.Value;
                Label        exTryCatch   = gen.BeginExceptionBlock();
                if (type.IsValueType)
                {
                    gen.Emit(OpCodes.Ldarg_0);
                    gen.Emit(OpCodes.Unbox, type);
                }
                else
                {
                    gen.Emit(OpCodes.Ldarg_0);
                }
                MethodInfo getMethod = propertyInfo.GetGetMethod();
                if (getMethod.IsVirtual)
                {
                    gen.Emit(OpCodes.Callvirt, getMethod);
                }
                else
                {
                    gen.Emit(OpCodes.Call, getMethod);
                }
                if (propertyInfo.PropertyType.IsValueType)
                {
                    gen.Emit(OpCodes.Box, propertyInfo.PropertyType);
                }
                gen.Emit(OpCodes.Stloc_S, value);
                gen.Emit(OpCodes.Leave_S, exTryCatch);
                gen.BeginCatchBlock(typeofException);
                gen.Emit(OpCodes.Stloc_S, e);
                gen.Emit(OpCodes.Ldstr, "The property value can\'t be serialized.");
                gen.Emit(OpCodes.Ldloc_S, e);
                gen.Emit(OpCodes.Newobj, hproseExceptionCtor);
                gen.Emit(OpCodes.Throw);
                gen.Emit(OpCodes.Leave_S, exTryCatch);
                gen.EndExceptionBlock();
                gen.Emit(OpCodes.Ldarg_1);
                gen.Emit(OpCodes.Ldloc_S, value);
                gen.Emit(OpCodes.Call, serializeMethod);
            }
            gen.Emit(OpCodes.Ret);
            serializePropertiesDelegate = (SerializeDelegate)dynamicMethod.CreateDelegate(typeofSerializeDelegate);
        }
Example #10
0
        /// <summary>
        /// Generate the contents of the method. This will generate:
        /// ...
        /// try
        ///	{
        ///		return Proxy.MethodName(arg1, arg2);
        ///	}
        ///	catch
        ///	{
        ///		CloseProxyBecauseOfException();
        ///		throw;
        ///	}
        /// ...
        /// </summary>
        /// <param name="method"></param>
        /// <param name="parameterTypes"></param>
        /// <param name="iLGenerator"></param>
        protected override void GenerateMethodImpl(MethodInfo method, Type[] parameterTypes, ILGenerator iLGenerator)
        {
            bool hasReturn = !IsVoidMethod(method);

            if (hasReturn)
            {
                // declare a variable to contain the return type
                // string returnValue;
                iLGenerator.DeclareLocal(method.ReturnType);
            }

            // try {
            Label tryLabel = iLGenerator.BeginExceptionBlock();

            {
                // this
                iLGenerator.Emit(OpCodes.Ldarg_0);

                // Get the details Property of the ClientBase
                MethodInfo proxyProperty = GetMethodFromBaseClass("get_Proxy");
                // Get the channel: "base.Channel<TInterface>."
                iLGenerator.EmitCall(OpCodes.Call, proxyProperty, null);

                // Prepare the parameters for the call
                ParameterInfo[] parameters = method.GetParameters();
                for (int index = 0; index < parameterTypes.Length; index++)
                {
                    iLGenerator.Emit(OpCodes.Ldarg, (((short)index) + 1));
                }

                // Call the Proxy via the interface
                iLGenerator.Emit(OpCodes.Callvirt, method);

                if (hasReturn)
                {
                    // returnValue = result of the function call
                    iLGenerator.Emit(OpCodes.Stloc_0);
                }
            }
            // catch {
            {
                GenerateStandardCatch(iLGenerator);
            }
            // }
            iLGenerator.EndExceptionBlock();

            if (hasReturn)
            {
                // return returnValue;
                iLGenerator.Emit(OpCodes.Ldloc_0);
            }

            // Thanks, all done
            iLGenerator.Emit(OpCodes.Ret);
        }
Example #11
0
        private void EmitMethod(TypeBuilder typeBuilder)
        {
            MethodBuilder mapMethod = typeBuilder.DefineMethod("Map", MethodAttributes.Public | MethodAttributes.Virtual, typeof(void), new[] { typeof(IEnumerable) });

            ILGenerator  il         = mapMethod.GetILGenerator();
            LocalBuilder result     = il.DeclareLocal(typeof(List <int>));  //0
            LocalBuilder item       = il.DeclareLocal(typeof(object));      //1
            LocalBuilder enumeartor = il.DeclareLocal(typeof(IEnumerator)); //2
            LocalBuilder dispose    = il.DeclareLocal(typeof(IDisposable)); //3

            Label labelWhile      = il.DefineLabel();
            Label labelReturn     = il.DefineLabel();
            Label labelMoveNext   = il.DefineLabel();
            Label labelEndFinally = il.DefineLabel();

            //Create result List
            ConstructorInfo constructorInfo = (typeof(List <int>).GetConstructor(Type.EmptyTypes));

            il.Emit(OpCodes.Newobj, constructorInfo);
            il.Emit(OpCodes.Stloc_0, result);

            il.Emit(OpCodes.Ldarg_1);
            il.EmitCall(OpCodes.Callvirt, typeof(IEnumerable).GetMethod("GetEnumerator"), Type.EmptyTypes);
            il.Emit(OpCodes.Stloc_2, enumeartor);

            il.BeginExceptionBlock();
            il.Emit(OpCodes.Br_S, labelMoveNext);
            il.MarkLabel(labelWhile);

            il.Emit(OpCodes.Ldloc_2);
            il.EmitCall(OpCodes.Callvirt, typeof(IEnumerator).GetProperty("Current").GetGetMethod(), Type.EmptyTypes);
            il.Emit(OpCodes.Stloc_1, item);

            il.MarkLabel(labelMoveNext);
            il.Emit(OpCodes.Ldloc_2);
            il.EmitCall(OpCodes.Callvirt, typeof(IEnumerator).GetMethod("MoveNext"), Type.EmptyTypes);
            il.Emit(OpCodes.Brtrue_S, labelWhile);

            il.BeginFinallyBlock();

            il.Emit(OpCodes.Ldloc_2);
            il.Emit(OpCodes.Isinst, typeof(IDisposable));
            il.Emit(OpCodes.Stloc_3, dispose);
            il.Emit(OpCodes.Ldloc_3);
            il.Emit(OpCodes.Brfalse_S, labelEndFinally);

            il.Emit(OpCodes.Ldloc_3);
            il.EmitCall(OpCodes.Callvirt, typeof(IDisposable).GetMethod("Dispose"), Type.EmptyTypes);

            il.MarkLabel(labelEndFinally);
            il.EndExceptionBlock();

            il.MarkLabel(labelReturn);
            il.Emit(OpCodes.Ret);
        }
Example #12
0
        private static void BuildAssembly(string sourceCode, string assemblyFilePath)
        {
            AssemblyName    assemblyName    = new AssemblyName("Temp");
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Save, Path.GetDirectoryName(assemblyFilePath));
            ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(assemblyName.Name, Path.GetFileName(assemblyFilePath));
            TypeBuilder     typeBuilder     = moduleBuilder.DefineType("Application", TypeAttributes.NotPublic | TypeAttributes.Sealed);
            MethodBuilder   methodBuilder   = typeBuilder.DefineMethod("Main", MethodAttributes.Private | MethodAttributes.Static, typeof(void), Type.EmptyTypes);
            ILGenerator     generator       = methodBuilder.GetILGenerator();

            generator.BeginExceptionBlock();
            using (StringReader reader = new StringReader(sourceCode))
            {
                MagnetoCompiler.Compile(MagnetoApplication.Current.ModuleManager, reader, generator);
            }
            generator.BeginCatchBlock(typeof(Exception));
            generator.Emit(OpCodes.Callvirt, exceptionMessageGetter);
            generator.Emit(OpCodes.Ldc_I4, (int)ConsoleColor.Red);
            generator.Emit(OpCodes.Call, foregroundColorSetter);
            generator.Emit(OpCodes.Ldstr, "");
            generator.Emit(OpCodes.Call, consoleWriteLineMethod);
            generator.Emit(OpCodes.Call, consoleWriteLineMethod);
            generator.BeginFinallyBlock();
            generator.Emit(OpCodes.Ldc_I4, (int)ConsoleColor.Cyan);
            generator.Emit(OpCodes.Call, foregroundColorSetter);
            generator.Emit(OpCodes.Ldstr, "");
            generator.Emit(OpCodes.Call, consoleWriteLineMethod);
            generator.Emit(OpCodes.Ldstr, "Finished: press <Enter> to exit.");
            generator.Emit(OpCodes.Call, consoleWriteLineMethod);
            generator.Emit(OpCodes.Call, consoleReadLineMethod);
            generator.EndExceptionBlock();
            generator.Emit(OpCodes.Ret);

            //	Generated code:
            //		try
            //		{
            //			// compiled application code
            //		}
            //		catch(Exception lException)
            //		{
            //			Console.ForegroundColor = ConsoleColor.Red;
            //			Console.WriteLine("");
            //			Console.WriteLine(lException.Message);
            //		}
            //		finally
            //		{
            //			Console.ForegroundColor = ConsoleColor.Cyan;
            //			Console.WriteLine("");
            //			Console.WriteLine("Finished: press <Enter> to exit.");
            //			Console.ReadLine();
            //		}

            typeBuilder.CreateType();
            assemblyBuilder.SetEntryPoint(methodBuilder, PEFileKinds.ConsoleApplication);
            assemblyBuilder.Save(Path.GetFileName(assemblyFilePath));
        }
Example #13
0
        internal override void TranslateToIL(ILGenerator il, Type rtype)
        {
            //This assumes that rtype == Void.class
            this.context.EmitLineInfo(il);
            Globals.ScopeStack.Push(new WithObject(Globals.ScopeStack.Peek(), new JSObject(null, false)));
            bool savedInsideProtectedRegion = compilerGlobals.InsideProtectedRegion;

            compilerGlobals.InsideProtectedRegion = true;
            Label lab = il.DefineLabel();

            compilerGlobals.BreakLabelStack.Push(lab);
            compilerGlobals.ContinueLabelStack.Push(lab);
            this.obj.TranslateToIL(il, Typeob.Object);
            this.EmitILToLoadEngine(il);
            il.Emit(OpCodes.Call, CompilerGlobals.jScriptWithMethod); // JScriptWith returns the with object as an 'Object' (used by the debugger EE)

            // define a local named 'with()' that the debugger EE will use to bind to the with object
            LocalBuilder withObj = null;

            if (context.document.debugOn)
            {
                il.BeginScope(); // used by the debugger to mark a with block
                withObj = il.DeclareLocal(Typeob.Object);
                withObj.SetLocalSymInfo("with()");
                il.Emit(OpCodes.Stloc, withObj);
            }
            else
            {
                il.Emit(OpCodes.Pop);
            }

            il.BeginExceptionBlock();
            this.block.TranslateToILInitializer(il);
            this.block.TranslateToIL(il, Typeob.Void);
            il.BeginFinallyBlock();
            if (context.document.debugOn)
            {
                // null the local used by the debugger EE
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Stloc, withObj);
            }
            this.EmitILToLoadEngine(il);
            il.Emit(OpCodes.Call, CompilerGlobals.popScriptObjectMethod);
            il.Emit(OpCodes.Pop);
            il.EndExceptionBlock();
            if (context.document.debugOn)
            {
                il.EndScope(); // used by the debugger to mark a with block
            }
            il.MarkLabel(lab);
            compilerGlobals.BreakLabelStack.Pop();
            compilerGlobals.ContinueLabelStack.Pop();
            compilerGlobals.InsideProtectedRegion = savedInsideProtectedRegion;
            Globals.ScopeStack.Pop();
        }
Example #14
0
        private void EmitMethod(FieldBuilder innerFieldBuilder, MethodInfo method, TypeBuilder typeBuilder)
        {
            Contract.Requires(method != null);
            Contract.Requires(typeBuilder != null);

            MethodBuilder methodBuilder = typeBuilder.DefineMethod(method.Name, MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, method.ReturnType, method.GetParameters().Select(pi => pi.ParameterType).ToArray());

            ILGenerator il = methodBuilder.GetILGenerator();

            LocalBuilder returnResult = null;

            if (method.ReturnType != typeof(void))
            {
                returnResult = il.DeclareLocal(method.ReturnType);
            }

            LocalBuilder exception   = il.DeclareLocal(typeof(Exception));
            Label        endOfMethod = il.DefineLabel();

            // try block
            il.BeginExceptionBlock();

            // Call OnExecuting method
            this.EmitOnExecutingMethodCall(il);

            // Call method
            EmitInnerMethodCall(method, innerFieldBuilder, il);

            // Call OnExecuted method
            this.EmitOnExecutedMethodCall(il);
            il.Emit(OpCodes.Leave_S, endOfMethod);

            il.BeginCatchBlock(typeof(Exception));

            // Call OnException method
            il.Emit(OpCodes.Stloc_S, exception);
            this.EmitOnExceptionMethodCall(exception, il);

            // re-throw;
            il.Emit(OpCodes.Rethrow);

            il.EndExceptionBlock();

            il.MarkLabel(endOfMethod);
            if (returnResult != null)
            {
                // return returnValue;
                il.Emit(OpCodes.Ldloc_S, returnResult);
            }

            // done
            il.Emit(OpCodes.Ret);
            typeBuilder.DefineMethodOverride(methodBuilder, method);
        }
 public void DefineFilterBodyWithTypeNotNull()
 {
     DefineBasicMethod();
     il_gen.BeginExceptionBlock();
     il_gen.EmitWriteLine("in try");
     il_gen.BeginExceptFilterBlock();
     il_gen.EmitWriteLine("in filter head");
     il_gen.BeginCatchBlock(typeof(Exception));
     il_gen.EmitWriteLine("in filter body");
     il_gen.EndExceptionBlock();
 }
Example #16
0
        private static void ExcptionDeal()
        {
            #region Init

            string          name            = "DynamicExceptionHandler";
            string          fileName        = name + ".dll";
            AssemblyName    asmName         = new AssemblyName(name);
            AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(name, fileName);

            #endregion

            TypeBuilder typeBuilder = moduleBuilder.DefineType("ExceptionHandler", TypeAttributes.Public);

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("ConvertToInt32", MethodAttributes.Public | MethodAttributes.Static, typeof(Int32), new Type[] { typeof(string) });

            ILGenerator  methodIL = methodBuilder.GetILGenerator();
            LocalBuilder num      = methodIL.DeclareLocal(typeof(Int32));

            //int num = 0;
            methodIL.Emit(OpCodes.Ldc_I4_0);
            methodIL.Emit(OpCodes.Stloc_0);

            //begin try
            Label tryLabel = methodIL.BeginExceptionBlock();
            //num = Convert.ToInt32(str);
            methodIL.Emit(OpCodes.Ldarg_0);
            methodIL.Emit(OpCodes.Call, typeof(Convert).GetMethod("ToInt32", new Type[] { typeof(string) }));
            methodIL.Emit(OpCodes.Stloc_0);
            //end try

            //begin catch 注意,这个时侯堆栈顶为异常信息ex
            methodIL.BeginCatchBlock(typeof(Exception));
            //Console.WriteLine(ex.Message);
            methodIL.Emit(OpCodes.Call, typeof(Exception).GetMethod("get_Message"));
            methodIL.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
            //end catch
            methodIL.EndExceptionBlock();

            //return num;
            methodIL.Emit(OpCodes.Ldloc_0);
            methodIL.Emit(OpCodes.Ret);

            Type type = typeBuilder.CreateType();

            assemblyBuilder.Save(fileName);

            object ob = type.GetMethod("ConvertToInt32").Invoke(null, new object[] { "12" });
            Console.WriteLine(ob);
            ob = type.GetMethod("ConvertToInt32").Invoke(null, new object[] { "s12" });
            Console.WriteLine(ob);
        }
        protected override void InitUnserializeDelegate(Type type, string[] names, DynamicMethod dynamicMethod)
        {
            Dictionary <string, PropertyTypeInfo> properties = HproseHelper.GetProperties(type);
            ILGenerator  gen   = dynamicMethod.GetILGenerator();
            LocalBuilder e     = gen.DeclareLocal(typeofException);
            int          count = names.Length;

            for (int i = 0; i < count; ++i)
            {
                PropertyTypeInfo property;
                if (properties.TryGetValue(names[i], out property))
                {
                    Label exTryCatch = gen.BeginExceptionBlock();
                    if (type.IsValueType)
                    {
                        gen.Emit(OpCodes.Ldarg_0);
                        gen.Emit(OpCodes.Unbox, type);
                    }
                    else
                    {
                        gen.Emit(OpCodes.Ldarg_0);
                    }
                    gen.Emit(OpCodes.Ldarg_1);
                    gen.Emit(OpCodes.Ldc_I4, i);
                    gen.Emit(OpCodes.Ldelem_Ref);
                    if (property.type.IsValueType)
                    {
                        gen.Emit(OpCodes.Unbox_Any, property.type);
                    }
                    MethodInfo setMethod = property.info.GetSetMethod(true);
                    if (setMethod.IsVirtual)
                    {
                        gen.Emit(OpCodes.Callvirt, setMethod);
                    }
                    else
                    {
                        gen.Emit(OpCodes.Call, setMethod);
                    }
                    gen.Emit(OpCodes.Leave_S, exTryCatch);
                    gen.BeginCatchBlock(typeofException);
                    gen.Emit(OpCodes.Stloc_S, e);
                    gen.Emit(OpCodes.Ldstr, "The property value can\'t be unserialized.");
                    gen.Emit(OpCodes.Ldloc_S, e);
                    gen.Emit(OpCodes.Newobj, hproseExceptionCtor);
                    gen.Emit(OpCodes.Throw);
                    gen.Emit(OpCodes.Leave_S, exTryCatch);
                    gen.EndExceptionBlock();
                }
            }
            gen.Emit(OpCodes.Ret);
        }
        private void DefineVerifyEntityStateIL(ILGenerator generator, LocalBuilder entityCopy, PropertyInfo propertyInfo, FieldBuilder fieldBuilder)
        {
            var contextType     = typeof(DbContext);
            var entityEntryType = typeof(DbEntityEntry);
            var entityStateType = typeof(EntityState);
            var label           = generator.DefineLabel();

            var methodInfo = contextType.GetMethod("Entry", BindingFlags.Instance | BindingFlags.Public, null, new[] { typeof(object) }, null);
            var localState = generator.DeclareLocal(entityStateType);
            var localValue = generator.DeclareLocal(propertyInfo.PropertyType);

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, fieldBuilder);
            generator.Emit(OpCodes.Call, propertyInfo.GetGetMethod());
            generator.Emit(OpCodes.Stloc, localValue);

            generator.Emit(OpCodes.Ldnull);
            generator.Emit(OpCodes.Ldloc, localValue);
            generator.Emit(OpCodes.Ceq);
            generator.Emit(OpCodes.Brtrue, label);

            generator.BeginExceptionBlock();
            generator.Emit(OpCodes.Ldarg_1);
            generator.Emit(OpCodes.Ldloc, localValue);
            generator.Emit(OpCodes.Call, methodInfo);

            var stateProperty = entityEntryType.GetProperty("State");

            generator.Emit(OpCodes.Call, stateProperty.GetGetMethod());
            generator.Emit(OpCodes.Stloc, localState);

            generator.Emit(OpCodes.Ldloc, localState);

            generator.Emit(OpCodes.Ldc_I4, (int)EntityState.Detached);

            generator.Emit(OpCodes.Ceq);
            generator.Emit(OpCodes.Brfalse, label);

            var ctor = typeof(EntityStateValidationException).GetConstructor(new[] { typeof(string) });

            generator.Emit(OpCodes.Ldstr, String.Format(
                               "The specified entity of type {0} is in a detached state and cannot be used for this operation",
                               propertyInfo.PropertyType.FullName));
            generator.Emit(OpCodes.Newobj, ctor);
            generator.Emit(OpCodes.Throw);

            generator.BeginCatchBlock(typeof(InvalidOperationException));
            generator.EndExceptionBlock();

            generator.MarkLabel(label);
        }
 public override void Emit(IEasyMember member, ILGenerator gen)
 {
     ArgumentsUtil.EmitLoadOwnerAndReference(this._syncLockSource, gen);
     gen.Emit(OpCodes.Call, typeof(Monitor).GetMethod("Enter", new Type[] { typeof(object) }));
     gen.BeginExceptionBlock();
     foreach (Statement statement in this._stmts)
     {
         statement.Emit(member, gen);
     }
     gen.BeginFinallyBlock();
     ArgumentsUtil.EmitLoadOwnerAndReference(this._syncLockSource, gen);
     gen.Emit(OpCodes.Call, typeof(Monitor).GetMethod("Exit"));
     gen.EndExceptionBlock();
 }
Example #20
0
        private void EmitStreamWriter(ILGenerator ilGenerator)
        {
            var streamWriterConstructor = typeof(StreamWriter).GetTypeInfo().DeclaredConstructors.First(c =>
            {
                var parameters = c.GetParameters();

                return(parameters.Length == 1 && parameters[0].ParameterType == typeof(Stream));
            });

            ilGenerator.Emit(OpCodes.Ldloc_1);
            ilGenerator.Emit(OpCodes.Newobj, streamWriterConstructor);
            ilGenerator.Emit(OpCodes.Stloc_2);
            ilGenerator.BeginExceptionBlock();
        }
        internal override void TranslateToIL(ILGenerator il, Type rtype)
        {
            base.context.EmitLineInfo(il);
            base.Globals.ScopeStack.Push(new WithObject(base.Globals.ScopeStack.Peek(), new JSObject(null, false)));
            bool insideProtectedRegion = base.compilerGlobals.InsideProtectedRegion;

            base.compilerGlobals.InsideProtectedRegion = true;
            Label item = il.DefineLabel();

            base.compilerGlobals.BreakLabelStack.Push(item);
            base.compilerGlobals.ContinueLabelStack.Push(item);
            this.obj.TranslateToIL(il, Typeob.Object);
            base.EmitILToLoadEngine(il);
            il.Emit(OpCodes.Call, CompilerGlobals.jScriptWithMethod);
            LocalBuilder local = null;

            if (base.context.document.debugOn)
            {
                il.BeginScope();
                local = il.DeclareLocal(Typeob.Object);
                local.SetLocalSymInfo("with()");
                il.Emit(OpCodes.Stloc, local);
            }
            else
            {
                il.Emit(OpCodes.Pop);
            }
            il.BeginExceptionBlock();
            this.block.TranslateToILInitializer(il);
            this.block.TranslateToIL(il, Typeob.Void);
            il.BeginFinallyBlock();
            if (base.context.document.debugOn)
            {
                il.Emit(OpCodes.Ldnull);
                il.Emit(OpCodes.Stloc, local);
            }
            base.EmitILToLoadEngine(il);
            il.Emit(OpCodes.Call, CompilerGlobals.popScriptObjectMethod);
            il.Emit(OpCodes.Pop);
            il.EndExceptionBlock();
            if (base.context.document.debugOn)
            {
                il.EndScope();
            }
            il.MarkLabel(item);
            base.compilerGlobals.BreakLabelStack.Pop();
            base.compilerGlobals.ContinueLabelStack.Pop();
            base.compilerGlobals.InsideProtectedRegion = insideProtectedRegion;
            base.Globals.ScopeStack.Pop();
        }
Example #22
0
 public static void checkAndSetExceptionHandler(List <FixedExceptionHandlersClass> sorted, int i, ILGenerator ilGenerator)
 {
     foreach (var allExceptionHandlerse in sorted)
     {
         if (allExceptionHandlerse.HandlerType == 1)
         {
             if (allExceptionHandlerse.TryStart == i)
             {
                 ilGenerator.BeginExceptionBlock();
             }
             if (allExceptionHandlerse.HandlerEnd == i)
             {
                 ilGenerator.EndExceptionBlock();
             }
             if (allExceptionHandlerse.HandlerStart.Contains(i))
             {
                 var indes = allExceptionHandlerse.HandlerStart.IndexOf(i);
                 ilGenerator.BeginCatchBlock(allExceptionHandlerse.CatchType[indes]);
             }
         }
         else if (allExceptionHandlerse.HandlerType == 5)
         {
             if (allExceptionHandlerse.TryStart == i)
             {
                 ilGenerator.BeginExceptionBlock();
             }
             else if (allExceptionHandlerse.HandlerEnd == i)
             {
                 ilGenerator.EndExceptionBlock();
             }
             else if (allExceptionHandlerse.TryEnd == i)
             {
                 ilGenerator.BeginFinallyBlock();
             }
         }
     }
 }
        public DefineLabelDelegate BeginExceptionBlock()
        {
            ILGenerator forIl = null;

            System.Reflection.Emit.Label?l = null;

            DefineLabelDelegate ret =
                il =>
            {
                if (forIl != null && forIl != il)
                {
                    l = null;
                }

                if (l != null)
                {
                    return(l.Value);
                }

                forIl = il;
                l     = forIl.BeginExceptionBlock();

                return(l.Value);
            };

            InstructionSizes.Add(() => InstructionSize.BeginExceptionBlock());

            LengthCache.Clear();

            Buffer.Add(
                (il, logOnly, log) =>
            {
                if (!logOnly)
                {
                    ret(il);
                }

                log.AppendLine("--BeginExceptionBlock--");
            }
                );

            TraversableBuffer.Add(new BufferedILInstruction {
                StartsExceptionBlock = true
            });

            Operations.Add(null);

            return(ret);
        }
Example #24
0
        public void PosTest3()
        {
            MethodBuilder method    = TestTypeBuilder.DefineMethod("PosTest3_Method", DefaultMethodAttribute);
            ILGenerator   generator = method.GetILGenerator();
            LocalBuilder  arg       = generator.DeclareLocal(typeof(object));

            generator.BeginExceptionBlock();

            generator.Emit(OpCodes.Ldnull, arg);
            generator.Emit(OpCodes.Ldarg_0, arg);
            generator.Emit(OpCodes.Nop, arg);

            // Try emit opcode which takes multiple args
            generator.Emit(OpCodes.Add, arg);
        }
Example #25
0
        public static void Do()
        {
            string name        = "EmitDemo.ExceptionHandler";
            string asmFileName = name + ".dll";

            AssemblyName    asmName       = new AssemblyName(name);
            AssemblyBuilder assBuilder    = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder   moduleBuilder = assBuilder.DefineDynamicModule(name, asmFileName);
            TypeBuilder     typeBuilder   = moduleBuilder.DefineType(name, TypeAttributes.Public);

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("ConvertToInt32", MethodAttributes.Public | MethodAttributes.Static, typeof(Int32), new Type[] { typeof(string) });
            ILGenerator   methodIL      = methodBuilder.GetILGenerator();

            LocalBuilder num = methodIL.DeclareLocal(typeof(Int32));

            //int num = 0;
            methodIL.Emit(OpCodes.Ldc_I4_0);
            methodIL.Emit(OpCodes.Stloc_0);//从计算堆栈的顶部弹出当前值并将其存储到索引 0 处的局部变量列表中
            //begin try
            Label lblTry = methodIL.BeginExceptionBlock();

            //num = Convert.ToInt32(str);
            methodIL.Emit(OpCodes.Ldarg_0);
            methodIL.Emit(OpCodes.Call, typeof(Convert).GetMethod("ToInt32", new Type[] { typeof(string) }));
            methodIL.Emit(OpCodes.Stloc_0);
            //end try

            //begin catch,注意,这个时侯堆栈顶为异常信息ex
            methodIL.BeginCatchBlock(typeof(Exception));
            //Console.WriteLine(ex.Message);
            methodIL.Emit(OpCodes.Call, typeof(Exception).GetMethod("get_Message"));
            methodIL.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
            methodIL.EndExceptionBlock();

            //return num
            methodIL.Emit(OpCodes.Ldloc_0);
            methodIL.Emit(OpCodes.Ret);

            Type type = typeBuilder.CreateType();

            assBuilder.Save(asmFileName);

            Console.WriteLine("input a string :");
            var str    = Console.ReadLine();
            int numRst = Convert.ToInt32(type.GetMethod("ConvertToInt32").Invoke(null, new object[] { str }));

            Console.WriteLine("convert result:{0}", numRst);
        }
Example #26
0
        /// <summary>
        /// Aspect code to inject at the beginning of weaved method
        /// </summary>
        /// <param name="typeBuilder">Type Builder</param>
        /// <param name="method">Method</param>
        /// <param name="parameter">Parameter</param>
        /// <param name="il">ILGenerator</param>
        internal void BeginAspectBlock(TypeBuilder typeBuilder, MethodBase method, ParameterInfo parameter, ILGenerator il)
        {
            var meth       = method as MethodInfo;
            var returnType = meth.ReturnType;

            local = returnType != typeof(void) ? il.DeclareLocal(returnType) : null;
            @lock = il.DeclareLocal(typeof(Thread.ReaderWriterLockSlim));

            il.Emit(method.IsStatic ? OpCodes.Ldnull : OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, GetLockMethod);
            il.Emit(OpCodes.Stloc, @lock);

            il.BeginExceptionBlock();
            il.Emit(OpCodes.Ldloc, @lock);
            il.Emit(OpCodes.Callvirt, EnterMethod);
        }
Example #27
0
        public void PosTest3()
        {
            TypeBuilder   type      = Helpers.DynamicType(TypeAttributes.NotPublic);
            MethodBuilder method    = type.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static);
            ILGenerator   generator = method.GetILGenerator();
            LocalBuilder  arg       = generator.DeclareLocal(typeof(object));

            generator.BeginExceptionBlock();

            generator.Emit(OpCodes.Ldnull, arg);
            generator.Emit(OpCodes.Ldarg_0, arg);
            generator.Emit(OpCodes.Nop, arg);

            // Try emit opcode which takes multiple args
            generator.Emit(OpCodes.Add, arg);
        }
Example #28
0
        private void InitSerializeFieldsDelegate(Type type)
        {
            Dictionary <string, MemberInfo> fields = HproseHelper.GetFields(type);
            DynamicMethod dynamicMethod            = new DynamicMethod("$SerializeFields",
                                                                       typeofVoid,
                                                                       typeofArgs,
                                                                       type,
                                                                       true);
            ILGenerator  gen   = dynamicMethod.GetILGenerator();
            LocalBuilder value = gen.DeclareLocal(typeofObject);
            LocalBuilder e     = gen.DeclareLocal(typeofException);

            foreach (KeyValuePair <string, MemberInfo> field in fields)
            {
                FieldInfo fieldInfo  = (FieldInfo)field.Value;
                Label     exTryCatch = gen.BeginExceptionBlock();
                if (type.IsValueType)
                {
                    gen.Emit(OpCodes.Ldarg_0);
                    gen.Emit(OpCodes.Unbox, type);
                }
                else
                {
                    gen.Emit(OpCodes.Ldarg_0);
                }
                gen.Emit(OpCodes.Ldfld, fieldInfo);
                if (fieldInfo.FieldType.IsValueType)
                {
                    gen.Emit(OpCodes.Box, fieldInfo.FieldType);
                }
                gen.Emit(OpCodes.Stloc_S, value);
                gen.Emit(OpCodes.Leave_S, exTryCatch);
                gen.BeginCatchBlock(typeofException);
                gen.Emit(OpCodes.Stloc_S, e);
                gen.Emit(OpCodes.Ldstr, "The field value can\'t be serialized.");
                gen.Emit(OpCodes.Ldloc_S, e);
                gen.Emit(OpCodes.Newobj, hproseExceptionCtor);
                gen.Emit(OpCodes.Throw);
                gen.Emit(OpCodes.Leave_S, exTryCatch);
                gen.EndExceptionBlock();
                gen.Emit(OpCodes.Ldarg_1);
                gen.Emit(OpCodes.Ldloc_S, value);
                gen.Emit(OpCodes.Call, serializeMethod);
            }
            gen.Emit(OpCodes.Ret);
            serializeFieldsDelegate = (SerializeDelegate)dynamicMethod.CreateDelegate(typeofSerializeDelegate);
        }
Example #29
0
        private static void EmitDeserializeConverter(ILGenerator il, SerializedMemberInfo member, Label nextLabel, LocalAllocator GetLocal,
                                                     Action <ILGenerator> thisobj, Action <ILGenerator> parentobj)
        {
            if (!member.HasConverter)
            {
                throw new InvalidOperationException("EmitDeserializeConverter called for member without converter");
            }

            using var stlocal  = GetLocal.Allocate(typeof(Value));
            using var valLocal = GetLocal.Allocate(member.Type);

            il.Emit(OpCodes.Stloc, stlocal);
            il.BeginExceptionBlock();
            il.Emit(OpCodes.Ldsfld, member.ConverterField);
            il.Emit(OpCodes.Ldloc, stlocal);
            parentobj(il);

            if (member.IsGenericConverter)
            {
                var fromValueBase = member.ConverterBase.GetMethod(nameof(ValueConverter <int> .FromValue),
                                                                   new[] { typeof(Value), typeof(object) });
                var fromValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                                .FirstOrDefault(m => m.GetBaseDefinition() == fromValueBase) ?? fromValueBase;
                il.Emit(OpCodes.Call, fromValue);
            }
            else
            {
                var fromValueBase = typeof(IValueConverter).GetMethod(nameof(IValueConverter.FromValue),
                                                                      new[] { typeof(Value), typeof(object) });
                var fromValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                                .FirstOrDefault(m => m.GetBaseDefinition() == fromValueBase) ?? fromValueBase;
                il.Emit(OpCodes.Call, fromValue);
                if (member.Type.IsValueType)
                {
                    il.Emit(OpCodes.Unbox);
                }
            }

            il.Emit(OpCodes.Stloc, valLocal);
            il.BeginCatchBlock(typeof(Exception));
            EmitWarnException(il, "Error occurred while deserializing");
            il.Emit(OpCodes.Leave, nextLabel);
            il.EndExceptionBlock();
            il.Emit(OpCodes.Ldloc, valLocal);
        }
Example #30
0
        public static Func <object, BaseProvider, List <DbParameter> > GetParamsImpl(object paramters, Type parametersType)
        {
            DynamicMethod method      = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), typeof(List <DbParameter>), new Type[] { typeof(object), typeof(BaseProvider) }, true);
            ILGenerator   iLGenerator = method.GetILGenerator();

            iLGenerator.DeclareLocal(typeof(List <DbParameter>));
            iLGenerator.Emit(OpCodes.Newobj, typeof(List <DbParameter>).GetConstructor(new Type[] { }));
            iLGenerator.Emit(OpCodes.Stloc_0);

            List <PropertyInfo> items = parametersType.GetProperties().ToList();

            iLGenerator.BeginExceptionBlock();
            var indexlocal            = iLGenerator.DeclareLocal(typeof(object));
            var indexlocalDbParameter = iLGenerator.DeclareLocal(typeof(DbParameter));

            foreach (PropertyInfo item in items)
            {
                iLGenerator.Emit(OpCodes.Ldarg_0);
                iLGenerator.Emit(OpCodes.Unbox_Any, parametersType);
                iLGenerator.Emit(OpCodes.Callvirt, item.GetGetMethod(true));

                if (item.PropertyType.IsValueType)
                {
                    iLGenerator.Emit(OpCodes.Box, item.PropertyType);
                }
                iLGenerator.Emit(OpCodes.Box, typeof(object));
                iLGenerator.Emit(OpCodes.Stloc, indexlocal);

                iLGenerator.Emit(OpCodes.Ldarg_1);
                iLGenerator.Emit(OpCodes.Ldstr, item.Name);
                iLGenerator.Emit(OpCodes.Ldloc, indexlocal);
                iLGenerator.Emit(OpCodes.Callvirt, typeof(BaseProvider).GetMethod("CreateEmitParameter", new Type[] { typeof(string), typeof(object) }));
                iLGenerator.Emit(OpCodes.Stloc, indexlocalDbParameter);

                iLGenerator.Emit(OpCodes.Ldloc_0);
                iLGenerator.Emit(OpCodes.Ldloc, indexlocalDbParameter);
                iLGenerator.Emit(OpCodes.Callvirt, typeof(List <DbParameter>).GetMethod("Add", new Type[] { typeof(DbParameter) }));
            }
            iLGenerator.BeginCatchBlock(typeof(Exception));
            iLGenerator.EmitCall(OpCodes.Call, typeof(SqlMapper).GetMethod("ThrowDataException"), null);
            iLGenerator.EndExceptionBlock();
            iLGenerator.Emit(OpCodes.Ldloc_0);
            iLGenerator.Emit(OpCodes.Ret);
            return((Func <object, BaseProvider, List <DbParameter> >)method.CreateDelegate(typeof(Func <object, BaseProvider, List <DbParameter> >)));
        }
Example #31
0
        void EmitSpecial(ILGenerator gen)
        {
            switch (special)
            {
                case Specials.Label:
                    gen.MarkLabel((Label)operand);
                    break;
                case Specials.BeginTry:
                    gen.BeginExceptionBlock();
                    break;
                case Specials.BeginFinally:
                    gen.BeginFinallyBlock();
                    break;
                case Specials.EndTry:
                    gen.EndExceptionBlock();
                    break;
                case Specials.BeginTotemScope:
                    gen.Emit(OpCodes.Nop);
                    gen.Emit(OpCodes.Ldarg_0);
                    gen.Emit(OpCodes.Newobj, Generator.scope_ctor);
                    gen.Emit(OpCodes.Stloc, (LocalBuilder)operand);
                    gen.BeginExceptionBlock();
                    break;
                case Specials.EndTotemScope:
                    var endFinallyLabel = gen.DefineLabel();
                    gen.BeginFinallyBlock();
                    gen.Emit(OpCodes.Ldloc, (LocalBuilder)operand);
                    gen.Emit(OpCodes.Ldnull);
                    gen.Emit(OpCodes.Ceq);
                    gen.Emit(OpCodes.Brtrue, endFinallyLabel);

                    gen.Emit(OpCodes.Ldloc, (LocalBuilder)operand);
                    gen.Emit(OpCodes.Callvirt, Generator.dispose);
                    gen.Emit(OpCodes.Nop);

                    gen.MarkLabel(endFinallyLabel);
                    gen.EndExceptionBlock();
                    break;
                default:
                    throw new InvalidOperationException("default:special");
            }
        }