private static void AddCollectionLoop(Collection<Instruction> ins, VariableDefinition leftEnumerator, VariableDefinition leftHasNext,
            VariableDefinition rightEnumerator, VariableDefinition rightHasNext)
        {
            var loopBegin = Instruction.Create(OpCodes.Nop);
            ins.Add(loopBegin);

            AddMoveNext(ins, leftEnumerator, leftHasNext);
            AddMoveNext(ins, rightEnumerator, rightHasNext);

            ins.IfAnd(
                c => AddCheckHasNext(c, leftHasNext, false),
                c => AddCheckHasNext(c, rightHasNext, false),
                t => AddReturnTrue(t),
                e =>
                {
                    e.IfAnd(
                        c => AddCheckHasNext(c, leftHasNext, true),
                        c => AddCheckHasNext(c, rightHasNext, true),
                        t =>
                        {
                            t.If(
                                c => AddCheckCurrent(c, leftEnumerator, rightEnumerator),
                                tt => AddRerurnFalse(tt));
                        },
                        e2 =>
                        {
                            ins.Add(Instruction.Create(OpCodes.Ldc_I4_0));
                            ins.Add(Instruction.Create(OpCodes.Ret));
                        });
                });

            ins.Add(Instruction.Create(OpCodes.Br, loopBegin));
        }
Example #2
0
 /// <summary>
 /// Creates a new statement initializing a delegate variable.
 /// </summary>
 /// <param name="constructor">The constructor for the delegate type.</param>
 /// <param name="target">The target the delegate will invoke.</param>
 /// <param name="storage">The variable which will store the new delegate.</param>
 public InitDelegateStatement(MethodReference constructor, MethodReference target, VariableDefinition storage)
     : base(null)
 {
     this.m_Constructor = constructor;
     this.m_Target = target;
     this.m_Storage = storage;
 }
 public GetSurroundingClassImplementation(VariableDefinition invocationInfo, 
     VariableDefinition surroundingClassImplementation, MethodInfo getSurroundingImplementationMethod)
 {
     _invocationInfo = invocationInfo;
     _surroundingClassImplementation = surroundingClassImplementation;
     _getSurroundingImplementationMethod = getSurroundingImplementationMethod;
 }
 public GetSurroundingImplementationInstance(VariableDefinition aroundInvokeProvider, VariableDefinition invocationInfo, VariableDefinition surroundingImplementation, Instruction skipGetSurroundingImplementation)
 {
     _aroundInvokeProvider = aroundInvokeProvider;
     _invocationInfo = invocationInfo;
     _surroundingImplementation = surroundingImplementation;
     _skipGetSurroundingImplementation = skipGetSurroundingImplementation;
 }
