Example #1
0
        private static MethodContext GetMethodContext(string caller, string path)
        {
            var key = caller + path;

            lock (Callers) {
                if (!Callers.ContainsKey(key))
                {
                    var context = new MethodContext();

                    var filename = path.Split('\\').Last().Replace(".cs", "");
                    var type     = ReflectionCache.Lookup(filename);
                    var method   = type.GetMethod(caller);

                    if (method != null)
                    {
                        var attributes = method.GetCustomAttributes(true);

                        context.Method           = method;
                        context.MethodAttributes = attributes.Cast <Attribute>().ToList();
                    }

                    Callers.Add(key, context);
                }

                return(Callers[key]);
            }
        }
Example #2
0
 private void MethodResolver(MethodContext context)
 {
     if (context.Method == GetMethod <ResolveMethodTests>(nameof(EmptyBodyTest)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(EmptyBodyReplace)));
     }
     else if (context.Method == GetMethod <ResolveMethodTests>(nameof(BodyImpTest)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(BodyImpReplace)));
     }
     else if (context.Method == GetMethod <ResolveMethodTests>(nameof(ReturnSimpleInt)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(ReturnSimpleIntReplace)));
     }
     else if (context.Method == GetMethod <ResolveMethodTests>(nameof(ReturnSimpleDouble)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(ReturnSimpleDoubleReplace)));
     }
     else if (context.Method == GetMethod <ResolveMethodTests>(nameof(ReturnSimpleObj)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(ReturnSimpleObjReplace)));
     }
     else if (context.Method == GetMethod <ResolveMethodTests>(nameof(LocalVariableNativeType)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(LocalVariableNativeTypeReplace)));
     }
     else if (context.Method == GetMethod <ResolveMethodTests>(nameof(LocalVariableReferenceType)))
     {
         context.ResolveMethod(GetMethod <ResolveMethodTests>(nameof(LocalVariableReferenceTypeReplace)));
     }
 }
Example #3
0
    public static SUnit TranslateMethodCall(Statement statement)
    {
        var expressions = statement.GetExpressions();

        // Give an empty SUnit if statement has no expressions.
        if (expressions.Count() == 0)
        {
            return(new SUnit(SUnitType.SingleMethodCall, "", "", "", new List <string>(), "void"));
        }

        // Build a minimal method context and declaration node required by SWUM.
        var                   exp  = expressions.First();
        string                type = exp.ResolveType().ToString();
        MethodContext         mc   = new MethodContext(type);
        MethodDeclarationNode mdn  = new MethodDeclarationNode(exp.ToString(), mc);

        // Apply the SWUM to our statement
        var swumRule = SetupBaseVerbRule();

        swumRule.InClass(mdn);
        swumRule.ConstructSwum(mdn);

        // Build and return SUnit from the SWUM
        SUnit sunit = new SUnit();

        sunit.action = GetAction(mdn);
        sunit.theme  = GetTheme(mdn);
        sunit.args   = GetArgs(mdn);

        return(sunit);
    }
Example #4
0
        /// <summary>
        /// Emits a sub instruction.
        /// </summary>
        /// <param name="instruction">The instruction.</param>
        /// <param name="context">The context.</param>
        /// <param name="builder">The builder.</param>
        public void Emit(Instruction instruction, MethodContext context, BuilderRef builder)
        {
            StackElement value2 = context.CurrentStack.Pop();
            StackElement value1 = context.CurrentStack.Pop();

            if (TypeHelper.IsFloatingPoint(value1) || TypeHelper.IsFloatingPoint(value2))
            {
                ValueRef result = LLVM.BuildFSub(builder, value1.Value, value2.Value, "subfp");
                context.CurrentStack.Push(new StackElement(result, value1.ILType, value1.Type));
            }
            else
            {
                bool isPtrVal1, isPtrVal2;
                CastHelper.HelpPossiblePtrCast(builder, ref value1, ref value2, out isPtrVal1, out isPtrVal2, "subcast");

                // If one of the two values is a pointer, then the result will be a pointer as well.
                if (isPtrVal1 || isPtrVal2)
                {
                    ValueRef      result          = LLVM.BuildSub(builder, value1.Value, value2.Value, "subptr");
                    TypeRef       resultingType   = (isPtrVal1 ? value1.Type : value2.Type);
                    TypeReference resultingILType = (isPtrVal1 ? value1.ILType : value2.ILType);
                    ValueRef      ptr             = LLVM.BuildIntToPtr(builder, result, resultingType, "ptr");
                    context.CurrentStack.Push(new StackElement(ptr, resultingILType, resultingType));
                }
                // Cast to different int size.
                else
                {
                    CastHelper.HelpIntCast(builder, ref value1, ref value2);
                    ValueRef result = LLVM.BuildSub(builder, value1.Value, value2.Value, "subi");
                    context.CurrentStack.Push(new StackElement(result, value1.ILType, value1.Type));
                }
            }
        }
        public void CompileMethod(MethodContext context)
        {
            // Print information about the method being compiled using reflection classes.
            MethodInfo methodInfo = context.MethodInfo;

            PerfManager.Instance.WriteLine("> JIT NopCodeInjector is called on method [{0}] with a StackSize {1}",
                                           methodInfo.Name, context.StackSize);

            // Generate a native code with a Ret + StackSize of the method
            CodeRef nativeCodeRef;

            if (context.StackSize > 0)
            {
                // If there is a stack, then, generate the RET + Stacksize opcode
                nativeCodeRef = context.AllocExecutionBlock(ReturnWithStackSize);
                Marshal.WriteInt16(nativeCodeRef.Pointer, 1, (short)context.StackSize);
            }
            else
            {
                // If there is no stack used, then RET
                nativeCodeRef = context.AllocExecutionBlock(ReturnWithNoStack);
            }

            // Inform NetAsm the native code to use for the method
            context.SetOutputNativeCode(nativeCodeRef);
        }
