public async Task AG0037_WithOwnedByAttributeOnClass_ShowsNoWarning()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(TestFixtureAttribute).Assembly, typeof(OwnedByAttribute).Assembly },
                Code       = @"
					using NUnit.Framework;
					using Agoda.Analyzers.Test.AgodaCustom;

					namespace Agoda.Website.SeleniumTests
					{
						[OwnedBy(Team.Team1)]
						class TestClass
						{
							[Test]
							public void GoodMethod() 
							{
							}

							[Test]
							public void AnotherGoodMethod() 
							{
							}
						}
					}"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
Exemple #2
0
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var amd = stack.QueryAttribute <AsyncMethodDecompiler>();

            if (amd != null && amd.ImplStyle == EAsyncImplStyle.FSM)
            {
                return(false);
            }

            object[] outArgs;
            object   result;

            stack.TryGetReturnValueSample((MethodInfo)callee, args, out outArgs, out result);

            var fspec = new FunctionSpec(typeof(Task))
            {
                CILRep = callee
            };
            var fcall = new FunctionCall()
            {
                Callee     = fspec,
                Arguments  = args.Select(a => a.Expr).ToArray(),
                ResultType = TypeDescriptor.GetTypeOf(result)
            };

            stack.Push(fcall, result);

            return(true);
        }
Exemple #3
0
        public async Task AG0018_ShouldBeAllowedWhenCreateAMethodWhichReturnInterfaces()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(TestFixtureAttribute).Assembly },
                Code       = @"
                    namespace Tests
                    {
                        using System.Collections.Generic;
                        using System.Collections.ObjectModel;
                        public class ServerNamesProvider
                        {
                            public IList<double> LocalServerV2 { get; set; }
                            public ISet<int> GetServerSetV2() { return null; }
                            public IList<string> GetServerFullNames() { return null; }        
                            public IDictionary<string, string> GetServerDnsV2() { return null; }
                            public IReadOnlyDictionary<string, int> GetNumberOfServerV2() { return null; }
                            public KeyedCollection<string, string> GetServerDnsV3() { return null; }
                            public byte[] GetRawData() { return null; }
                            public int NumberOfServer { get; set; }
                            public byte[] RawData { get; set; }
                            public string DNSName { get; set; }
                        }
                    }"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
Exemple #4
0
        public async Task AG0027_WithPermittedSelectors_ThenPass(string selectBy)
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(IWebElement).Assembly },
                Code       = $@"
                    using System;
                    using OpenQA.Selenium;
                    using OpenQA.Selenium.Chrome;
                    using System.Collections.ObjectModel;
        
                    namespace Selenium.Tests.Utils
                    {{
                        public class Utils
                        {{
                            public ReadOnlyCollection<IWebElement> elements1 = new ChromeDriver().FindElements(By.CssSelector(""{selectBy}""));
                            public IWebElement element1 = new ChromeDriver().FindElement(By.CssSelector(""{selectBy}""));
                            public ReadOnlyCollection<IWebElement> elements2 = new ChromeDriver().FindElementsByCssSelector(""{selectBy}"");
                            public IWebElement element2 = new ChromeDriver().FindElementByCssSelector(""{selectBy}"");
                        }}
                    }}"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
        public async Task AG0005_WhenMethodNotPublic_ShouldNotShowWarning(string modifier)
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(TestFixtureAttribute).Assembly },
                Code       = $@"
                    using System.Collections;
                    using NUnit.Framework;
                    
                    namespace Tests
                    {{
                        public class TestClass
                        {{
                            [Test]
                            {modifier} void PrivateMethod(){{}}
                    
                        }}
                    
                        public class MyTestDataClass
                        {{
                            public static IEnumerable TestCases
                            {{
                                get {{ yield return null; }}
                            }}
                        }}
                    }}"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
        public async Task AG0026_WithPermittedByAccessor_ThenNoWarning()
        {
            var code = new CodeDescriptor
            {
                References = new [] { typeof(IWebElement).Assembly },
                Code       = @"
                    using System;
                    using OpenQA.Selenium;
                    using OpenQA.Selenium.Chrome;
        
                    namespace Selenium.Tests.Utils
                    {
                        public class Utils
                        {
                            public void Test()
                            {
                                var driver = new ChromeDriver();
                                var elements1 = driver.FindElement(By.CssSelector(""selector""));
                            }
                        }
                    }"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
Exemple #7
0
        public async Task AG0027_WithForbiddenFindElementsSelectorsInMethod_ThenShowWarning(string selectBy)
        {
            var code = new CodeDescriptor
            {
                References = new [] { typeof(IWebElement).Assembly },
                Code       = $@"
                    using System;
                    using OpenQA.Selenium;
                    using OpenQA.Selenium.Chrome;
        
                    namespace Selenium.Tests.Utils
                    {{
                        public class Utils
                        {{
                            public void Test()
                            {{
                                var driver = new ChromeDriver();
                                var elements1 = driver.FindElementsByCssSelector(""{selectBy}"");
                                var elements2 = driver.FindElementByCssSelector(""{selectBy}"");
                            }}
                        }}
                    }}
                "
            };

            var expected = new[]
            {
                new DiagnosticLocation(13, 82),
                new DiagnosticLocation(14, 81),
            };

            await VerifyDiagnosticsAsync(code, expected);
        }
        public async Task TestHttpContextAsArgument()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(HttpContext).Assembly },
                Code       = @"
					using System.Web;
	
					interface ISomething {
						void SomeMethod(HttpContext c, string sampleString); // ugly interface method
					}
				
					class TestClass: ISomething {
						
						public void SomeMethod(HttpContext context, string sampleString) {
							// this method is ugly
						}
	
						public TestClass(System.Web.HttpContext context) {
							// this constructor is uglier
						}
					}"
            };

            var expected = new[]
            {
                new DiagnosticLocation(5, 23),
                new DiagnosticLocation(10, 30),
                new DiagnosticLocation(14, 24)
            };

            await VerifyDiagnosticsAsync(code, expected);
        }
        private void AnalyzeFieldRef(FieldRefInfo fri, CodeDescriptor code)
        {
            Type fieldType = fri.Field.FieldType;

            object[] attrs = fieldType.GetCustomAttributes(typeof(MapToIntrinsicType), false);
            if (attrs.Length == 0)
            {
                if (fri.IsWritten && !fieldType.IsValueType)
                {
                    ReportError("Illegal write access to field " +
                                fri.Field.Name + " of class " + fri.Field.DeclaringType.Name + ": At runtime, " +
                                "only value types may be written.");
                    return;
                }
                if (fri.IsWritten && fri.Field.IsStatic)
                {
                    ReportError("Illegal write access to field " +
                                fri.Field.Name + " of class " + fri.Field.DeclaringType.Name + ": At runtime, " +
                                "only non-static fields may be written.");
                    return;
                }
                if (fri.IsRead && !fieldType.IsValueType && !fieldType.IsArray)
                {
                    //FIXME
                    // E.g. DesignContext.Instance is allowed...

                    /*
                     * ReportError("Illegal read access to field " + fri.Field.Name + " of class " +
                     *  fri.Field.DeclaringType.Name + ": At runtime, only value types and arrays " +
                     *  "may be accessed.");
                     * */
                    return;
                }
            }
        }
        public async Task AG0026_WithForbiddenFindElementsInMethod_ThenShowWarning(string methodName)
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(IWebElement).Assembly },
                Code       = $@"
                    using System;
                    using OpenQA.Selenium;
                    using OpenQA.Selenium.Chrome;
                    using System.Collections.ObjectModel;
        
                    namespace Selenium.Tests.Utils
                    {{
                        public class Utils
                        {{
                            public void Test()
                            {{
                                var element = new ChromeDriver().{methodName}(""abc"");
                            }}
                        }}
                    }}"
            };

            await VerifyDiagnosticsAsync(code, new DiagnosticLocation(13, 47));
        }
        public async Task AG0037_WithOwnedByAttributeMissing_ShowsWarning()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(TestFixtureAttribute).Assembly, typeof(OwnedByAttribute).Assembly },
                Code       = @"
					using NUnit.Framework;
					using Agoda.Analyzers.Test.AgodaCustom;

					namespace Agoda.Website.Selenium.Tests
					{
						class TestClass
						{
							[Test]
							[OwnedBy(Team.Team1)]
							public void GoodMethod() 
							{
							}

							[Test]
							public void BadMethod() 
							{
							}
						}
					}"
            };

            await VerifyDiagnosticsAsync(code, new DiagnosticLocation(15, 8));
        }