Example #5
0
 public EmitBeforeInvoke(VariableDefinition invocationInfo, VariableDefinition surroundingClassImplementation, VariableDefinition surroundingImplementation, Type registryType)
 {
     _invocationInfo = invocationInfo;
     _surroundingClassImplementation = surroundingClassImplementation;
     _surroundingImplementation = surroundingImplementation;
     _registryType = registryType;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="MethodBodyRewriterParameters"/> class.
        /// </summary>
        /// <param name="IL">The CilWorker that is responsible for the current method body.</param>
        /// <param name="oldInstructions">The value indicating the list of old instructions in the current method body.</param>
        /// <param name="interceptionDisabled">The value that determines whether or not interception is disabled.</param>
        /// <param name="invocationInfo">The local variable that will store the <see cref="IInvocationInfo"/> instance.</param>
        /// <param name="returnValue">The value indicating the local variable that will store the return value.</param>
        /// <param name="methodReplacementProvider">The <see cref="IMethodReplacementProvider"/> instance.</param>
        /// <param name="aroundInvokeProvider">The <see cref="IAroundInvokeProvider"/> instance.</param>
        /// <param name="classMethodReplacementProvider">The class-level<see cref="IMethodReplacementProvider"/> instance.</param>
        /// <param name="getMethodReplacementProviderMethod">The functor that resolves the GetMethodReplacementProvider method.</param>
        /// <param name="registryType">The interception registry type that will be responsible for handling class-level interception events.</param>
        public MethodBodyRewriterParameters(CilWorker IL, IEnumerable<Instruction> oldInstructions,
                                            VariableDefinition interceptionDisabled,
                                            VariableDefinition invocationInfo,
                                            VariableDefinition returnValue,
                                            VariableDefinition methodReplacementProvider,
                                            VariableDefinition aroundInvokeProvider,
                                            VariableDefinition classMethodReplacementProvider,
                                            Func<ModuleDefinition, MethodReference> getMethodReplacementProviderMethod,
                                            Type registryType)
        {
            if (methodReplacementProvider.VariableType.FullName != typeof(IMethodReplacementProvider).FullName)
                throw new ArgumentException("methodReplacementProvider");

            if (aroundInvokeProvider.VariableType.FullName != typeof(IAroundInvokeProvider).FullName)
                throw new ArgumentException("aroundInvokeProvider");

            _cilWorker = IL;
            _oldInstructions = oldInstructions;
            _interceptionDisabled = interceptionDisabled;
            _invocationInfo = invocationInfo;
            _returnValue = returnValue;
            _methodReplacementProvider = methodReplacementProvider;
            _aroundInvokeProvider = aroundInvokeProvider;
            _classMethodReplacementProvider = classMethodReplacementProvider;
            _getMethodReplacementProviderMethod = getMethodReplacementProviderMethod;
            _registryType = registryType;
        }
Example #7
0
    MethodDefinition InjectInterceptedMethod(TypeDefinition targetType, MethodDefinition innerOnPropertyChanging)
    {
        var delegateHolderInjector = new DelegateHolderInjector
                                     {
                                         TargetTypeDefinition=targetType,
                                         OnPropertyChangingMethodReference = innerOnPropertyChanging,
                                         ModuleWeaver = this
                                     };
        delegateHolderInjector.InjectDelegateHolder();
        var method = new MethodDefinition(EventInvokerNames.First(), GetMethodAttributes(targetType), ModuleDefinition.TypeSystem.Void);

        var propertyName = new ParameterDefinition("propertyName", ParameterAttributes.None, ModuleDefinition.TypeSystem.String);
        method.Parameters.Add(propertyName);
        if (InterceptorType == InvokerTypes.Before)
        {
            var before = new ParameterDefinition("before", ParameterAttributes.None, ModuleDefinition.TypeSystem.Object);
            method.Parameters.Add(before);
        }

        var action = new VariableDefinition("firePropertyChanging", ActionTypeReference);
        method.Body.Variables.Add(action);

        var variableDefinition = new VariableDefinition("delegateHolder", delegateHolderInjector.TypeDefinition);
        method.Body.Variables.Add(variableDefinition);

        var instructions = method.Body.Instructions;

        var last = Instruction.Create(OpCodes.Ret);
        instructions.Add(Instruction.Create(OpCodes.Newobj, delegateHolderInjector.ConstructorDefinition));
        instructions.Add(Instruction.Create(OpCodes.Stloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
        instructions.Add(Instruction.Create(OpCodes.Stfld, delegateHolderInjector.PropertyName));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        instructions.Add(Instruction.Create(OpCodes.Stfld, delegateHolderInjector.Target));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldftn, delegateHolderInjector.MethodDefinition));
        instructions.Add(Instruction.Create(OpCodes.Newobj, ActionConstructorReference));
        instructions.Add(Instruction.Create(OpCodes.Stloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldfld, delegateHolderInjector.PropertyName));
        if (InterceptorType == InvokerTypes.Before)
        {
            instructions.Add(Instruction.Create(OpCodes.Ldarg_2));
            instructions.Add(Instruction.Create(OpCodes.Call, InterceptMethod));
        }
        else
        {
            instructions.Add(Instruction.Create(OpCodes.Call, InterceptMethod));
        }

        instructions.Add(last);
        method.Body.InitLocals = true;

        targetType.Methods.Add(method);
        return method;
    }
    MethodDefinition InjectMethod(TypeDefinition targetType, string eventInvokerName, FieldReference propertyChangingField)
    {
        var method = new MethodDefinition(eventInvokerName, GetMethodAttributes(targetType), ModuleDefinition.TypeSystem.Void);
		method.Parameters.Add(new ParameterDefinition("propertyName", ParameterAttributes.None, ModuleDefinition.TypeSystem.String));

        var handlerVariable = new VariableDefinition(PropChangingHandlerReference);
        method.Body.Variables.Add(handlerVariable);
		var boolVariable = new VariableDefinition(ModuleDefinition.TypeSystem.Boolean);
        method.Body.Variables.Add(boolVariable);

        var instructions = method.Body.Instructions;

        var last = Instruction.Create(OpCodes.Ret);
        instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        instructions.Add(Instruction.Create(OpCodes.Ldfld, propertyChangingField)); 
        instructions.Add(Instruction.Create(OpCodes.Stloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldnull));
        instructions.Add(Instruction.Create(OpCodes.Ceq));
        instructions.Add(Instruction.Create(OpCodes.Stloc_1));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_1));
        instructions.Add(Instruction.Create(OpCodes.Brtrue_S, last));
        instructions.Add(Instruction.Create(OpCodes.Ldloc_0));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
        instructions.Add(Instruction.Create(OpCodes.Newobj, ComponentModelPropertyChangingEventConstructorReference));
        instructions.Add(Instruction.Create(OpCodes.Callvirt, ComponentModelPropertyChangingEventHandlerInvokeReference));


        instructions.Add(last);
        method.Body.InitLocals = true;
        targetType.Methods.Add(method);
        return method;
    }