Example #6
0
        private void OnControllerProcess(object data)
        {
            object[]       array   = (object[])data;
            IMethodHandler handler = (IMethodHandler)array[0];
            ISession       context = (ISession)array[1];
            object         message = array[2];

            Implement.Session.Current = context;
            try
            {
                MethodContext mc = new MethodContext(mApplication, context, new object[] { context, message }, handler);

                mc.Execute();
                if (mc.Result != null)
                {
                    mApplication.Server.Send(mc.Result, context.Channel);
                }
            }
            catch (Exception e_)
            {
                "{0} invoke error ".Log4Error(e_, handler.ToString());
                context.Channel.InvokeError(e_);
            }
            finally
            {
                Implement.Session.Current = null;
            }
        }
        public void OnMethodInvoked(MethodContext context)
        {
            context.Arguments.SetArgument(0, 2);
            context.Arguments.SetArgument(1, "ab");
            context.Arguments.SetArgument(2, new SimpleStruct(2));
            context.Arguments.SetArgument(3, new SimpleClass(2));
            context.Arguments.SetArgument(4, new[] { 2, 1 });
            context.Arguments.SetArgument(5, new[] { "cd", "ab" });
            context.Arguments.SetArgument(6, new[] { new SimpleStruct(2), new SimpleStruct(1) });
            context.Arguments.SetArgument(7, new[] { new SimpleClass(2), new SimpleClass(1) });
            context.Arguments.SetArgument(8, new List <int> {
                2, 1
            });
            context.Arguments.SetArgument(9, new List <string> {
                "cd", "ab"
            });
            context.Arguments.SetArgument(10, new List <SimpleStruct> {
                new SimpleStruct(2), new SimpleStruct(1)
            });
            context.Arguments.SetArgument(11, new List <SimpleClass> {
                new SimpleClass(2), new SimpleClass(1)
            });

            context.Proceed();
        }
        public void Replace(MethodBody currentBody, ICollection<MethodReference> modifiedItems)
        {
            var invalidCalls = _callFilter.GetInvalidCalls(currentBody, modifiedItems);
            if (invalidCalls.Count == 0)
                return;

            var currentInstructions = currentBody.Instructions.Cast<Instruction>().ToArray();
            var stackCtor = _targetModule.ImportConstructor<Stack<object>>(new Type[0]);
            var IL = currentBody.CilWorker;

            var targetMethod = currentBody.Method;
            var currentArgument = targetMethod.AddLocal<object>();
            var currentArguments = targetMethod.AddLocal<Stack<object>>();

            currentBody.Instructions.Clear();

            // Create the stack that will hold the method arguments
            IL.Emit(OpCodes.Newobj, stackCtor);
            IL.Emit(OpCodes.Stloc, currentArguments);
            foreach (var currentInstruction in currentInstructions)
            {
                var currentMethod = currentInstruction.Operand as MethodReference;

                // Ignore any instructions that weren't affected by the
                // interface extraction
                if (currentMethod != null && invalidCalls.ContainsKey(currentMethod))
                {
                    var context = new MethodContext(IL, currentArguments, currentMethod, currentArgument);
                    _replaceMethodCall.Replace(context, _targetModule);
                }

                IL.Append(currentInstruction);
            }
        }
Example #9
0
        private MethodContext TryGetVerb(MethodInfo info)
        {
            var ctx = new MethodContext {
                ActionName = info.Name.ToLower()
            };


            foreach (var httpMethod in Method.Methods)
            {
                if (!ctx.ActionName.EndsWith(httpMethod.ToLower()))
                {
                    continue;
                }
                ctx.HttpMethod = httpMethod;
                ctx.ActionName = ctx.ActionName.Remove(ctx.ActionName.Length - httpMethod.Length);
                return(ctx);
            }

            var attributes = info.GetCustomAttributes(typeof(ValidForAttribute), true);

            if (attributes.Length == 1)
            {
                ctx.HttpMethod = ((ValidForAttribute)attributes[0]).Method;
                return(ctx);
            }

            return(null);
        }
Example #10
0
 private static void MethodResolver(MethodContext context)
 {
     if (context.Method == Utils.GetMethod <DetourMethodTest>(nameof(SimpleMethod)))
     {
         MethodInfo detour = Utils.GetMethod <DetourMethodTest>(nameof(SimpleMethodDetour));
         context.ResolveDetour(detour);
     }
     else if (context.Method == Utils.GetMethod <DetourMethodTest>(nameof(Sum)))
     {
         MethodInfo detour = Utils.GetMethod <DetourMethodTest>(nameof(Mul));
         context.ResolveDetour(detour);
     }
     else if (context.Method == Utils.GetMethod <DetourMethodTest>(nameof(SimpleMethodStatic)))
     {
         MethodInfo detour = Utils.GetMethod <DetourMethodTest>(nameof(SimpleMethodDetourStatic));
         context.ResolveDetour(detour);
     }
     else if (context.Method == Utils.GetMethod <DetourMethodTest>(nameof(SumStatic)))
     {
         MethodInfo detour = Utils.GetMethod <DetourMethodTest>(nameof(MulStatic));
         context.ResolveDetour(detour);
     }
     else if (context.Method.Name == nameof(GenericMethod))
     {
         MethodInfo detour = Utils.GetMethod <DetourMethodTest>(nameof(GenericMethodDetour));
         detour = detour.MakeGenericMethod(context.Method.GetGenericArguments());
         context.ResolveDetour(detour);
     }
     else if (context.Method.Name == nameof(GenericMethodStatic))
     {
         MethodInfo detour = Utils.GetMethod <DetourMethodTest>(nameof(GenericMethodStaticDetour));
         detour = detour.MakeGenericMethod(context.Method.GetGenericArguments());
         context.ResolveDetour(detour);
     }
 }