Exemple #12
0
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            if (args[0].Variability == Msil.EVariability.ExternVariable)
            {
                throw new NotSupportedException("Delegate calls must have constant target!");
            }

            Delegate deleg = (Delegate)args[0].Sample;

            if (deleg == null)
            {
                return(false);
            }

            StackElement[] callArgs;
            if (deleg.Method.IsStatic)
            {
                callArgs = new StackElement[args.Length - 1];
                Array.Copy(args, 1, callArgs, 0, args.Length - 1);
            }
            else
            {
                callArgs = new StackElement[args.Length];
                Array.Copy(args, callArgs, args.Length);
                callArgs[0].Sample      = deleg.Target;
                callArgs[0].Expr        = LiteralReference.CreateConstant(deleg.Target);
                callArgs[0].Variability = Msil.EVariability.Constant;
            }
            stack.ImplementCall(deleg.Method, callArgs);
            return(true);
        }
        public async Task AG0026_WithForbiddenByAccessor_ThenShowWarning(string methodName)
        {
            var code = new CodeDescriptor
            {
                References = new [] { typeof(IWebElement).Assembly },
                Code       = $@"
                    using System;
                    using OpenQA.Selenium;
                    using OpenQA.Selenium.Chrome;
        
                    namespace Selenium.Tests.Utils
                    {{
                        public class Utils
                        {{
                            public void Test()
                            {{
                                var driver = new ChromeDriver();
                                var elements1 = driver.FindElement(By.{methodName}(""abc""));
                            }}
                        }}
                    }}"
            };

            await VerifyDiagnosticsAsync(code, new DiagnosticLocation(13, 68));
        }