Example #9
0
        public static void HandleDups(MethodDefinition coroutine, OrderedDictionary<Instruction, List<Instruction>> coroutineInstructions, Instruction instruction, List<Instruction> current, TypeReference expectedType, ref VariableDefinition dupLoc)
        {
            // FIXME: This is kindof a kludge... think on it
            if (instruction.Previous.OpCode != OpCodes.Dup)
                return;

            var action = current.ToArray ();
            current.Clear ();

            if (dupLoc == null) {
                dupLoc = new VariableDefinition (coroutine.Module.Import (typeof (object)));
                coroutine.Body.Variables.Add (dupLoc);
            }

            if (expectedType.IsValueType)
                current.Add (Instruction.Create (OpCodes.Box, expectedType));

            current.Add (Instruction.Create (OpCodes.Stloc, dupLoc));

            current.AddRange  (action);

            current.Add (Instruction.Create (OpCodes.Ldloc, dupLoc));
            if (expectedType.IsValueType) {
                current.Add (Instruction.Create (OpCodes.Unbox, expectedType));
                current.Add (Instruction.Create (OpCodes.Ldobj, expectedType));
            }
        }
        private static AssemblyDefinition CreateTestAssembly(OpCode opCode, bool invert)
        {
            var name = new AssemblyNameDefinition("TestConditionalsBoundaryTurtle", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestConditionalsBoundaryTurtle", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var boolType = assembly.MainModule.Import(typeof(bool));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var param = new ParameterDefinition("input", ParameterAttributes.In, intType);
            method.Parameters.Add(param);
            var resultVariable = new VariableDefinition(boolType);
            method.Body.Variables.Add(resultVariable);

            var processor = method.Body.GetILProcessor();
            Instruction loadReturnValueInstruction = processor.Create(OpCodes.Ldloc, resultVariable);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, param));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
            method.Body.Instructions.Add(processor.Create(opCode));
            if (invert)
            {
                method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
                method.Body.Instructions.Add(processor.Create(OpCodes.Ceq));
            }
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(loadReturnValueInstruction);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ret));

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GetMethodReplacementProvider"/> class.
 /// </summary>
 /// <param name="methodReplacementProvider">The local variable that contains the <see cref="IMethodReplacementProvider"/> instance.</param>
 /// <param name="hostMethod">The target method.</param>
 /// <param name="resolveGetProviderMethod">The functor that will resolve the GetProvider method.</param>
 public GetMethodReplacementProvider(VariableDefinition methodReplacementProvider, MethodDefinition hostMethod,
                                     Func<ModuleDefinition, MethodReference> resolveGetProviderMethod)
 {
     _methodReplacementProvider = methodReplacementProvider;
     _hostMethod = hostMethod;
     _resolveGetProviderMethod = resolveGetProviderMethod;
 }
        private TypeDefinition GenerateTypeA(AssemblyDefinition assembly)
        {
            var objType = assembly.MainModule.Import(typeof (object));

            // define base class
            var aType = new TypeDefinition("A", "", TypeAttributes.Class, objType);
            assembly.MainModule.Types.Add(aType);

            var typeParameter = new GenericParameter("T", aType);
            aType.GenericParameters.Add(typeParameter);

            var baseMethod = new MethodDefinition("Get",
                                                  MethodAttributes.Assem | MethodAttributes.Virtual |
                                                  MethodAttributes.NewSlot, typeParameter);
            aType.Methods.Add(baseMethod);
            baseMethod.DeclaringType = aType;

            var local = new VariableDefinition(typeParameter);
            baseMethod.Body.Variables.Add(local);

            var cil = baseMethod.Body.CilWorker;
            cil.Emit(OpCodes.Ldloca, local);
            cil.Emit(OpCodes.Initobj, typeParameter);
            cil.Emit(OpCodes.Ldloc, local);
            cil.Emit(OpCodes.Ret);
            return aType;
        }