Example #11
0
            internal override void Read(MethodContext context, BinaryReader reader)
            {
                int id;

                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (Instruction.OpCode.OperandType)
                {
                case OperandType.ShortInlineVar:
                    id = reader.ReadByte();
                    break;

                case OperandType.InlineVar:
                    id = reader.ReadUInt16();
                    break;

                default:
                    throw new InvalidBranchException(
                              $"OpCode {Instruction.OpCode}, operand type {Instruction.OpCode.OperandType} doesn't match {GetType().Name}");
                }
                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (context.MethodBody == null)
                {
                    Value = new MsilLocal(id);
                }
                else
                {
                    Value = new MsilLocal(context.MethodBody.LocalVariables[id]);
                }
            }
Example #12
0
            internal override void Read(MethodContext context, BinaryReader reader)
            {
                int id;

                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (Instruction.OpCode.OperandType)
                {
                case OperandType.ShortInlineVar:
                    id = reader.ReadByte();
                    break;

                case OperandType.InlineVar:
                    id = reader.ReadUInt16();
                    break;

                default:
                    throw new InvalidBranchException(
                              $"OpCode {Instruction.OpCode}, operand type {Instruction.OpCode.OperandType} doesn't match {GetType().Name}");
                }

                if (id == 0 && !context.Method.IsStatic)
                {
                    throw new ArgumentException("Haven't figured out how to ldarg with the \"this\" argument");
                }
                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (context.Method == null)
                {
                    Value = new MsilArgument(id);
                }
                else
                {
                    Value = new MsilArgument(context.Method.GetParameters()[id - (context.Method.IsStatic ? 0 : 1)]);
                }
            }
Example #13
0
        public void Execute(MethodContext context, MethodState state, object operand = null)
        {
            MethodToken methodDef = (operand as MethodToken);

            if (methodDef == null)
            {
                throw new ArgumentException("Incorrect or null method definition");
            }
            MethodDesc method = null;

            if (methodDef.Owner != null)
            {
                TypeObject owner = context.TypesHeap.GetTypeObject(methodDef.Owner);
                method = owner.VTable.GetMethod(methodDef);
            }
            else
            {
                method = context.TypesHeap.GetGlobalMethod(methodDef);
            }

            if (method == null)
            {
                throw new InvalidOperationException("Method described by the provided metadata was not found in type's vtable");
            }

            state.CallMethod            = method;
            state.ExecutionInterruption = ExecutionInterruption.Call;
        }
        protected override void StoreObject(MethodContext method, string key, object value)
        {
            if (cache.ContainsKey(key))
                cache.Remove(key);

            cache.Add(key, value);
        }