Exemple #14
0
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var stateLookup = stack.QueryAttribute <IStateLookup>();

            if (stateLookup == null)
            {
                var pd = decompilee as ProcessDescriptor;
                if (pd == null)
                {
                    var md = decompilee as MethodDescriptor;
                    if (md == null)
                    {
                        throw new InvalidOperationException("Unsupported code descriptor: " + decompilee);
                    }
                    pd = md.CallingProcess;
                }
                var pred     = pd.Instance.Predicate;
                var predElem = stack.GetCallExpression(
                    pred.Method, new StackElement(LiteralReference.CreateConstant(pred.Target), pred.Target, EVariability.Constant));
                var fspec = new FunctionSpec(typeof(void))
                {
                    CILRep       = callee,
                    IntrinsicRep = IntrinsicFunctions.Wait(WaitParams.EWaitKind.WaitUntil)
                };
                builder.Call(fspec, new Expression[] { predElem.Expr });
            }
            else
            {
                builder.Store(
                    stateLookup.NextStateSignal,
                    stateLookup.GetStateExpression(stack.CurrentILIndex));
                builder.Return();
            }
            return(true);
        }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            if (args[0].Variability == Msil.EVariability.ExternVariable)
                throw new NotSupportedException("Delegate calls must have constant target!");

            Delegate deleg = (Delegate)args[0].Sample;
            if (deleg == null)
                return false;

            StackElement[] callArgs;
            if (deleg.Method.IsStatic)
            {
                callArgs = new StackElement[args.Length - 1];
                Array.Copy(args, 1, callArgs, 0, args.Length - 1);
            }
            else
            {
                callArgs = new StackElement[args.Length];
                Array.Copy(args, callArgs, args.Length);
                callArgs[0].Sample = deleg.Target;
                callArgs[0].Expr = LiteralReference.CreateConstant(deleg.Target);
                callArgs[0].Variability = Msil.EVariability.Constant;
            }
            stack.ImplementCall(deleg.Method, callArgs);
            return true;
        }
        public async Task AG0012_WithShouldlyAssertion_ShouldNotShowWarning()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(TestFixtureAttribute).Assembly, typeof(Shouldly.Should).Assembly },
                Code       = @"
                    using NUnit.Framework;
                    using Shouldly;
                    using System;
                    
                    namespace Tests
                    {
                        public class TestClass
                        {
                            [Test]
                            public void This_Is_Valid()
                            {
                                int[] arrayForShouldBe = { 1, 2, 3 };
                                arrayForShouldBe.Length.ShouldBe(3);
                            }
                    
                            [Test]
                            public void This_Is_AlsoValid()
                            {
                                Should.Throw<Exception>(() => {
                                    var y = 1;
                                });
                            }
                        }
                    }"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
Exemple #17
0
 public FSMTransformer(DesignContext ctx, CodeDescriptor code, object instance, object[] arguments)
 {
     System.Diagnostics.Debug.Assert(arguments.Length == 1);
     _context   = ctx;
     _code      = code;
     _instance  = instance;
     _arguments = arguments;
 }
Exemple #18
0
 public FSMTransformerTemplate(DesignContext ctx, CodeDescriptor code, object instance, object[] arguments)
 {
     _context    = ctx;
     _code       = code;
     _instance   = instance;
     _arguments  = arguments;
     _methodCode = MethodCode.Create(_code.Method);
 }
Exemple #19
0
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                IHasSignalBase sink = (IHasSignalBase)args[0].Sample;
                SignalRef      next = SignalRef.Create(sink.Signal, SignalRef.EReferencedProperty.Next);

                builder.Store(next, args[1].Expr);
                return(true);
            }
Exemple #20
0
        public override IDecompilationResult Rewrite(DesignContext ctx, CodeDescriptor code, object instance, object[] arguments)
        {
            ProcessDescriptor pd = (ProcessDescriptor)code;

            pd.Kind = Process.EProcessKind.Triggered;
            FSMTransformer trans = new FSMTransformer(ctx, code, instance, arguments);

            return(trans.Transform());
        }
        public async Task AG0012_WithNestedAssertions_ShouldNotShowWarning()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(TestFixtureAttribute).Assembly, typeof(Shouldly.Should).Assembly },
                Code       = @"
                    using NUnit.Framework;
                    using Shouldly;
                    using System;
                    
                    namespace Tests
                    {
                        public class TestClass
                        {
                            [Test]
                            public void Assertion_In_Loop_Is_Valid()
                            {
                                int[] array = { 1, 2, 3 };
                                for (int i = 0; i < 3; i++)
                                {
                                    array[i].ShouldBe(i + 1);
                                }
                            }
                            
                            [Test]
                            public void Assertion_In_Nested_Loop_Is_Valid()
                            {
                                int[] array = { 1, 2, 3 };
                                for (int i = 0; i < 3; i++)
                                {
                                    for (int j = 0; j < 3; j++)
                                    {    
                                        array[i].ShouldBe(i + 1);
                                    }
                                }
                            }

                            [Test]
                            public void Assertion_In_Local_Function_Is_Valid()
                            {
                                int[] array = { 1, 2, 3 };
                                
                                helper(array[0]);

                                void helper(int i)
                                {
	                                Assert.AreEqual(i, i + 1);
                                }
                            }
                        }
                    }"
            };

            await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
        }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var side = args[0].Sample as IXilinxBlockMemSide;
            if (side == null)
                return false;

            var code = IntrinsicFunctions.XILOpCode(
                DefaultInstructionSet.Instance.WrMem(side),
                typeof(void));
            builder.Call(code.Callee, args[1].Expr, args[2].Expr);
            return true;
        }
Exemple #23
0
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                LiteralReference lvref = (LiteralReference)args[0].Expr;
                Variable         lv    = lvref.ReferencedObject as Variable;

                if (lv == null)
                {
                    throw new InvalidOperationException("DoNotUnroll must be applied to a local variable!");
                }
                stack.DoNotUnroll(lv.LocalIndex);
                return(true);
            }
Exemple #24
0
        public static CodeEntity New(CodeDescriptor aDescriptor, XmlSettingCategory aSettingsCategory)
        {
            CodeEntity ret = null;

            //
            if (aSettingsCategory.Contains(KSettingsKeyFileName))
            {
                string fileName = aSettingsCategory[KSettingsKeyFileName];
                ret = New(aDescriptor, FSEntity.New(fileName));
            }
            //
            return(ret);
        }