Example #13
0
        public void Visit(IBehaviorDefinition method, CustomAttribute attribute)
        {
            ILProcessor processor = method.Body.GetILProcessor();
            string description = attribute.Properties.Where(argument => (argument.Name == "Description")).First().Argument.Value as string;
            Instruction exitInstruction = processor.Create(OpCodes.Callvirt, method.Module.Import(broadcastType.GetMethod("Run", new[] {typeof(object), typeof(string)})));
            var returnValue = new VariableDefinition("retVal", method.Module.Import(typeof(object)));
            var enclosingObject = new VariableDefinition("enclosing", method.Module.Import(typeof(object)));
            method.Body.Variables.Add(enclosingObject);
            method.Body.Variables.Add(returnValue);
            Instruction store = processor.Create(OpCodes.Stloc, returnValue);
            Instruction reload = processor.Create(OpCodes.Ldloc, returnValue);
            var instructions = new List<Instruction>();
            if (!ReturnsVoid(method))
            {
                instructions.Add(store);
            }
            instructions.Add(processor.Create(OpCodes.Newobj, method.Module.Import(broadcastType.GetConstructor(new Type[] { }))));
            instructions.Add(processor.Create(OpCodes.Ldarg_0));
            instructions.Add(processor.Create(OpCodes.Ldstr, description));
            instructions.Add(exitInstruction);
            if (!ReturnsVoid(method))
            {
                instructions.Add(reload);
            }

            new InsertionAtEnd(processor, method).Run(instructions);
        }
Example #14
0
        public ScopeVariable(string name, string type, VariableDefinition variable)
        {
            Name = name;
              Type = type;

              Var = variable;
        }
Example #15
0
        private static void AddCollectionCode(PropertyDefinition property, bool isFirst, Collection<Instruction> ins, VariableDefinition resultVariable, MethodDefinition method, TypeDefinition type)
        {
            if (isFirst)
            {
                ins.Add(Instruction.Create(OpCodes.Ldc_I4_0));
                ins.Add(Instruction.Create(OpCodes.Stloc, resultVariable));
            }

            ins.If(
                c =>
                {
                    LoadVariable(property, c, type);

                },
                t =>
                {
                    LoadVariable(property, t, type);
                    var enumeratorVariable = method.Body.Variables.Add(property.Name + "Enumarator", ReferenceFinder.IEnumerator.TypeReference);
                    var currentVariable = method.Body.Variables.Add(property.Name + "Current", ReferenceFinder.Object.TypeReference);

                    GetEnumerator(t, enumeratorVariable);

                    AddCollectionLoop(resultVariable, t, enumeratorVariable, currentVariable);
                },
                f => { });
        }
 public GetClassMethodReplacementProvider(VariableDefinition invocationInfo, VariableDefinition classMethodReplacementProvider, 
     Func<ModuleDefinition, MethodReference> resolveGetProviderMethod)
 {
     _invocationInfo = invocationInfo;
     _classMethodReplacementProvider = classMethodReplacementProvider;
     _resolveGetProviderMethod = resolveGetProviderMethod;
 }
