[Test] // bug #81431 public void FilterAndCatchBlock() { DefineBasicMethod(); ILGenerator il = il_gen; il.BeginExceptionBlock(); il.BeginExceptFilterBlock(); il.BeginCatchBlock(null); il.BeginCatchBlock(typeof(SystemException)); }
public CatchBlock CatchBlock(Type exceptionType, Action <ILGenerator> filter) { EnsureTryBlockEnded(); if (hasFinallyBlock) { throw new InvalidOperationException( "Exception block already has a finally block - cannot start new catch block"); } if (hasFaultBlock) { throw new InvalidOperationException( "Exception block already has a fault block - cannot have both catch and fault blocks"); } if (filter != null) { generator.BeginExceptFilterBlock(); if (exceptionType != null) { var filterBlockEnd = generator.DefineLabel(); var customFilter = generator.DefineLabel(); generator .Duplicate() .IsInstanceOfType(exceptionType) .BranchIfTrue(customFilter) .Pop() .LoadConstant(false) .BranchTo(filterBlockEnd); generator.MarkLabel(customFilter); filter(generator); generator.MarkLabel(filterBlockEnd); } else { filter(generator); } generator.BeginCatchBlock(null); } else { generator.BeginCatchBlock(exceptionType); } hasCatchBlocks = true; return(new CatchBlock(generator, endLabel)); }
public override void BeginCatch(TreeNode node, TreeNode node2, Qualifier qual, string p) { LocalBuilder l = (LocalBuilder)node2.Entry.ReflectionObject; ig.BeginCatchBlock(l.LocalType); ig.Emit(OpCodes.Stloc, l); }
/// <summary> /// 编织创建无返回值的方法 /// </summary> /// <param name="methodIL">方法指令器</param> /// <param name="proxyMethod">代理的方法</param> /// <param name="parameterTypes">方法的参数</param> /// <param name="_testfb"></param> private static void CreateVoidMethod(ILGenerator methodIL, MethodInfo proxyMethod, MethodInfo souceMethod, FieldBuilder _testfb) { Type[] parameterTypes = proxyMethod.GetParameters().Select(o => o.ParameterType).ToArray(); var _try = methodIL.BeginExceptionBlock(); callMethodAfter(methodIL, souceMethod); #region 调用方法等同于 ReturnType result= method(arg1,arg2,....); methodIL.Emit(OpCodes.Ldarg_0); methodIL.Emit(OpCodes.Ldfld, _testfb); for (short i = 0; i < parameterTypes.Length; i++) { methodIL.Emit(OpCodes.Ldarg, i + 1); } methodIL.Emit(OpCodes.Callvirt, proxyMethod); #endregion callMethodBefore(methodIL, _testfb, souceMethod); methodIL.BeginCatchBlock(typeof(Exception)); methodIL.EmitWriteLine("异常"); methodIL.BeginFinallyBlock(); methodIL.EmitWriteLine("一定"); methodIL.EndExceptionBlock(); methodIL.Emit(OpCodes.Ret); }
public static void MarkBlockBefore(ILGenerator il, ExceptionBlock block, out Label?label) { label = null; switch (block.blockType) { case ExceptionBlockType.BeginExceptionBlock: label = il.BeginExceptionBlock(); return; case ExceptionBlockType.BeginCatchBlock: il.BeginCatchBlock(block.catchType); return; case ExceptionBlockType.BeginExceptFilterBlock: il.BeginExceptFilterBlock(); return; case ExceptionBlockType.BeginFaultBlock: il.BeginFaultBlock(); return; case ExceptionBlockType.BeginFinallyBlock: il.BeginFinallyBlock(); return; } }
public static void ImplantCatchException(ILGenerator il, Type exType, LocalBuilder context) { if (exType == null) { return; } Type type = typeof(Exception); var ex = il.DeclareLocal(type); il.BeginCatchBlock(type); //进入catch块后,此时的栈顶就是Exception对象 il.Emit(OpCodes.Castclass, type); il.Emit(OpCodes.Stloc, ex); ConstructorInfo info = exType.GetConstructor(Type.EmptyTypes); il.Emit(OpCodes.Newobj, info); var method = exType.GetMethod("OnException"); il.Emit(OpCodes.Ldloc, context); il.Emit(OpCodes.Ldloc, ex); il.Emit(OpCodes.Callvirt, method); il.EndExceptionBlock(); }
static void GenerateCode(ProgramNode root, string outputPath) { string name = Path.GetFileNameWithoutExtension(outputPath); string filename = Path.GetFileName(outputPath); AssemblyName assemblyName = new AssemblyName(name); AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, Path.GetDirectoryName(Path.GetFullPath(outputPath))); ModuleBuilder moduleBuilder = assembly.DefineDynamicModule(name, filename); TypeBuilder programType = moduleBuilder.DefineType("Program", TypeAttributes.Public); MethodBuilder mainMethod = programType.DefineMethod("Main", MethodAttributes.Static | MethodAttributes.Public, typeof(void), System.Type.EmptyTypes); assembly.SetEntryPoint(mainMethod); ILGenerator generator = mainMethod.GetILGenerator(); generator.BeginExceptionBlock(); CodeGenerator cg = new CodeGenerator(generator, moduleBuilder, programType); root.Generate(cg); generator.BeginCatchBlock(typeof(Exception)); generator.Emit(OpCodes.Pop); generator.Emit(OpCodes.Ldc_I4_1); generator.Emit(OpCodes.Call, typeof(Environment).GetMethod("Exit")); generator.EndExceptionBlock(); generator.Emit(OpCodes.Ret); programType.CreateType(); moduleBuilder.CreateGlobalFunctions(); assembly.Save(filename); }
protected override void InitUnserializeDelegate(Type type, string[] names, DynamicMethod dynamicMethod) { Dictionary <string, MemberInfo> members = HproseHelper.GetMembers(type); ILGenerator gen = dynamicMethod.GetILGenerator(); LocalBuilder e = gen.DeclareLocal(typeofException); int count = names.Length; for (int i = 0; i < count; i++) { 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 (members[names[i]] is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)members[names[i]]; if (fieldInfo.FieldType.IsValueType) { gen.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType); } gen.Emit(OpCodes.Stfld, fieldInfo); } else { PropertyInfo propertyInfo = (PropertyInfo)members[names[i]]; if (propertyInfo.PropertyType.IsValueType) { gen.Emit(OpCodes.Unbox_Any, propertyInfo.PropertyType); } MethodInfo setMethod = propertyInfo.GetSetMethod(); 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 member 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); }
// internal static void Proceed(MethodBuilder method, ILGenerator ILGen) { var @ret = ILGen.DefineLabel(); var @endTry = ILGen.DefineLabel(); var @endFilter = ILGen.DefineLabel(); //.try var @try = ILGen.BeginExceptionBlock(); ILGen.Emit(OpCodes.Ldstr, "Throw"); ILGen.Emit(OpCodes.Call, mInfo_WriteLine); ILGen.Emit(OpCodes.Newobj, cInfo_Exception); ILGen.Emit(OpCodes.Throw); ILGen.MarkLabel(@endTry); //.end try //.filter //ILGen.BeginExceptFilterBlock(); //ILGen.Emit(OpCodes.Isinst, typeof(Exception)); //ILGen.Emit(OpCodes.Brfalse_S, endFilter); //ILGen.Emit(OpCodes.Ldarg_1); //ILGen.Emit(OpCodes.Brfalse_S, endFilter); //ILGen.MarkLabel(endFilter); //.end filter //.catch ILGen.BeginCatchBlock(typeof(Exception)); //ILGen.BeginCatchBlock(null); ILGen.Emit(OpCodes.Ldstr, "Swallow"); ILGen.Emit(OpCodes.Call, mInfo_WriteLine); ILGen.Emit(OpCodes.Leave_S, @ret); ILGen.EndExceptionBlock(); //.end catch ILGen.MarkLabel(@ret); ILGen.Emit(OpCodes.Ret); }
internal override void Emit(EmitContext ec) { ILGenerator ig = ec.ig; Type t = typeof(object); bool in_function = InFunction; if (in_function) { local_builder = ig.DeclareLocal(t); } else { field_info = ec.type_builder.DefineField(mangle_id(id), t, FieldAttributes.Public | FieldAttributes.Static); } ig.BeginCatchBlock(typeof(Exception)); CodeGenerator.load_engine(in_function, ig); ig.Emit(OpCodes.Call, typeof(Try).GetMethod("JScriptExceptionValue")); if (in_function) { ig.Emit(OpCodes.Stloc, local_builder); } else { ig.Emit(OpCodes.Stsfld, field_info); } stms.Emit(ec); }
/// <summary> /// Try to emit something like that: /// /// .method public static bool TestFilter (bool execute_handler) /// { /// .locals init(bool) /// try { /// newobj instance void [mscorlib]System.Exception::.ctor() /// throw /// } filter { /// pop /// ldarg.0 /// endfilter /// } { /// ldc.i4.1 /// stloc.0 /// leave quit /// } /// ldc.i4.0 /// stloc.0 /// quit: /// ldloc.0 /// ret /// } /// /// It should return true if the handler has been executed /// Otherwise, the exception should not be catched /// </summary> void DefineTestFilterMethod() { MethodBuilder mb = tb.DefineMethod("TestFilter", MethodAttributes.Public | MethodAttributes.Static, typeof(bool), new Type [] { typeof(bool) }); ConstructorInfo exCtor = typeof(Exception).GetConstructor(new Type [0]); il_gen = mb.GetILGenerator(); il_gen.DeclareLocal(typeof(bool)); Label quit = il_gen.DefineLabel(); il_gen.BeginExceptionBlock(); il_gen.Emit(OpCodes.Newobj, exCtor); il_gen.Emit(OpCodes.Throw); il_gen.BeginExceptFilterBlock(); il_gen.Emit(OpCodes.Pop); il_gen.Emit(OpCodes.Ldarg_0); il_gen.BeginCatchBlock(null); il_gen.Emit(OpCodes.Ldc_I4_1); il_gen.Emit(OpCodes.Stloc_0); il_gen.Emit(OpCodes.Leave, quit); il_gen.EndExceptionBlock(); il_gen.Emit(OpCodes.Ldc_I4_0); il_gen.Emit(OpCodes.Stloc_0); il_gen.MarkLabel(quit); il_gen.Emit(OpCodes.Ldloc_0); il_gen.Emit(OpCodes.Ret); }
static void TT() { DynamicMethod multiplyHidden = new DynamicMethod( "", typeof(void), new[] { typeof(int) }, typeof(Example)); ILGenerator ig = multiplyHidden.GetILGenerator(); ig.BeginExceptionBlock(); ig.Emit(OpCodes.Call, typeof(A).GetMethod("ThrowMe")); ig.BeginCatchBlock(typeof(Exception)); ig.Emit(OpCodes.Call, typeof(A).GetMethod("Handler")); ig.EndExceptionBlock(); ig.Emit(OpCodes.Ret); var invoke = (Action <int>) multiplyHidden.CreateDelegate( typeof(Action <int>) ); invoke(1); }
public void Emit(ILGenerator il, int offset, ExceptionHandlingClauseData clause) { if (offset == clause.TryOffset) { il.BeginExceptionBlock(); } if (offset == clause.HandlerOffset) { switch (clause.Flags) { case ExceptionHandlingClauseOptions.Finally: il.BeginFinallyBlock(); break; case ExceptionHandlingClauseOptions.Fault: il.BeginFaultBlock(); break; case ExceptionHandlingClauseOptions.Clause: il.BeginCatchBlock(typeResolver.GetType(clause.CatchType)); break; default: throw new DelegateDeserializationException(string.Format("Unknown clause {0}", clause.Flags)); } } if (offset == clause.HandlerOffset + clause.HandlerLength) { il.EndExceptionBlock(); } }
public void BeginCatchBlock(Type type) { if (!Active) { return; } IL.BeginCatchBlock(type); Text.Append("Catch (").Append(type.ToString()).AppendLine(); }
public IILGen Catch(Type exceptionType) { _sourceCodeWriter.CloseScope(); _sourceCodeWriter.MarkAndWriteLine(_ilGenerator, $"catch ({exceptionType.FullName})"); _sourceCodeWriter.OpenScope(); _ilGenerator.BeginCatchBlock(exceptionType); return(this); }
internal override void Emit(ILGenerator ilg) { ExVar.Declare(ilg); ilg.BeginCatchBlock(ExVar.Type.Type); ilg.Emit(OpCodes.Isinst, ExVar.Type.Type); ilg.Emit(OpCodes.Stloc, ExVar.Index); Stmt.Emit(ilg); }
/// <summary> /// Emit the required IL instructions to the new method. /// </summary> private DynamicMethod BuildTestMethod(Type fixtureType, string methodName, MethodBodyReader reader) { Type exceptionType = typeof(Exception); Type exceptionCollectionType = typeof(Dictionary <int, Exception>); ConstructorInfo exceptionCollectionTypeConstructor = exceptionCollectionType.GetConstructor(Type.EmptyTypes); MethodInfo exceptionCollectionTypeAddMethod = exceptionCollectionType.GetMethod("Add"); List <List <ILInstruction> > sections = GetMethodSections(reader); ushort freeLocalIndex = reader.GetFreeLocalIndex(); ushort localExceptionCollection = freeLocalIndex++; ushort localException = freeLocalIndex++; DynamicMethod testMethod = new DynamicMethod(methodName, exceptionCollectionType, new Type[] { fixtureType }, fixtureType); ILGenerator generator = testMethod.GetILGenerator(); DeclareLocalVariableTypes(generator, reader); // Instantiate exception collection. generator.DeclareLocal(exceptionCollectionType); generator.Emit(OpCodes.Nop); generator.Emit(OpCodes.Newobj, exceptionCollectionTypeConstructor); generator.Emit(OpCodes.Stloc_S, localExceptionCollection); foreach (List <ILInstruction> sect in sections) { // Start the try block. generator.BeginExceptionBlock(); foreach (ILInstruction instruction in sect) { instruction.EmitTo(generator); } // If no exception was thrown add a null reference to the collection. generator.Emit(OpCodes.Ldloc_S, localExceptionCollection); generator.Emit(OpCodes.Ldc_I4, sect[0].Offset); generator.Emit(OpCodes.Ldnull); generator.Emit(OpCodes.Callvirt, exceptionCollectionTypeAddMethod); generator.Emit(OpCodes.Nop); // Catch Exception. generator.BeginCatchBlock(exceptionType); // Save thrown exception. generator.DeclareLocal(exceptionType); generator.Emit(OpCodes.Stloc_S, localException); generator.Emit(OpCodes.Nop); // Add the exception to the collection. generator.Emit(OpCodes.Ldloc_S, localExceptionCollection); generator.Emit(OpCodes.Ldc_I4, sect[0].Offset); generator.Emit(OpCodes.Ldloc_S, localException); generator.Emit(OpCodes.Callvirt, exceptionCollectionTypeAddMethod); generator.Emit(OpCodes.Nop); // Exit the try block. generator.EndExceptionBlock(); } generator.Emit(OpCodes.Ldloc_S, localExceptionCollection); generator.Emit(OpCodes.Ret); return(testMethod); }
public static Func <IDataReader, object> GetInitModelByReader(Type type, IDataReader reader) { Type[] parameterTypes = new Type[] { typeof(IDataReader) }; DynamicMethod method = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), typeof(object), parameterTypes, true); ILGenerator iLGenerator = method.GetILGenerator(); iLGenerator.DeclareLocal(typeof(int)); iLGenerator.DeclareLocal(type); iLGenerator.Emit(OpCodes.Ldc_I4_0); iLGenerator.Emit(OpCodes.Stloc_0); DataMap dataMap = Metadata.GetDataMap(type); string[] names = (from i in Enumerable.Range(0, reader.FieldCount) select reader.GetName(i)) .Where(e => e != "RN" && (dataMap._properties.Where(p => p.Name == e).Count() > 0 || dataMap._columnAttributes.Where(p => p.columnName == e).Count() > 0)).Distinct().ToArray <string>(); ConstructorInfo info = dataMap.FindConstructor(); iLGenerator.Emit(OpCodes.Newobj, info); iLGenerator.Emit(OpCodes.Stloc_1); iLGenerator.BeginExceptionBlock(); int num = 0; int localIndex = iLGenerator.DeclareLocal(typeof(object)).LocalIndex; foreach (ColumnMap map in (from n in names select dataMap.GetMember(n)).ToList <ColumnMap>()) { //var labelElse = iLGenerator.DefineLabel(); //var labelEnd = iLGenerator.DefineLabel(); iLGenerator.Emit(OpCodes.Ldarg_0);//加载reader iLGenerator.Emit(OpCodes.Ldstr, map.MemberName); MethodInfo getValueMethod = typeof(IDataRecord).GetMethod("get_Item", new[] { typeof(string) }); iLGenerator.Emit(OpCodes.Callvirt, getValueMethod); iLGenerator.Emit(OpCodes.Stloc, (short)localIndex); iLGenerator.Emit(OpCodes.Ldloc_1);//压入对象 iLGenerator.Emit(OpCodes.Ldloc, localIndex); iLGenerator.Emit(OpCodes.Dup); Label notNullLabel = iLGenerator.DefineLabel(); iLGenerator.Emit(OpCodes.Isinst, typeof(DBNull)); //是1,否0 iLGenerator.Emit(OpCodes.Brfalse_S, notNullLabel); //如果非空、非0则控制权转到label iLGenerator.Emit(OpCodes.Pop); iLGenerator.Emit(OpCodes.Ldstr, "0"); iLGenerator.Emit(OpCodes.Stloc, localIndex); iLGenerator.Emit(OpCodes.Ldloc, localIndex); iLGenerator.Emit(OpCodes.Br_S, notNullLabel); iLGenerator.MarkLabel(notNullLabel); iLGenerator.Emit(OpCodes.Call, typeof(Convert).GetMethod(typeMap[map.MemberType], new Type[] { typeof(object) })); iLGenerator.Emit(OpCodes.Callvirt, map.SetMethodInfo); num++; } iLGenerator.BeginCatchBlock(typeof(Exception)); iLGenerator.EmitCall(OpCodes.Call, typeof(Check).GetMethod("ThrowDataException"), null); iLGenerator.EndExceptionBlock(); //iLGenerator.Emit(OpCodes.Ldloc, localIndex); iLGenerator.Emit(OpCodes.Ldloc_1); iLGenerator.Emit(OpCodes.Ret); return((Func <IDataReader, object>)method.CreateDelegate(typeof(Func <IDataReader, object>))); }
public void BeginCatchBlock(TypeSpec type) { if (IsAnonymousStoreyMutateRequired) { type = CurrentAnonymousMethod.Storey.Mutator.Mutate(type); } ig.BeginCatchBlock(type.GetMetaInfo()); }
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); }
public TryCatchManager Catch(Action <LocalBuilder> builder) { generator.BeginCatchBlock(typeof(Exception)); var ex = generator.DeclareLocal(typeof(Exception)); generator.Emit(OpCodes.Stloc_S, ex); builder(ex); return(this); }
private static LocalBuilder[] GetColumnIndices(ILGenerator il, List <DbColumnInfo> columnInfoes) { var colIndices = new LocalBuilder[columnInfoes.Count]; for (var i = 0; i < colIndices.Length; i++) { // int %index% = arg.GetOrdinal(%ColumnName%); colIndices[i] = il.DeclareLocal(typeof(int)); if (columnInfoes[i].IsOptional) { // try { il.BeginExceptionBlock(); } il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldstr, columnInfoes[i].ColumnName); il.Emit(OpCodes.Callvirt, DataRecord_GetOrdinal); il.Emit(OpCodes.Stloc_S, colIndices[i]); if (columnInfoes[i].IsOptional) { var exit = il.DefineLabel(); il.Emit(OpCodes.Leave_S, exit); // } catch (IndexOutOfRangeException) { il.BeginCatchBlock(typeof(IndexOutOfRangeException)); // //forget the exception il.Emit(OpCodes.Pop); // int %index% = -1; // if not found, -1 il.Emit(OpCodes.Ldc_I4_M1); il.Emit(OpCodes.Stloc_S, colIndices[i]); il.Emit(OpCodes.Leave_S, exit); // } catch (ArgumentException) { il.BeginCatchBlock(typeof(ArgumentException)); // forget the exception il.Emit(OpCodes.Pop); // int %index% = -1; // if not found, -1 il.Emit(OpCodes.Ldc_I4_M1); il.Emit(OpCodes.Stloc_S, colIndices[i]); il.Emit(OpCodes.Leave_S, exit); // } il.EndExceptionBlock(); il.MarkLabel(exit); } } return(colIndices); }
public override void Generate(EmitStmtContext context) { ILGenerator il = context.ILout; MarkSequencePoint(context); il.BeginCatchBlock(exType); EmitHelper.StormVar(il, exSymbol.VarBuilder); CatchBody.Generate(context); il.EndExceptionBlock(); }
public void BeginCatchBlock() { TypeBuilder type = Helpers.DynamicType(TypeAttributes.NotPublic); MethodBuilder method = type.DefineMethod("PosTest4_Method", MethodAttributes.Public | MethodAttributes.Static); ILGenerator generator = method.GetILGenerator(); generator.BeginExceptionBlock(); generator.BeginCatchBlock(typeof(TestExceptionLocal1)); VerifyDeclareLocal(generator); }
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)); }
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(); } }
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); }
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(); }
private void EmitILForExceptionHandlers(ILGenerator ilGenerator, Instruction instruction, List <ExceptionHandler> handlers) { int catchBlockCount = 0; foreach (var handler in handlers.Where(h => h.TryStart == instruction.Offset)) { if (handler.Flag == "Clause") { if (catchBlockCount >= 1) { continue; } ilGenerator.BeginExceptionBlock(); catchBlockCount++; //break; continue; } ilGenerator.BeginExceptionBlock(); } foreach (var handler in handlers.Where(h => h.HandlerEnd == instruction.Offset)) //|| (h.HandlerEnd == instruction.Offset - 1 && instruction.OpCode == OpCodes.Ret))) { if (handler.Flag == "Clause") { var _handlers = handlers.Where(h => h.TryEnd == handler.TryEnd && h.Flag == "Clause"); if (handler.HandlerEnd == _handlers.Select(h => h.HandlerEnd).Max()) { ilGenerator.EndExceptionBlock(); } //break; continue; } ilGenerator.EndExceptionBlock(); } foreach (var handler in handlers.Where(h => h.HandlerStart == instruction.Offset)) { if (handler.Flag == "Clause") { ilGenerator.BeginCatchBlock(handler.CatchType); } else if (handler.Flag == "Finally") { ilGenerator.BeginFinallyBlock(); } } }