Exemple #25
0
        public async Task TestIHttpContextAccessorAsArgument()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(IHttpContextAccessor).Assembly, typeof(HttpContextAccessor).Assembly },
                Code       = @"
using Microsoft.AspNetCore.Http;

interface ISomething
{
    void SomeMethod(IHttpContextAccessor c, string sampleString); // ugly interface method
    void SomeMethod(HttpContextAccessor c, string sampleString); // ugly interface method
}

class TestClass : ISomething
{
    public void SomeMethod(IHttpContextAccessor context, string sampleString)
    {
        // this method is ugly
    }

    public void SomeMethod(HttpContextAccessor context, string sampleString)
    {
        //this method is ugly
    }

     public TestClass(Microsoft.AspNetCore.Http.IHttpContextAccessor context)
    {
        // this constructor is uglier
    }

    public TestClass(Microsoft.AspNetCore.Http.HttpContextAccessor context)
    {
        // this constructor is uglier
    }
}"
            };

            var expected = new[]
            {
                new DiagnosticLocation(6, 21),
                new DiagnosticLocation(7, 21),
                new DiagnosticLocation(12, 28),
                new DiagnosticLocation(17, 28),
                new DiagnosticLocation(22, 23),
                new DiagnosticLocation(27, 22)
            };
            HttpContextAccessor a;

            await VerifyDiagnosticsAsync(code, expected);
        }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var side = args[0].Sample as IXilinxBlockMemSide;
            if (side == null)
                return false;

            var sample = StdLogicVector._0s(side.DataReadWidth);
            var code = IntrinsicFunctions.XILOpCode(
                DefaultInstructionSet.Instance.RdMem(side),
                TypeDescriptor.GetTypeOf(sample),
                args[1].Expr);
            stack.Push(code, sample);
            return true;
        }
Exemple #27
0
            public override bool Rewrite(
                CodeDescriptor decompilee,
                Expression waitObject,
                Analysis.IDecompiler stack,
                IFunctionBuilder builder)
            {
                var fspec = new FunctionSpec(typeof(void))
                {
                    IntrinsicRep = IntrinsicFunctions.Wait(WaitParams.EWaitKind.WaitFor)
                };

                builder.Call(fspec, waitObject);
                return(true);
            }
Exemple #28
0
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                if (args[0].Sample == null)
                {
                    throw new InvalidOperationException("null sample");
                }

                ConstSignalSourceBase src = (ConstSignalSourceBase)callee.Invoke(args[0].Sample);

                src.ValueExpr = args[0].Expr;
                Expression srcex = LiteralReference.CreateConstant(src);

                stack.Push(srcex, src);
                return(true);
            }
        public async Task AG0011_WithDirectAccess_ShowsWarning()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(HttpContext).Assembly },
                Code       = @"
					class TestClass {
						public void TestMethod() {
							var queryString = System.Web.HttpContext.Current.Request.QueryString;
						}
					}"
            };

            await VerifyDiagnosticsAsync(code, new DiagnosticLocation(4, 65));
        }
Exemple #30
0
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var stateLookup = stack.QueryAttribute <IStateLookup>();

            if (stateLookup == null)
            {
                //throw new InvalidOperationException("Process calling Issue(): Please use [TransformIntoFSM] attribute for proper translation.");
                return(false);
            }
            else
            {
                IEnumerable <TAVerb> coStates = (IEnumerable <TAVerb>)args[1].Sample;
                stateLookup.ImplementCoState(stack.CurrentILIndex, coStates, 0, builder);
            }
            return(true);
        }
        public async Task AG0011_ThroughLocalVariable_ShowsWarning()
        {
            var code = new CodeDescriptor
            {
                References = new[] { typeof(HttpContext).Assembly },
                Code       = @"
					class TestClass {
						public void TestMethod() {
							var request = System.Web.HttpContext.Current.Request;
							var queryParamValue = request.QueryString[""queryParam""];
						}
					}"
            };

            await VerifyDiagnosticsAsync(code, new DiagnosticLocation(5, 38));
        }