Example #17
0
        public void Visit(IBehaviorDefinition method, CustomAttribute attribute)
        {
            ILProcessor processor = method.Body.GetILProcessor();
            string description = attribute.Properties.Where(argument => (argument.Name == "Description")).First().Argument.Value as string;
            var listType = typeof(List<object>);
            var listVariable = new VariableDefinition("argumentz", method.Module.Import(listType));
            method.Body.Variables.Add(listVariable);
            var instructions = new List<Instruction>();
            instructions.Add(processor.Create(OpCodes.Newobj, method.Module.Import(listType.GetConstructor(new Type[] { }))));
            instructions.Add(processor.Create(OpCodes.Stloc, listVariable));

            int parameterIndex = 1;
            foreach (var parameter in method.Parameters)
            {
                instructions.Add(processor.Create(OpCodes.Ldloc, listVariable));
                instructions.Add(processor.Create(OpCodes.Ldarg, parameterIndex));
                if (parameter.ParameterType.IsPrimitive || parameter.ParameterType.IsValueType)
                    instructions.Add(processor.Create(OpCodes.Box, parameter.ParameterType));
                instructions.Add(processor.Create(OpCodes.Callvirt, method.Module.Import(listType.GetMethod("Add", new[] { typeof(object) }))));
                ++parameterIndex;
            }
            instructions.Add(processor.Create(OpCodes.Newobj, method.Module.Import(broadcastType.GetConstructor(new Type[] {}))));
            instructions.Add(processor.Create(OpCodes.Ldloc, listVariable));
            instructions.Add(processor.Create(OpCodes.Ldstr, description));
            instructions.Add(processor.Create(OpCodes.Callvirt, method.Module.Import(broadcastType.GetMethod("Run", new[] {listType, typeof(string)}))));

            new InsertionAtStart(processor, method).Run(instructions);
        }
 public GetClassMethodReplacementProvider(IMethodBodyRewriterParameters parameters, 
     Func<ModuleDefinition, MethodReference> resolveGetProviderMethod)
 {
     _invocationInfo = parameters.InvocationInfo;
     _classMethodReplacementProvider = parameters.ClassMethodReplacementProvider;
     _resolveGetProviderMethod = resolveGetProviderMethod;
 }
        private static AssemblyDefinition CreateTestAssembly()
        {
            var name = new AssemblyNameDefinition("TestArithmeticOperatorTurtleAdd", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestArithmeticOperatorTurtleAdd", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType);
            var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType);
            method.Parameters.Add(leftParam);
            method.Parameters.Add(rightParam);
            var resultVariable = new VariableDefinition(intType);
            method.Body.Variables.Add(resultVariable);

            var processor = method.Body.GetILProcessor();
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_1));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg_2));
            method.Body.Instructions.Add(processor.Create(OpCodes.Add));
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldloc, resultVariable));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ret));

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
    void InjectAsStreamReader(TypeDefinition targetType, FieldDefinition fieldDefinition)
    {
        AsStreamReaderMethod = new MethodDefinition("AsStreamReader", staticMethodAttributes, StreamReaderTypeReference);
        var streamVariable = new VariableDefinition(StreamTypeReference);
        AsStreamReaderMethod.Body.Variables.Add(streamVariable);
        var pathParam = new ParameterDefinition(ModuleDefinition.TypeSystem.String);
        AsStreamReaderMethod.Parameters.Add(pathParam);
        AsStreamReaderMethod.Body.InitLocals = true;
        var inst = AsStreamReaderMethod.Body.Instructions;

        var skipReturn = Instruction.Create(OpCodes.Nop);

        inst.Add(Instruction.Create(OpCodes.Ldsfld, fieldDefinition));
        inst.Add(Instruction.Create(OpCodes.Ldarg, pathParam));
        inst.Add(Instruction.Create(OpCodes.Callvirt, GetManifestResourceStreamMethod));

        inst.Add(Instruction.Create(OpCodes.Stloc, streamVariable));
        inst.Add(Instruction.Create(OpCodes.Ldloc, streamVariable));
        inst.Add(Instruction.Create(OpCodes.Brtrue_S, skipReturn));

        inst.Add(Instruction.Create(OpCodes.Ldnull));
        inst.Add(Instruction.Create(OpCodes.Ret));
        inst.Add(skipReturn);

        inst.Add(Instruction.Create(OpCodes.Ldloc, streamVariable));
        inst.Add(Instruction.Create(OpCodes.Newobj, StreamReaderConstructorReference));
        inst.Add(Instruction.Create(OpCodes.Ret));
        targetType.Methods.Add(AsStreamReaderMethod);
    }
 public void AddLocals(MethodDefinition hostMethod)
 {
     _constructorArguments = hostMethod.AddLocal<List<object>>();
     _currentArgument = hostMethod.AddLocal<object>();
     _methodContext = hostMethod.AddLocal<ITypeActivationContext>();
     _currentActivator = hostMethod.AddLocal<ITypeActivator>();
 }