Example #15
0
	public MethodContext method() {
		MethodContext _localctx = new MethodContext(Context, State);
		EnterRule(_localctx, 6, RULE_method);
		try {
			EnterOuterAlt(_localctx, 1);
			{
			State = 48; Match(ID);
			State = 49; Match(T__3);
			State = 50; args_def();
			State = 51; Match(T__4);
			State = 52; Match(T__5);
			State = 53; Match(TYPE);
			State = 54; Match(T__1);
			State = 55; expr(0);
			State = 56; Match(T__2);
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}
        public void OnMethodInvoked(MethodContext context)
        {
            context.Arguments.SetArgument(0, 2);
            context.Arguments.SetArgument(1, "ab");

            context.Proceed();
        }
Example #17
0
        /// <summary>
        /// Gets the content of a method as an instruction stream
        /// </summary>
        /// <param name="method">Method to examine</param>
        /// <returns>instruction stream</returns>
        public static IEnumerable <MsilInstruction> ReadInstructions(MethodBase method)
        {
            var context = new MethodContext(method);

            context.Read();
            return(context.Instructions);
        }
        public void CompileMethod(MethodContext context)
        {
            MethodInfo methodInfo = context.MethodInfo;

            PerfManager.Instance.WriteLine("> JIT CodeInjector is called on method [{0}]", methodInfo.Name);
            if (methodInfo.Name == "NetAsmAdd")
            {
                // Output the native code with the C code (see TestStaticCodeInjection class)
                context.SetOutputNativeCode(new byte[] { 0x8b, 0x44, 0x24, 0x04, 0x03, 0xc2, 0xc2, 0x04, 0x00 });
            }
            else if (methodInfo.Name == "NetAsmAddFromDll")
            {
                CodeRef referenceToDllFunction = CodeRef.BindToDllFunction("NetAsmDemoCLib.dll", "NetAsmAddInC");
                // Set the native code to use the DLL function
                context.SetOutputNativeCode(referenceToDllFunction);
            }
            else if (methodInfo.Name == "NetAsmIndirectCaller")
            {
                // Demonstrate how to call a clr method from a native method.
                MethodInfo info = typeof(TestDynamicCodeInjection).GetMethod("ManagedMethodCalledByNetAsm");
                // Get the pointer to the method ManagedMethodCalledByNetAsm
                IntPtr pointerToFunction = info.MethodHandle.GetFunctionPointer();
                // Generate an execution block with the template code nativeIndirectCall
                CodeRef codeRef = context.AllocExecutionBlock(nativeIndirectCall);
                // Calculate relative JMP address
                IntPtr jmpRelativeAddress = new IntPtr(pointerToFunction.ToInt64() - (codeRef.Pointer.ToInt64() + nativeIndirectCall.Length));
                // Write the relative JMP address just after the JMP opcode (0xE9)
                Marshal.WriteIntPtr(codeRef.Pointer, 1, jmpRelativeAddress);
                // Set output native code
                context.SetOutputNativeCode(codeRef);
            }
        }
Example #19
0
        public void TestToPlainString_NotParsed()
        {
            var                   formals = new FormalParameterRecord[] { new FormalParameterRecord("SGVData*", false, "p"), new FormalParameterRecord("ASSchedule*", false, "p2") };
            MethodContext         mc      = new MethodContext("int", true, "MyClass", formals, true, false, false);
            MethodDeclarationNode mdn     = new MethodDeclarationNode("CalcNewValue", mc);

            Assert.AreEqual("CalcNewValue", mdn.ToPlainString());
        }
Example #20
0
 public void Execute(MethodContext context, MethodState state, object operand = null)
 {
     if (context.EvalStack.Count < 1)
     {
         throw new InvalidStackSizeException("Stack is empty");
     }
     context.EvalStack.Pop();
 }
Example #21
0
        public void OnMethodInvoked(MethodContext context)
        {
            context.Proceed();

            var value = (int)context.ReturnValue;

            context.SetReturnValue(value + 1);
        }
        public void OnMethodInvoked(MethodContext context)
        {
            context.Arguments.SetArgument(0, new InheritsFromSimpleClass(2));
            context.Arguments.SetArgument(1, new[] { "ab" });
            context.Arguments.SetArgument(2, new[] { 2 });

            context.Proceed();
        }
Example #23
0
        public override void OnException(MethodContext context)
        {
            Console.WriteLine(context.FullName + " " + this.GetType().Name + " OnException");
            var mthdName = context.FullName;

            context.WillReturn(false);
            LogHelper.LogInfo(mthdName + " Ā·Ā¢Ć‰ĆŗƒƬĀ³Ā£Ā£Āŗ" + context.Exception.AllMessage());
        }
Example #24
0
        /// <summary>
        /// Method that will be called upon exception
        /// </summary>
        /// <param name="context">MethodContext</param>
        /// <param name="ex">Exception that occurred while executing weaved method</param>
        internal override void OnException(MethodContext context, System.Exception ex)
        {
            var attr    = context.Attributes.Where(x => x is LogAttribute).FirstOrDefault() as LogAttribute;
            var logType = attr != null ? attr.Type : LoggingType.Debug;

            Backend.Log(context, logType, "Error {0}({1})", ex, context.Method.Name, string.Join(",",
                                                                                                 context.Arguments.Select(x => string.Format("{0} = {1}", x.Name, x.Value))));
        }
Example #25
0
 private static void MethodResolver(MethodContext context)
 {
     if (context.Method.DeclaringType != null &&
         context.Method.DeclaringType.GetCustomAttribute <ClassRecompileTestAttribute>() != null)
     {
         MethodsCompiled.Add(context.Method);
     }
 }
        public void OnMethodInvoked(MethodContext context)
        {
            context.Proceed();

            var ret = (string)context.ReturnValue;

            context.SetReturnValue(ret + "b");
        }
Example #27
0
        /// <summary>
        /// Emits a ldftn instruction.
        /// </summary>
        /// <param name="instruction">The instruction.</param>
        /// <param name="context">The context.</param>
        /// <param name="builder">The builder.</param>
        public void Emit(Instruction instruction, MethodContext context, BuilderRef builder)
        {
            MethodDefinition method  = (MethodDefinition)instruction.Operand;
            ValueRef         result  = LLVM.BuildIntToPtr(builder, context.Compiler.Lookup.GetFunction(NameHelper.CreateMethodName(method)).Value, TypeHelper.NativeIntType, "ldftn");
            StackElement     element = new StackElement(result, typeof(IntPtr).GetTypeReference(), TypeHelper.NativeIntType);

            context.CurrentStack.Push(element);
        }
        public void OnMethodInvoked(MethodContext context)
        {
            context.Arguments.SetArgument(0, 2);
            context.Arguments.SetArgument(1, new SimpleStruct(2));
            context.Arguments.SetArgument(2, new SimpleClass(2));

            context.Proceed();
        }
Example #29
0
        public void OnMethodInvoked(MethodContext context)
        {
            context.Proceed();

            var newEnumerable = CreateNewEnumerable(context.ReturnValue as IEnumerable <string>);

            context.SetReturnValue(newEnumerable);
        }
Example #30
0
        /// <summary>
        /// Method that will be called prior to success of weaved methods
        /// </summary>
        /// <param name="context">MethodContext</param>
        internal override void OnSuccess(MethodContext context)
        {
            var attr    = context.Attributes.Where(x => x is LogAttribute).FirstOrDefault() as LogAttribute;
            var logType = attr != null ? attr.Type : LoggingType.Debug;

            Backend.Log(context, logType, "Completed {0}({1}) -> {2}", null, context.Method.Name, string.Join(",",
                                                                                                              context.Arguments.Select(x => string.Format("{0} = {1}", x.Name, x.Value))), context.Returns);
        }
Example #31
0
        public void Select(MethodContext ctxt, string selector)
        {
            var elements = new ElementsQuery(browser);

            ctxt.Elements(elements);

            elements.AddSelect(selector);
        }
Example #32
0
 public bool AddMethod(MethodContext method)
 {
     if (this.MethodDict.Contains(method.ProcDesc))
     {
         return(false);
     }
     MethodDict.Add(method.ProcDesc, method);
     return(true);
 }
        /// <summary>
        /// Method executed after real method execution.
        /// </summary>
        /// <param name="method"></param>
        public override sealed void MethodExit(MethodContext method)
        {
            string key = (string)method["Cache.Key"];

            bool cacheHit = (bool)method["Cache.Hit"];
            if (cacheHit)
                this.TouchObject(method, key, method.ReturnValue);
            else
                this.StoreObject(method, key, method.ReturnValue);
        }
        /// <summary>
        /// Get key for a method.
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        protected virtual string GetKey(MethodContext method)
        {
            StringBuilder sb = new StringBuilder();
            sb
                .Append(method.RealObject.GetType().Name)
                .Append(".")
                .Append(method.Method.Name);
            foreach (var param in method.Parameters)
                sb.Append("|").Append(param.Name).Append(":").Append(param.GetStringValue());

            return sb.ToString();
        }
 public void TestConstructor_Context() {
     MethodContext mc = new MethodContext("STATUS", false);
     MethodDeclarationNode mdn = new MethodDeclarationNode("MyMethod", mc);
     Assert.AreEqual("MyMethod", mdn.Name);
     Assert.AreEqual(mc, mdn.Context);
     Assert.AreEqual(MethodRole.Unknown, mdn.Role);
     Assert.IsNull(mdn.FormalParameters);
     Assert.IsNull(mdn.DeclaringClass);
     Assert.IsNull(mdn.ReturnType);
     Assert.IsNull(mdn.Action);
     Assert.IsNull(mdn.Theme);
     Assert.IsNull(mdn.SecondaryArguments);
     Assert.IsNull(mdn.UnknownArguments);
     Assert.IsFalse(mdn.IsReactive);
     Assert.IsFalse(mdn.IsConstructor);
     Assert.IsFalse(mdn.IsDestructor);
 }
Example #36
0
 public ImporterFactory(MethodContext context)
 {
     this.context = context;
 }
Example #37
0
        private MethodContext TryGetVerb(MethodInfo info)
        {
            var ctx = new MethodContext {ActionName = info.Name.ToLower()};


            foreach (var httpMethod in Method.Methods)
            {
                if (!ctx.ActionName.EndsWith(httpMethod.ToLower())) continue;
                ctx.HttpMethod = httpMethod;
                ctx.ActionName = ctx.ActionName.Remove(ctx.ActionName.Length - httpMethod.Length);
                return ctx;
            }

            var attributes = info.GetCustomAttributes(typeof (ValidForAttribute), true);
            if (attributes.Length == 1)
            {
                ctx.HttpMethod = ((ValidForAttribute) attributes[0]).Method;
                return ctx;
            }

            return null;
        }
		void UnwrapRefArgument(MethodContext methodContext, ParamContext parContext)
		{
			methodContext.WrapperParams.Add(parContext.ArgDeclaration);
			
			CodeVariableDeclarationStatement tmpVariableDeclaration = new CodeVariableDeclarationStatement(parContext.RawType, ((parContext.Direction==FieldDirection.Ref)?"ref":"out") + "_" + parContext.Name);
			if (parContext.Direction == FieldDirection.Ref) {
				tmpVariableDeclaration.InitExpression = parContext.UnwrappedArgExpression;
			}
			CodeExpression tmpVariableExpression = new CodeVariableReferenceExpression(tmpVariableDeclaration.Name);
			CodeExpression tmpVariableDirectionalExpression = new CodeDirectionExpression(parContext.Direction, tmpVariableExpression);
			methodContext.DoBeforeInvoke.Add(tmpVariableDeclaration);
			
			methodContext.BaseMethodInvokeParams.Add(tmpVariableDirectionalExpression);
			
			CodeAssignStatement assignExpression = new CodeAssignStatement(parContext.ArgRefExpression, Wrap(parContext.RawType, tmpVariableExpression));
			methodContext.DoAfterInvoke.Add(assignExpression);
		}
 public void TestToPlainString_Context() {
     var formals = new FormalParameterRecord[] { new FormalParameterRecord("SGVData*", false, "p"), new FormalParameterRecord("ASSchedule*", false, "p2") };
     MethodContext mc = new MethodContext("int", true, "MyClass", formals, true, false, false);
     MethodDeclarationNode mdn = new MethodDeclarationNode("CalcNewValue", mc);
     var splitter = new ConservativeIdSplitter();
     mdn.Parse(splitter);
     mdn.AssignStructuralInformation(splitter, new UnigramTagger());
     Assert.AreEqual("Calc New Value", mdn.ToPlainString());
 }
 /// <summary>
 /// When implemented, allows to define new expiration date.
 /// </summary>
 /// <param name="method"></param>
 /// <param name="key"></param>
 /// <param name="obj"></param>
 protected virtual void TouchObject(MethodContext method, string key, object obj)
 {
 }
 public void TestToPlainString_NotParsed() {
     var formals = new FormalParameterRecord[] { new FormalParameterRecord("SGVData*", false, "p"), new FormalParameterRecord("ASSchedule*", false, "p2") };
     MethodContext mc = new MethodContext("int", true, "MyClass", formals, true, false, false);
     MethodDeclarationNode mdn = new MethodDeclarationNode("CalcNewValue", mc);
     Assert.AreEqual("CalcNewValue", mdn.ToPlainString());
 }
 public void TestAssignStructuralInformation() {
     var formals = new FormalParameterRecord[] { new FormalParameterRecord("SGVData*", false, "p"), new FormalParameterRecord("ASSchedule*", false, "p2") };
     MethodContext mc = new MethodContext("int", true, "MyClass", formals, true, false, false);
     MethodDeclarationNode mdn = new MethodDeclarationNode("MyMethod", mc);
     mdn.Parse(new NullSplitter());
     mdn.AssignStructuralInformation(new NullSplitter(), new NullTagger());
     Assert.AreEqual(Location.Name, mdn.ParsedName.Location);
     Assert.AreEqual("int", mdn.ReturnType.Name);
     Assert.IsTrue(mdn.ReturnType.IsPrimitive);
     Assert.AreEqual("MyClass", mdn.DeclaringClass.Name);
     Assert.AreEqual(2, mdn.FormalParameters.Count);
     Assert.AreEqual("SGVData*", mdn.FormalParameters[0].Type.Name);
     Assert.AreEqual("p", mdn.FormalParameters[0].Name);
     Assert.AreEqual("ASSchedule*", mdn.FormalParameters[1].Type.Name);
     Assert.AreEqual("p2", mdn.FormalParameters[1].Name);
 }
        int WbemNative.IWbemServices.ExecMethodAsync(
            string objectPath,
            string methodName,
            Int32 flags,
            WbemNative.IWbemContext wbemContext,
            WbemNative.IWbemClassObject wbemInParams,
            WbemNative.IWbemObjectSink wbemSink)
        {
            if (wbemContext == null || wbemInParams == null || wbemSink == null || this.wbemServices == null)
                return (int)WbemNative.WbemStatus.WBEM_E_INVALID_PARAMETER;

            int result = (int)WbemNative.WbemStatus.WBEM_S_NO_ERROR;

            try
            {
                ObjectPathRegex objPathRegex = new ObjectPathRegex(objectPath);
                ParameterContext parms = new ParameterContext(objPathRegex.ClassName, this.wbemServices, wbemContext, wbemSink);
                WbemInstance wbemInstance = new WbemInstance(parms, objPathRegex);

                MethodContext methodContext = new MethodContext(parms, methodName, wbemInParams, wbemInstance);
                IWmiProvider wmiProvider = this.GetProvider(parms.ClassName);
                if (!wmiProvider.InvokeMethod(methodContext))
                {
                    result = (int)WbemNative.WbemStatus.WBEM_E_NOT_FOUND;
                }

                WbemException.ThrowIfFail(wbemSink.SetStatus(
                    (int)WbemNative.tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE,
                    (int)result,
                    null,
                    null));
            }
            catch (WbemException e)
            {
                DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                   (ushort)System.Runtime.Diagnostics.EventLogCategory.Wmi,
                   (uint)System.Runtime.Diagnostics.EventLogEventId.WmiExecMethodFailed,
                   e.ToString());
                result = e.ErrorCode;
                wbemSink.SetStatus((int)WbemNative.tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE,
                    result, null, null);
            }
#pragma warning suppress 56500 // covered by FxCOP
            catch (Exception e)
            {
                DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error,
                   (ushort)System.Runtime.Diagnostics.EventLogCategory.Wmi,
                   (uint)System.Runtime.Diagnostics.EventLogEventId.WmiExecMethodFailed,
                   e.ToString());
                result = (int)WbemNative.WbemStatus.WBEM_E_FAILED;
                wbemSink.SetStatus((int)WbemNative.tag_WBEM_STATUS_TYPE.WBEM_STATUS_COMPLETE,
                    (int)result, null, null);
            }
            finally
            {
                Marshal.ReleaseComObject(wbemSink);
            }
            return result;
        }
 public override void MethodEnter(MethodContext method)
 {
     if (InterceptStartCallback != null)
         InterceptStartCallback(method);
 }
	public MethodContext method() {
		MethodContext _localctx = new MethodContext(Context, State);
		EnterRule(_localctx, 10, RULE_method);
		int _la;
		try {
			EnterOuterAlt(_localctx, 1);
			{
			State = 816; k_method();
			State = 821;
			ErrorHandler.Sync(this);
			_la = TokenStream.La(1);
			while (_la==SCOL) {
				{
				{
				State = 817; Match(SCOL);
				State = 818; other_param();
				}
				}
				State = 823;
				ErrorHandler.Sync(this);
				_la = TokenStream.La(1);
			}
			State = 824; Match(COL);
			State = 825; iana_token();
			State = 826; Match(CRLF);
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			ErrorHandler.ReportError(this, re);
			ErrorHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}
 /// <summary>
 /// Log Entry
 /// </summary>
 /// <param name="method"></param>
 /// <param name="elapsed"></param>
 /// <param name="returnValue"></param>
 public LogEntry(MethodContext method, TimeSpan elapsed, object returnValue)
 {
     this.Method = method;
     this.Elapsed = elapsed;
     this.ReturnValue = returnValue;
 }
 /// <summary>
 /// Method executed after real method execution.
 /// </summary>
 /// <param name="method"></param>
 public override sealed void MethodExit(MethodContext method)
 {
     var sw = method.GetValue("sw") as Stopwatch;
     var logEntry = new LogEntry(method, sw.Elapsed, method.ReturnValue);
     this.InsertLog(logEntry);
 }
		void UnwrapArrayArgument(MethodContext methodContext, ParamContext parContext)
		{
			//OUTPUT:
			//		
			//		public void void__array(Test[] arg)
			//		{
			//			Debugger.Interop.CorDebug.Test[] array_arg = new Debugger.Interop.CorDebug.Test[arg.Length];
			//			for (int i = 0; (i < arg.Length); i = (i + 1))
			//			{
			//				if ((arg[i] != null))
			//				{
			//					array_arg[i] = arg[i].WrappedObject;
			//				}
			//			}
			//			this.WrappedObject.void__array(array_arg);
			//			for (int i = 0; (i < arg.Length); i = (i + 1))
			//			{
			//				if ((array_arg[i] != null))
			//				{
			//					arg[i] = Test.Wrap(array_arg[i]);
			//				} else
			//				{
			//					arg[i] = null;
			//				}
			//			}
			//		}
			
			methodContext.WrapperParams.Add(parContext.ArgDeclaration);
			
			string rawArrayName = "array_" + parContext.Name;
			
			CodeExpression arg_Length =
				// arg.Length
				new CodePropertyReferenceExpression(parContext.ArgRefExpression, "Length");
			CodeExpression i =
				// i
				new CodeVariableReferenceExpression("i");
			CodeStatement loopInit =
				// int i = 0
				new CodeVariableDeclarationStatement(typeof(int), "i", new CodePrimitiveExpression(0));
			CodeExpression loopCondition =
				// (i < arg.Length)
				new CodeBinaryOperatorExpression(
					i,
					CodeBinaryOperatorType.LessThan,
					arg_Length);
			CodeStatement loopIteration =
				// i = (i + 1)
				new CodeAssignStatement(
					i,
					new CodeBinaryOperatorExpression(
						i,
						CodeBinaryOperatorType.Add,
						new CodePrimitiveExpression(1)));
			CodeExpression arg_i =
				// arg[i]
				new CodeIndexerExpression(
					parContext.ArgRefExpression,
					i);
			CodeVariableReferenceExpression array_arg =
				// array_arg
				new CodeVariableReferenceExpression(rawArrayName);
			CodeExpression array_arg_i =
				// array_arg[i]
				new CodeIndexerExpression(
					array_arg,
					i);
			
			// Debugger.Interop.CorDebug.Test[] array_arg = new Debugger.Interop.CorDebug.Test[arg.Length];
			methodContext.DoBeforeInvoke.Add(
				new CodeVariableDeclarationStatement(
					new CodeTypeReference(parContext.RawType),
					array_arg.VariableName,
					new CodeArrayCreateExpression(parContext.RawType, arg_Length)));
			
			methodContext.DoBeforeInvoke.Add(
				new CodeIterationStatement(
					loopInit,
					loopCondition,
					loopIteration,
					// if
					new CodeConditionStatement(
						// (arg[i] != null)
						new CodeBinaryOperatorExpression(
							arg_i,
							CodeBinaryOperatorType.IdentityInequality,
							new CodePrimitiveExpression(null)),
						// array_arg[i] = arg[i].WrappedObject;
						new CodeAssignStatement(
							array_arg_i,
							Unwrap(parContext.RawType, arg_i)))));
			
			methodContext.DoAfterInvoke.Add(
				new CodeIterationStatement(
					loopInit,
					loopCondition,
					loopIteration,
					// if
					new CodeConditionStatement(
						// (array_arg[i] != null)
						new CodeBinaryOperatorExpression(
							array_arg_i,
							CodeBinaryOperatorType.IdentityInequality,
							new CodePrimitiveExpression(null)),
						//
						new CodeStatement [] {
							// arg[i] = Test.Wrap(array_arg[i]);
							new CodeAssignStatement(
								arg_i,
								Wrap(
									parContext.RawType.Assembly.GetType(parContext.RawType.FullName.Replace("[]","")),
									array_arg_i))},
						// else
						new CodeStatement [] {
							// arg[i] = null;
							new CodeAssignStatement(
								arg_i,
								new CodePrimitiveExpression(null))})));
			
			methodContext.BaseMethodInvokeParams.Add(array_arg);
		}
        public void TestGetParse() {
            MethodContext mc = new MethodContext("int", true, "MyClass", null, true, false, false);
            MethodDeclarationNode mdn = new MethodDeclarationNode("CalcNewValue", mc);
            UnigramSwumBuilder builder = new UnigramSwumBuilder();
            builder.ApplyRules(mdn);

            var parsedName = mdn.GetParse();
            Assert.AreEqual(3, parsedName.Size());
            Assert.AreEqual("Calc", parsedName[0].Text);
            Assert.AreEqual(PartOfSpeechTag.Verb, parsedName[0].Tag);
            Assert.AreEqual("New", parsedName[1].Text);
            Assert.AreEqual(PartOfSpeechTag.NounModifier, parsedName[1].Tag);
            Assert.AreEqual("Value", parsedName[2].Text);
            Assert.AreEqual(PartOfSpeechTag.NounIgnorable, parsedName[2].Tag);
        }
Example #50
0
 /// <summary>
 /// Creates a new MethodDeclarationNode with the given method name and context.
 /// </summary>
 /// <param name="name">The name of the method.</param>
 /// <param name="context">The method's context.</param>
 public MethodDeclarationNode(string name, MethodContext context)
     : base(name) {
     this.Context = context;
 }
 protected override object GetObject(MethodContext method, string key)
 {
     object ret;
     cache.TryGetValue(key, out ret);
     return ret;
 }
		CodeTypeMember MakeMember(MethodInfo method)
		{
			MethodContext methodContext = new MethodContext(this, method);
			
			ParameterInfo[] pars = method.GetParameters();
			for(int i = 0; i < pars.Length; i++) {
				ParamContext parContext = new ParamContext(this, pars[i]);
				
				if (parContext.IsWrapped) {
					if (parContext.Direction == FieldDirection.In) {
						if (pars[i].ParameterType.IsArray) {
							UnwrapArrayArgument(methodContext, parContext);
						} else {
							UnwrapArgument(methodContext, parContext);
						}
					} else {
						UnwrapRefArgument(methodContext, parContext);
					}
				} else {
					PassArgument(methodContext, parContext);
				}
				
				// If last parameter is 'out' and method returns void
				if (i == pars.Length - 1 &&
				    parContext.Direction == FieldDirection.Out &&
				    methodContext.RawReturnType == typeof(void)) {
					
					// Placeholder for the parameter
					methodContext.DoBeforeInvoke.Insert(0,
						new CodeVariableDeclarationStatement(parContext.WrappedType, parContext.Name));
					// Remove the parameter
					methodContext.WrapperParams.RemoveAt(methodContext.WrapperParams.Count - 1);
					
					methodContext.WrappedReturnType = parContext.WrappedType;
					methodContext.DoAfterInvoke.Add(
						new CodeMethodReturnStatement(
							new CodeVariableReferenceExpression(parContext.Name)));
				}
			}
			
			if (methodContext.WrapperParams.Count == 0) {
				if (methodContext.Name.StartsWith("Is")) {
					methodContext.CodeMemberMethod = new CodeMemberProperty();
				}
				if (methodContext.Name.StartsWith("Get")) {
					methodContext.CodeMemberMethod = new CodeMemberProperty();
					methodContext.Name = methodContext.Name.Remove(0, 3);
				}
			}
			
			return methodContext.Emit();
		}
 public override void ExceptionFilter(MethodContext method, Exception exception)
 {
     if (DefaultHandler != null)
         DefaultHandler(exception);
 }
Example #54
0
 public MethodExtension(MethodContext context)
 {
     Context = context;
 }
 /// <summary>
 /// Gets object from defined cache storage. Should be implemented in derived class.
 /// </summary>
 /// <param name="method"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 protected abstract object GetObject(MethodContext method, string key);
		void UnwrapArgument(MethodContext methodContext, ParamContext parContext)
		{
			methodContext.WrapperParams.Add(parContext.ArgDeclaration);
			methodContext.BaseMethodInvokeParams.Add(parContext.UnwrappedDirectionalArgExpression);
		}
 public override void MethodExit(MethodContext method)
 {
     if (InterceptEndCallback != null)
         InterceptEndCallback(method);
 }
 public MethodCloneFactory(MethodContext context)
 {
     this.context = context;
 }
 int WbemNative.IWbemServices.ExecMethodAsync(string objectPath, string methodName, int flags, WbemNative.IWbemContext wbemContext, WbemNative.IWbemClassObject wbemInParams, WbemNative.IWbemObjectSink wbemSink)
 {
     if (((wbemContext == null) || (wbemInParams == null)) || ((wbemSink == null) || (this.wbemServices == null)))
     {
         return -2147217400;
     }
     int hResult = 0;
     try
     {
         ObjectPathRegex objPathRegex = new ObjectPathRegex(objectPath);
         ParameterContext parms = new ParameterContext(objPathRegex.ClassName, this.wbemServices, wbemContext, wbemSink);
         WbemInstance wbemInstance = new WbemInstance(parms, objPathRegex);
         MethodContext method = new MethodContext(parms, methodName, wbemInParams, wbemInstance);
         if (!this.GetProvider(parms.ClassName).InvokeMethod(method))
         {
             hResult = -2147217406;
         }
         WbemException.ThrowIfFail(wbemSink.SetStatus(0, hResult, null, null));
     }
     catch (WbemException exception)
     {
         DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.Wmi, (EventLogEventId) (-1073610735), new string[] { exception.ToString() });
         hResult = exception.ErrorCode;
         wbemSink.SetStatus(0, hResult, null, null);
     }
     catch (Exception exception2)
     {
         DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.Wmi, (EventLogEventId) (-1073610735), new string[] { exception2.ToString() });
         hResult = -2147217407;
         wbemSink.SetStatus(0, hResult, null, null);
     }
     finally
     {
         Marshal.ReleaseComObject(wbemSink);
     }
     return hResult;
 }
 /// <summary>
 /// Sets object from defined cache storage. Should be implemented in derived class.
 /// </summary>
 /// <param name="method"></param>
 /// <param name="key"></param>
 /// <param name="obj"></param>
 protected abstract void StoreObject(MethodContext method, string key, object obj);