Exemple #32
0
        public CodeDocument(CodeDescriptor desc, DocumentView parent)
            : base(desc.FilePath, parent)
        {
            this.desc = desc;
            Text      = desc.Name;
            BackColor = UIManager.Instance.DullFlairColor;



            initControls();
            configureControls();
            addControls();

            discHandler = new FileChangedEventHandler(discListener);
            Dirty       = false;
        }
        private void AdaptCalls(CodeDescriptor cd, Dictionary <object, IEnumerable <SignalArgumentDescriptor> > map)
        {
            List <Statement>            stmts = cd.Implementation.Body.GetAtomicStatements();
            IEnumerable <CallStatement> calls = stmts.Select(s => s as CallStatement).Where(s => s != null);
            ComponentDescriptor         owner = (ComponentDescriptor)cd.Owner;

            foreach (CallStatement stmt in calls)
            {
                var fspec = stmt.Callee as FunctionSpec;
                if (fspec == null)
                {
                    continue;
                }
                object key;

                /*if (fspec.SysDOMRep != null)
                 *  key = fspec.SysDOMRep;
                 * else*/
                if (fspec.CILRep != null)
                {
                    key = fspec.CILRep;
                }
                else
                {
                    continue;
                }
                IEnumerable <SignalArgumentDescriptor> addArgs;
                if (!map.TryGetValue(key, out addArgs))
                {
                    continue;
                }
                List <Expression> args = stmt.Arguments.ToList();
                foreach (SignalArgumentDescriptor sad in addArgs)
                {
                    SignalBase sigInst = (SignalBase)sad.Sample;
                    var        sigRef  = sigInst.Descriptor
                                         .AsSignalRef(SignalRef.EReferencedProperty.Instance)
                                         .RelateToComponent(owner);
                    if (sigRef == null)
                    {
                        throw new InvalidOperationException("Signal not found in local component");
                    }
                    args.Add(sigRef);
                }
                stmt.Arguments = args.ToArray();
            }
        }
 public override void RewriteRead(CodeDescriptor decompilee, FieldInfo field, object instance, IDecompiler stack, IFunctionBuilder builder)
 {
     throw new InvalidOperationException("State machine is not expected to read state inside state handler");
 }
 public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
 {
     return true;
 }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            Type returnType;
            if (callee.ReturnsSomething(out returnType))
                throw new ArgumentException("The IgnoreOnDecompilation attribute may only be applied to methods returning a void result. Use StaticEvaluation instead.");

            if (_call)
            {
                callee.Invoke(args.Select(a => a.Sample).ToArray());
            }

            return true;
        }
 /// <summary>
 /// Constructs an instance
 /// </summary>
 /// <param name="ctx">underlying design context</param>
 /// <param name="code">code descriptor of async method to decompile</param>
 /// <param name="instance">assumed instance on which the method is called</param>
 /// <param name="arguments">sample instances of method arguments</param>
 public AsyncMethodDecompiler(DesignContext ctx, CodeDescriptor code, object instance, object[] arguments)
 {
     _context = ctx;
     _code = code;
     _instance = instance;
     _arguments = arguments;
     ImplStyle = code.AsyncMethod.HasCustomOrInjectedAttribute<TransformIntoFSM>() ? EAsyncImplStyle.FSM : EAsyncImplStyle.Sequential;
 }
 public override void RewriteRead(CodeDescriptor decompilee, FieldInfo field, object instance, IDecompiler stack, IFunctionBuilder builder)
 {
     var me = stack.QueryAttribute<AsyncMethodDecompiler>();
     var elem = (StackElement)me._tasks[field.Name];
     stack.Push(elem);
 }
 public override void RewriteRead(CodeDescriptor decompilee, FieldInfo field, object instance, IDecompiler stack, IFunctionBuilder builder)
 {
     var me = stack.QueryAttribute<AsyncMethodDecompiler>();
     var v = me._argFields[field.Name];
     if (!me._declared.Contains(v))
     {
         builder.DeclareLocal(v);
         me._declared.Add(v);
     }
     var lr = (LiteralReference)v;
     stack.Push(lr, v.Type.GetSampleInstance(ETypeCreationOptions.ForceCreation));
 }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            Type returnType;
            if (callee.ReturnsSomething(out returnType))
            {
                dynamic awaiter = args[0].Sample;
                if ((object)awaiter != null)
                {
                    if (!awaiter.IsCompleted)
                        throw new InvalidOperationException("Task not completed - what are you awaiting for?");

                    object resultSample = awaiter.GetResult();
                    var resultType = resultSample.GetType();
                    var fspec = new FunctionSpec(resultType)
                    {
                        IntrinsicRep = IntrinsicFunctions.GetAsyncResult(awaiter)
                    };
                    var fcall = new FunctionCall()
                    {
                        Callee = fspec,
                        Arguments = new Expression[0],
                        ResultType = resultType
                    };
                    stack.Push(fcall, resultSample);
                }
            }
            return true;
        }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            object[] outArgs;
            object rsample = null;
            if (callee is MethodInfo &&
                !callee.HasCustomOrInjectedAttribute<IDoNotCallOnDecompilation>())
            {
                stack.TryGetReturnValueSample((MethodInfo)callee, args, out outArgs, out rsample);
            }
            Type returnType;
            callee.IsFunctionOrCtor(out returnType);
            TypeDescriptor rtype;
            if (rsample != null)
                rtype = TypeDescriptor.GetTypeOf(rsample);
            else
                rtype = returnType;

            IntrinsicFunction ifun;
            FunctionCall fcall;
            if (args[1].Variability == EVariability.Constant &&
                args[2].Variability == EVariability.Constant)
            {
                // constant arguments case
                int first = (int)TypeConversions.ConvertValue(args[1].Sample, typeof(int));
                int second = (int)TypeConversions.ConvertValue(args[2].Sample, typeof(int));
                var range = new Range(first, second, EDimDirection.Downto);
                ifun = new IntrinsicFunction(IntrinsicFunction.EAction.Slice, range)
                {
                    MethodModel = callee
                };
                var fspec = new FunctionSpec(rtype)
                {
                    CILRep = callee,
                    IntrinsicRep = ifun
                };
                fcall = new FunctionCall()
                {
                    Callee = fspec,
                    Arguments = new Expression[] { args[0].Expr },
                    ResultType = rtype,
                    SetResultTypeClass = EResultTypeClass.ObjectReference
                };
            }
            else
            {
                ifun = new IntrinsicFunction(IntrinsicFunction.EAction.Slice)
                {
                    MethodModel = callee
                };
                var fspec = new FunctionSpec(rtype)
                {
                    CILRep = callee,
                    IntrinsicRep = ifun
                };
                fcall = new FunctionCall()
                {
                    Callee = fspec,
                    Arguments = args.Select(arg => arg.Expr).ToArray(),
                    ResultType = rtype,
                    SetResultTypeClass = EResultTypeClass.ObjectReference
                };
            }
            stack.Push(fcall, rsample);
            return true;
        }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            Type returnType;
            if (!callee.ReturnsSomething(out returnType))
                throw new ArgumentException("The StaticEvaluation attribute may only be applied to methods returning some result. Use IgnoreOnDecompilation instead.");

            object result = null;
            try
            {
                result = callee.Invoke(args.Select(arg => arg.Sample).ToArray());
            }
            catch (TargetInvocationException)
            {
            }
            Expression resultExpr = ResultGen(result);
            stack.Push(new StackElement(resultExpr, result, EVariability.Constant));
            return true;
        }