Example #22
0
        /// <summary>
        /// Emits a call that obtains the hash code for the current service instance.
        /// </summary>
        /// <param name="il">The <see cref="ILProcessor"/> that points to the method body.</param>
        /// <param name="module">The target module.</param>
        /// <param name="serviceInstance">The local variable that contains the service instance.</param>
        private void GetServiceHash(ILProcessor il, ModuleDefinition module, VariableDefinition serviceInstance)
        {
            il.Emit(OpCodes.Ldloc, serviceInstance);

            var getHashCodeMethod = module.ImportMethod<object>("GetHashCode");
            il.Emit(OpCodes.Callvirt, getHashCodeMethod);
        }
        private static AssemblyDefinition CreateTestAssembly()
        {
            var name = new AssemblyNameDefinition("TestBranchConditionTurtle", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestBranchConditionTurtle", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var boolType = assembly.MainModule.Import(typeof(bool));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType);
            var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType);
            method.Parameters.Add(leftParam);
            method.Parameters.Add(rightParam);
            var resultVariable = new VariableDefinition(boolType);
            method.Body.Variables.Add(resultVariable);

            var processor = method.Body.GetILProcessor();
            Instruction loadReturnValueInstruction = processor.Create(OpCodes.Ldloc, resultVariable);
            Instruction storeTrueInReturnValueInstruction = processor.Create(OpCodes.Ldc_I4, -1);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, leftParam));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldarg, rightParam));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ceq));
            method.Body.Instructions.Add(processor.Create(OpCodes.Brtrue_S, storeTrueInReturnValueInstruction));
            method.Body.Instructions.Add(processor.Create(OpCodes.Ldc_I4, 0));
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(processor.Create(OpCodes.Br_S, loadReturnValueInstruction));
            method.Body.Instructions.Add(storeTrueInReturnValueInstruction);
            method.Body.Instructions.Add(processor.Create(OpCodes.Stloc, resultVariable));
            method.Body.Instructions.Add(loadReturnValueInstruction);
            method.Body.Instructions.Add(processor.Create(OpCodes.Ret));

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
Example #24
0
        public void Visit(IBehaviorDefinition behaviorDefinition, CustomAttribute attribute)
        {
            ILProcessor processor = behaviorDefinition.Body.GetILProcessor();
            var pingerDefinition = new VariableDefinition("pinger",
                                                         behaviorDefinition.Module.Import(pingType));
            behaviorDefinition.Body.Variables.Add(pingerDefinition);

            var start = new List<Instruction>
                            {
                                processor.Create(OpCodes.Ldstr, behaviorDefinition.Name),
                                processor.Create(OpCodes.Newobj,
                                                 behaviorDefinition.Module.Import(
                                                     pingType.GetConstructor(new[]{typeof(string)}))),
                                processor.Create(OpCodes.Stloc, pingerDefinition),
                                processor.Create(OpCodes.Ldloc, pingerDefinition),
                                processor.Create(OpCodes.Callvirt,
                                               behaviorDefinition.Module.Import(pingType.GetMethod("Start",
                                                                                                      new Type[] {}))),

                            };
            var end = new List<Instruction>
                          {
                              processor.Create(OpCodes.Ldloc, pingerDefinition),
                              processor.Create(OpCodes.Callvirt,
                                               behaviorDefinition.Module.Import(pingType.GetMethod("End",
                                                                                                      new Type[] {})))
                          };

            new InsertionAtStart(processor, behaviorDefinition).Run(start);
            new InsertionAtEnd(processor, behaviorDefinition).Run(end);
            foreach (var instruction in behaviorDefinition.Body.Instructions)
            {
                Console.Out.WriteLine("{0}/[{1}]: {2} {3}", instruction.Offset, Sequence(instruction.SequencePoint), instruction.OpCode, instruction.Operand);
            }
        }
 public InvokeMethodReplacement(Instruction executeOriginalInstructions, VariableDefinition methodReplacementProvider, VariableDefinition classMethodReplacementProvider, VariableDefinition invocationInfo)
 {
     _executeOriginalInstructions = executeOriginalInstructions;
     _methodReplacementProvider = methodReplacementProvider;
     _classMethodReplacementProvider = classMethodReplacementProvider;
     _invocationInfo = invocationInfo;
 }
    int AddBeforeAfterInvokerCall(int index, PropertyDefinition property)
    {
        var beforeVariable = new VariableDefinition(msCoreReferenceFinder.ObjectTypeReference);
        setMethodBody.Variables.Add(beforeVariable);
        var afterVariable = new VariableDefinition(msCoreReferenceFinder.ObjectTypeReference);
        setMethodBody.Variables.Add(afterVariable);
        var isVirtual = property.GetMethod.IsVirtual;
        var getMethod = property.GetMethod.GetGeneric();

        index = instructions.Insert(index,
                                    Instruction.Create(OpCodes.Ldarg_0),
                                    CreateCall(getMethod),
                                    //TODO: look into why this box is required
                                    Instruction.Create(OpCodes.Box, property.GetMethod.ReturnType),
                                    Instruction.Create(OpCodes.Stloc, afterVariable),
                                    Instruction.Create(OpCodes.Ldarg_0),
                                    Instruction.Create(OpCodes.Ldstr, property.Name),
                                    Instruction.Create(OpCodes.Ldloc, beforeVariable),
                                    Instruction.Create(OpCodes.Ldloc, afterVariable),
                                    CallEventInvoker()
            );

        instructions.Prepend(
            Instruction.Create(OpCodes.Ldarg_0),
            CreateCall(getMethod),
            //TODO: look into why this box is required
            Instruction.Create(OpCodes.Box, property.GetMethod.ReturnType),
            Instruction.Create(OpCodes.Stloc, beforeVariable));
        return index + 4;
    }
Example #27
0
        public void Visit(IBehaviorDefinition behaviorDefinition, CustomAttribute attribute)
        {
            ILProcessor processor = behaviorDefinition.Body.GetILProcessor();
            var pingerDefinition = new VariableDefinition("pinger",
                                                          behaviorDefinition.Module.Import(breakpointType));
            behaviorDefinition.Body.Variables.Add(pingerDefinition);
            var sequencedInstructions =
                behaviorDefinition.Body.Instructions.Where(instruction => instruction.SequencePoint != null).ToList();

            Console.Out.WriteLine(sequencedInstructions.Count);
            //            var extractedInstructions = Specific(sequencedInstructions, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 20, 21);
            var extractedInstructions = Filtered(sequencedInstructions);
            foreach (var instruction in extractedInstructions)
            {
                Type intType = typeof(int);
                var breakPointInstructions = new List<Instruction>
                                       {
                                           processor.Create(OpCodes.Newobj, behaviorDefinition.Module.Import(
                                                                                breakpointType.GetConstructor(new Type[]{}))),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.StartLine),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.StartColumn),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.EndLine),
                                           processor.Create(OpCodes.Ldc_I4, instruction.SequencePoint.EndColumn),
                                           processor.Create(OpCodes.Ldstr, instruction.SequencePoint.Document.Url),
                                           processor.Create(OpCodes.Call,
                                                            behaviorDefinition.Module.Import(breakpointType.GetMethod("Activate",
                                                                                                                      new[] {intType, intType, intType, intType, typeof(string)})))
                                       };
                breakPointInstructions.ForEach(bpr => processor.InsertBefore(instruction, bpr));
                foreach (var i in behaviorDefinition.Body.Instructions)
                {
                    Console.Out.WriteLine("{0}/[{1}]: {2} {3}", i.Offset, Sequence(i.SequencePoint), i.OpCode, i.Operand);
                }
            }
        }