Exemple #43
0
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                var ufixSample = (UFix)args[0].Sample;
                var ufixType = args[0].Expr.ResultType;
                var slvuType = TypeDescriptor.GetTypeOf(ufixSample.SLVValue);

                object[] outArgs;
                object rsample;
                stack.TryGetReturnValueSample((MethodInfo)callee, args, out outArgs, out rsample);
                if (rsample == null)
                    throw new ArgumentException("Unable to infer result sample");

                var sfixSample = (SFix)rsample;
                var sfixType = TypeDescriptor.GetTypeOf(sfixSample);
                var slvsType = TypeDescriptor.GetTypeOf(sfixSample.SLVValue);
                var zlit = LiteralReference.CreateConstant(StdLogic._0);

                var eargs = args.Select(arg => arg.Expr).ToArray();
                var cast1 = IntrinsicFunctions.Cast(eargs, ufixType.CILType, slvuType, true);
                var cast2 = Expression.Concat(zlit, cast1);
                var cast3 = IntrinsicFunctions.Cast(new Expression[] { cast2 }, slvsType.CILType, sfixType, true);

                stack.Push(cast3, rsample);
                return true;
            }
 public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
 {
     throw new ArgumentException("Method " + callee.ToString() + " was assumed not to be called at runtime. " +
         "However, a call to this method was found in " + decompilee.Method.ToString());
 }
        public override bool Rewrite(CodeDescriptor decompilee, Expression waitObject, IDecompiler stack, IFunctionBuilder builder)
        {
            if (stack.HasAttribute<Analysis.M2M.HLS>())
            {
                return true;
            }

            var curps = DesignContext.Instance.CurrentProcess;
            SLSignal clk = (SLSignal)curps.Sensitivity[0].Owner;
            SignalRef srEdge;
            if (curps.Predicate.Equals((Func<bool>)clk.RisingEdge))
                srEdge = SignalRef.Create(clk.Descriptor, SignalRef.EReferencedProperty.RisingEdge);
            else
                srEdge = SignalRef.Create(clk.Descriptor, SignalRef.EReferencedProperty.FallingEdge);
            var lrEdge = new LiteralReference(srEdge);

            int nwait = 0;
            var nwaitEx = waitObject.Children[0];
            bool nwaitConst = nwaitEx.IsConst();
            if (nwaitConst)
            {
                nwait = (int)TypeConversions.ConvertValue(
                        nwaitEx.Eval(DefaultEvaluator.DefaultConstEvaluator),
                        typeof(int));
            }

            var fspec = new FunctionSpec(typeof(void))
            {
                IntrinsicRep = IntrinsicFunctions.Wait(WaitParams.EWaitKind.WaitUntil)
            };

            Variable v = null;
            LiteralReference lrV = null;

            if (!nwaitConst || nwait > 3)
            {
                v = new Variable(typeof(int))
                {
                    Name = "_wait_i" + (ictr++)
                };
                builder.DeclareLocal(v);
                lrV = new LiteralReference(v);
                builder.Store(v, LiteralReference.CreateConstant((int)0));
                var loop = builder.Loop();
                builder.If(Expression.Equal(lrV, nwaitEx));
                {
                    builder.Break(loop);
                }
                builder.EndIf();
            }
            int ncalls = 1;
            if (nwaitConst && nwait <= 3)
                ncalls = nwait;
            for (int i = 0; i < ncalls; i++)
            {
                builder.Call(fspec, lrEdge);
            }
            if (!nwaitConst || nwait > 3)
            {
                builder.Store(v, lrV + LiteralReference.CreateConstant((int)1));
                builder.EndLoop();
            }
            return true;
        }
 public override void RewriteRead(CodeDescriptor decompilee, FieldInfo field, object instance, IDecompiler stack, IFunctionBuilder builder)
 {
     var me = stack.QueryAttribute<AsyncMethodDecompiler>();
     var awaiter = field.GetValue(me._fsmInstance);
     var lr = LiteralReference.CreateConstant(awaiter);
     stack.Push(new StackElement(lr, awaiter, Msil.EVariability.Constant));
 }
 public override void RewriteWrite(CodeDescriptor decompilee, FieldInfo field, object instance, StackElement value, IDecompiler stack, IFunctionBuilder builder)
 {
     var me = stack.QueryAttribute<AsyncMethodDecompiler>();
     try
     {
         field.SetValue(me._fsmInstance, value.Sample);
     }
     catch (Exception)
     {
         var task = me.GetTaskFromAwaiter(value.Sample);
         var awaiterType = field.FieldType;
         var targetAwaiter = Activator.CreateInstance(awaiterType);
         var targetAwaiterField = awaiterType.GetField("m_task", BindingFlags.Instance | BindingFlags.NonPublic);
         targetAwaiterField.SetValue(targetAwaiter, task);
         field.SetValue(me._fsmInstance, targetAwaiter);
     }
 }
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var amd = stack.QueryAttribute<AsyncMethodDecompiler>();
            if (amd != null && amd.ImplStyle == EAsyncImplStyle.FSM)
            {
                return false;
            }

            object[] outArgs;
            object result;
            stack.TryGetReturnValueSample((MethodInfo)callee, args, out outArgs, out result);

            var fspec = new FunctionSpec(typeof(Task))
            {
                CILRep = callee
            };
            var fcall = new FunctionCall()
            {
                Callee = fspec,
                Arguments = args.Select(a => a.Expr).ToArray(),
                ResultType = TypeDescriptor.GetTypeOf(result)
            };

            stack.Push(fcall, result);

            return true;
        }
 public override void RewriteWrite(CodeDescriptor decompilee, FieldInfo field, object instance, StackElement value, IDecompiler stack, IFunctionBuilder builder)
 {
     var me = stack.QueryAttribute<AsyncMethodDecompiler>();
     var v = me._argFields[field.Name];
     if (!me._declared.Contains(v))
     {
         builder.DeclareLocal(v);
         me._declared.Add(v);
     }
     builder.Store(v, value.Expr);
     if (value.Sample != null)
         v.UpgradeType(TypeDescriptor.GetTypeOf(value.Sample));
     if (me._curSI != null)
         me._curSI.LVState[field.Name] = value.Sample;
 }
        public override IStorableLiteral ImplementDeclaration(CodeDescriptor container, object sample, ParameterInfo pi)
        {
            var signal = sample as SignalBase;
            if (signal == null)
                throw new ArgumentException("Signal instance null");

            Type etype = pi.ParameterType;
            ArgumentDescriptor.EArgDirection flowDir;
            if (typeof(IInOutPort).IsAssignableFrom(etype))
                flowDir = ArgumentDescriptor.EArgDirection.InOut;
            else if (typeof(IInPort).IsAssignableFrom(etype))
                flowDir = ArgumentDescriptor.EArgDirection.In;
            else if (typeof(IOutPort).IsAssignableFrom(etype))
                flowDir = ArgumentDescriptor.EArgDirection.Out;
            else
                throw new NotImplementedException();

            var sref = new SignalRef(signal.Descriptor, SignalRef.EReferencedProperty.Instance);

            SignalArgumentDescriptor desc = new SignalArgumentDescriptor(
                sref,
                ArgumentDescriptor.EArgDirection.In,
                flowDir,
                EVariability.Constant,
                pi.Position);
            container.AddChild(desc, sref.Name);

            return sref;
        }
 public override void RewriteWrite(CodeDescriptor decompilee, FieldInfo field, object instance, StackElement value, IDecompiler stack, IFunctionBuilder builder)
 {
     var me = stack.QueryAttribute<AsyncMethodDecompiler>();
     me._tasks[field.Name] = value;
 }
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                var ctx = stack.QueryAttribute<AsyncMethodDecompiler>();
                if (ctx == null)
                    throw new InvalidOperationException("Method must be decompiled using AsyncMethodDecompiler.");
                if (ctx.ImplStyle != EAsyncImplStyle.FSM)
                    throw new InvalidOperationException("Awaiting other tasks is only possible when decompiling to FSM.");

                ctx.ImplementAwait(decompilee, callee, args, stack, builder);

                return true;
            }
 /// <summary>
 /// Constructs a SysDOM method body for the given code descriptor.
 /// </summary>
 /// <param name="ctx">design context</param>
 /// <param name="code">code descriptor of tagged method</param>
 /// <param name="instance">instance on which method is called (null for static methods)</param>
 /// <param name="arguments">method argument samples</param>
 /// <returns>custom decompilation result</returns>
 public abstract IDecompilationResult Rewrite(DesignContext ctx, CodeDescriptor code, object instance, object[] arguments);
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                var ctx = stack.QueryAttribute<AsyncMethodDecompiler>();
                if (ctx.ImplStyle == EAsyncImplStyle.FSM)
                {
                    if (args.Length == 2 &&
                        ctx._curCoFSM.ResultVar != null)
                    {
                        builder.Store(ctx._curCoFSM.ResultVar, args[1].Expr);
                        if (args[1].Expr.ResultType.IsComplete)
                            ctx._curCoFSM.ResultVar.UpgradeType(args[1].Expr.ResultType);
                    }
                    
                    var si = ctx.ForkInitialSI();
                    var pi = new ProceedWithStateInfo()
                    {
                        TargetState = si,
                        TargetWaitState = false,
                        LambdaTransition = false
                    };

                    if (ctx._curCoFSM != null &&
                        ctx._curCoFSM.DoneVar != null)
                    {
                        var tr = LiteralReference.CreateConstant(true);
                        builder.Store(ctx._curCoFSM.DoneVar, tr);
                        pi.TargetState = null;
                    }

                    var fspec = new FunctionSpec(typeof(void))
                    {
                        IntrinsicRep = IntrinsicFunctions.ProceedWithState(pi)
                    };
                    builder.Call(fspec, LiteralReference.CreateConstant(pi));
                }
                return true;
            }
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                var ctx = stack.QueryAttribute<AsyncMethodDecompiler>();
                if (ctx == null)
                    throw new InvalidOperationException("Method must be decompiled using AsyncMethodDecompiler.");
                if (ctx.ImplStyle == EAsyncImplStyle.Sequential)
                    return true;

                var awaiterCallExpr = stack.ResolveVariableReference(stack.CurrentILIndex, args[1].Expr);
                var awaiterCall = awaiterCallExpr as FunctionCall;
                if (awaiterCall != null)
                {
                    var waitObject = awaiterCall.Arguments[0];
                    var asyncCall = waitObject as FunctionCall;
                    if (asyncCall != null)
                    {
                        var cspec = asyncCall.Callee as FunctionSpec;
                        if (cspec != null && 
                            cspec.CILRep != null &&
                            cspec.CILRep.HasCustomOrInjectedAttribute<TickAttribute>())
                        {
                            var si = ctx.ForkNextSI();
                            var pi = new ProceedWithStateInfo()
                            {
                                TargetState = si,
                                TargetWaitState = false,
                                LambdaTransition = false
                            };
                            var fspec = new FunctionSpec(typeof(void))
                            {
                                IntrinsicRep = IntrinsicFunctions.ProceedWithState(pi)
                            };
                            builder.Call(fspec, LiteralReference.CreateConstant(pi));
                            return true;
                        }
                    }
                }

                var awaiter = args[1].Sample;
                var task = ctx.GetTaskFromAwaiter(awaiter);

                if (task != null)
                {
                    if (!task.IsCompleted)
                        throw new InvalidOperationException("Task not completed - what are you awaiting for?");

                    var sin = ctx.ForkNextSI();
                    sin.HasWaitState = true;
                    var jp = new JoinParams()
                    {
                        JoinedTask = task,
                        Continuation = sin
                    };
                    sin.JP = jp;
                    ctx.ImplementJoin(jp, builder, sin);
                }

                return true;
            }
 /// <summary>
 /// Constructs a literal from a given <c>ParameterInfo</c>.
 /// </summary>
 /// <param name="container">constructor or method to which the argument belongs</param>
 /// <param name="sample">sample value for argument</param>
 /// <param name="pi">CLI parameter information</param>
 /// <returns>a SysDOM literal to use for that argument</returns>
 public abstract IStorableLiteral ImplementDeclaration(CodeDescriptor container, object sample, ParameterInfo pi);
        public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
        {
            var ctx = stack.QueryAttribute<AsyncMethodDecompiler>();
            if (ctx == null)
                throw new InvalidOperationException("Method must be decompiled using AsyncMethodDecompiler.");

            var style = ctx.ImplStyle;

            if (style == EAsyncImplStyle.Sequential)
            {
                ctx.ImplementAwait(decompilee, callee, args, stack, builder);
            }

            bool flag = style == EAsyncImplStyle.Sequential;
            var lr = LiteralReference.CreateConstant(flag);
            stack.Push(new StackElement(lr, flag, Msil.EVariability.Constant));
            return true;
        }
 public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
 {
     object[] vargs = args.Select(arg => arg.Sample).ToArray();
     Expression[] eargs = args.Select(arg => arg.Expr).ToArray();
     object sample = null;
     try
     {
         sample = callee.Invoke(vargs);
     }
     catch (Exception)
     {
     }
     Expression result = new BinOp()
     {
         Operation = Kind
     };
     Array.Copy(eargs, result.Children, 2);
     if (sample != null)
         result.ResultType = TypeDescriptor.GetTypeOf(sample);
     else
     {
         Type rtype;
         callee.IsFunction(out rtype);
         result.ResultType = (TypeDescriptor)rtype;
     }
     stack.Push(result, sample);
     return true;
 }