Example #28
0
    int AddBeforeAfterInvokerCall(int index, PropertyDefinition property)
    {
        var beforeVariable = new VariableDefinition(typeSystem.Object);
        setMethodBody.Variables.Add(beforeVariable);
        var afterVariable = new VariableDefinition(typeSystem.Object);
        setMethodBody.Variables.Add(afterVariable);
        var getMethod = property.GetMethod.GetGeneric();

        index = instructions.Insert(index,
                                    Instruction.Create(OpCodes.Ldarg_0),
                                    CreateCall(getMethod),
                                    Instruction.Create(OpCodes.Box, property.GetMethod.ReturnType),
                                    Instruction.Create(OpCodes.Stloc, afterVariable),
                                    Instruction.Create(OpCodes.Ldarg_0),
                                    Instruction.Create(OpCodes.Ldstr, property.Name),
                                    Instruction.Create(OpCodes.Ldloc, beforeVariable),
                                    Instruction.Create(OpCodes.Ldloc, afterVariable),
                                    CallEventInvoker()
            );

        instructions.Prepend(
            Instruction.Create(OpCodes.Ldarg_0),
            CreateCall(getMethod),
            Instruction.Create(OpCodes.Box, property.GetMethod.ReturnType),
            Instruction.Create(OpCodes.Stloc, beforeVariable));
        return index + 4;
    }
 public static VariableDefinition AddV(this Collection<VariableDefinition> variables,
     TypeReference typeReference)
 {
     VariableDefinition variable = new VariableDefinition(typeReference);
     variables.Add(variable);
     return variable;
 }
 /// <summary>
 /// Emits the IL instructions that will store information about the method <paramref name="targetMethod">currently being executed</paramref>
 /// and stores the results into the <paramref name="invocationInfo">variable.</paramref>
 /// </summary>
 /// <param name="emitter">The <see cref="IEmitInvocationInfo"/> instance.</param>
 /// <param name="method">The method whose implementation will be intercepted.</param>
 /// <param name="targetMethod">The actual method that will contain the resulting instructions.</param>
 /// <param name="invocationInfo">The <see cref="VariableDefinition">local variable</see> that will store the current <see cref="IInvocationInfo"/> instance.</param>
 public static void Emit(this IEmitInvocationInfo emitter, MethodInfo method, MethodDefinition targetMethod,
                         VariableDefinition invocationInfo)
 {
     ModuleDefinition module = targetMethod.DeclaringType.Module;
     MethodReference interceptedMethod = module.Import(method);
     emitter.Emit(targetMethod, interceptedMethod, invocationInfo);
 }
Example #31
0
 public VariableIndex(int index)
 {
     this.variable = null;
     this.index    = index;
 }
Example #32
0
 static int GetVariableIndex(VariableDefinition variable)
 {
     return(variable.Index);
 }