Exemple #59
0
            public override bool Rewrite(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
            {
                var elemProf = args[0];
                if (elemProf.Variability != EVariability.Constant)
                    throw new NotSupportedException("Profiler must be derivable as constant value");

                var prof = (ScheduleProfiler)elemProf.Sample;
                var ilRef = new ILIndexRef(decompilee.Method, stack.CurrentILIndex);
                if (_isBegin)
                {
                    if (prof.FirstILIndex != null)
                        throw new InvalidOperationException("Profiling of " + prof.Name + " already has start position at " + prof.FirstILIndex);
                    prof.FirstILIndex = ilRef;
                }
                else
                {
                    if (prof.LastILIndex != null)
                        throw new InvalidOperationException("Profiling of " + prof.Name + " already has end position at " + prof.LastILIndex);
                    prof.LastILIndex = ilRef;
                }

                var constraints = builder.ResultFunction.QueryAttribute<SchedulingConstraints>();
                if (constraints == null)
                {
                    constraints = new SchedulingConstraints();
                    builder.ResultFunction.AddAttribute(constraints);
                }
                if (!constraints.Profilers.Contains(prof))
                    constraints.Profilers.Add(prof);

                return true;
            }
 internal void ImplementAwait(CodeDescriptor decompilee, MethodBase callee, StackElement[] args, IDecompiler stack, IFunctionBuilder builder)
 {
     var awaiterCallExpr = stack.ResolveVariableReference(stack.CurrentILIndex, args[0].Expr);
     var awaiterCall = awaiterCallExpr as FunctionCall;
     if (awaiterCall == null)
         throw new InvalidOperationException("Unable to resolve awaited object.");
     var waitObject = awaiterCall.Arguments[0];
     var awaiterType = args[0].Expr.ResultType.CILType;
     var rw = awaiterType.GetCustomOrInjectedAttribute<RewriteAwait>();
     if (rw == null)
     {
         var fcall = waitObject as FunctionCall;
         if (fcall != null)
         {
             var fspec = fcall.Callee as FunctionSpec;
             if (fspec != null && fspec.CILRep != null)
                 rw = fspec.CILRep.GetCustomOrInjectedAttribute<RewriteAwait>();
         }
     }
     if (rw != null)
         rw.Rewrite(decompilee, waitObject, stack, builder);
     else
         throw new InvalidOperationException("Unable to find await implementor");
 }