public void IgnoredMethodsSkipped() { MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), new IdentityNameGenerator()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassIgnore)).ToList(); Assert.Equal(1, actual.Count); }
private static void Execute(ModuleDefinition mainModule, ModuleDefinition l2MModule, ModuleDefinition coreModule) { var l2MOptimizeAttribute = l2MModule.GetType("LinqPatcher.Attributes", "OptimizeAttribute"); var classAnalyzer = new ClassAnalyzer(mainModule, l2MOptimizeAttribute); var methodAnalyzer = new MethodAnalyzer(coreModule); var methodBuilder = new MethodBuilder(mainModule, coreModule); var analyzedClass = classAnalyzer.Analyze(); foreach (var optimizeClass in analyzedClass.OptimizeTypes) { foreach (var method in classAnalyzer.AnalyzeMethod(optimizeClass)) { var analyzedMethod = methodAnalyzer.Analyze(method); var returnType = mainModule.ImportReference(analyzedMethod.ReturnType); methodBuilder.Create(optimizeClass, MethodHelper.CreateUniqueName, analyzedMethod.ParameterType, returnType); methodBuilder.Begin(); foreach (var linqOperator in analyzedMethod.Operators) { var linq = methodAnalyzer.OperatorFactory(linqOperator, methodBuilder); methodBuilder.AppendOperator(linq); } methodBuilder.BuildOperator(); methodBuilder.End(); methodBuilder.Replace(method); } } mainModule.Write($"{TargetModuleName}.dll"); }
public void IdsSetForMethods() { MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), Mock.Of <IMethodNameGenerator>()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassWithMethods)).ToList(); Assert.Collection(actual, f => Assert.Equal(1, f.Id), f => Assert.Equal(2, f.Id), f => Assert.Equal(3, f.Id)); }
private static void Execute(ModuleDefinition mainModule, ModuleDefinition l2MModule, ModuleDefinition coreModule) { var l2MOptimizeAttribute = l2MModule.GetType("LinqPatcher.Attributes", "OptimizeAttribute"); var typeSystem = mainModule.TypeSystem; var classAnalyzer = new ClassAnalyzer(mainModule, l2MOptimizeAttribute); var methodAnalyzer = new MethodAnalyzer(typeSystem); var methodBuilder = new MethodBuilder(mainModule, coreModule); var analyzedClass = classAnalyzer.Analyze(); foreach (var targetClass in analyzedClass.OptimizeTypes) { foreach (var method in classAnalyzer.AnalyzeMethod(targetClass)) { var analyzedMethod = methodAnalyzer.Analyze(method); var methodName = Guid.NewGuid().ToString("N"); methodBuilder.Create(targetClass, methodName, analyzedMethod.ParameterType, analyzedMethod.ReturnType); methodBuilder.Begin(); foreach (var linqOperator in analyzedMethod.Operators) { var linq = methodAnalyzer.OperatorFactory(linqOperator, methodBuilder); methodBuilder.AppendOperator(linq); } methodBuilder.BuildOperator(); methodBuilder.End(); methodBuilder.Replace(method); } } mainModule.Write("Main.dll"); }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { // 1. No data member is changed. if (this.NumOfChangedField(mAnalyzer) != 0) { return(false); } // 2. Return type is bool. if (mAnalyzer.RTypeIsBoolean()) { // 3. Do not directly return any data member. if (this.NumOfDirectRetField(mAnalyzer) == 0) { return(true); } else { return(false); } } else { return(false); } }
public static void Main(string[] args) { Console.Title = "ExeInjector v0.2"; Console.CursorVisible = false; Console.BackgroundColor = ConsoleColor.Black; Console.SetCursorPosition(0, 0); var menu = new Menu ( new MenuItem("Next", "Welcome to ExeInjector!", () => Console.WriteLine("Select the target assembly.")), new MenuItem("Exit", "Terminates the process and closes the window.", () => Environment.Exit(0)) ); menu.ShowMenu(); do { var libPath = DialogHelper.SelectFileDialog("Library(.dll)|*.dll"); if (Path.GetFileName(libPath) == "Assembly-CSharp.dll") { Console.Clear(); Console.WriteLine("Analyzing..."); var analyzer = new MethodAnalyzer(libPath); var methods = analyzer.FindMethod(); var targetMethods = new MenuItem[methods.Count]; for (var i = 0; i < targetMethods.Length; i++) { targetMethods[i] = new MenuItem(methods[i].FullName, "Select the method to inject the code into.", () => Console.WriteLine("Please select an executable file.")); } var methodsMenu = new Menu(targetMethods); methodsMenu.ShowMenu(true); var exePath = DialogHelper.SelectFileDialog("Exe(.exe)|*.exe"); var writer = new MethodWriter(exePath); writer.Inject(methods[methodsMenu.Index]); Console.Clear(); Console.WriteLine("Target assembly overwrite complete!"); analyzer.Finish(); break; } if (libPath == string.Empty) { break; } Console.WriteLine("Assembly-CSharp.dll"); } while (true); Console.ReadKey(); }
public void Analyzer_ReturnsValidNumberOfAnnotations_GivenConstraints(string methodName, int expectedContracts) { // analyze method MethodInfo method = this.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); MethodAnalysis analysis = new MethodAnalyzer().AnalyzeMethod(method, false, emitWarnings: false); // assert Assert.AreEqual(expectedContracts, analysis.ParameterPreconditions.Length + analysis.ReturnValuePreconditions.Length); Assert.AreEqual(expectedContracts > 0, analysis.HasContract); }
internal static void BindEvent <TContext>(this Binder <TContext> binder, Action <TContext> eventSubscription) where TContext : class { Expression left; Expression right; Action <TContext> unsubscribe; MethodAnalyzer.SplitEventExpression(eventSubscription, out left, out right, out unsubscribe); binder.AddRule(null, null, null, true, false, new[] { left, right }); }
public void BindValueAttributeAnalyzed() { MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), new IdentityNameGenerator()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassWithMethods)).ToList(); Assert.Collection(actual.OrderBy(p => p.ParameterCount), f => Assert.True(true), f => Assert.NotNull(f.ReturnValueAttribute), f => Assert.True(true)); }
public void ResultTypeSetForMethods() { MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), new IdentityNameGenerator()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassWithMethods)).ToList(); Assert.Collection(actual.OrderBy(p => p.ParameterCount), f => Assert.Equal(typeof(void), f.ResultType), f => Assert.Equal(typeof(string), f.ResultType), f => Assert.Equal(typeof(void), f.ResultType)); }
public void NamesSetForMethods() { MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), new IdentityNameGenerator()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassWithMethods)).ToList(); Assert.Collection(actual, f => Assert.Equal(nameof(SimpleClassWithMethods.MethodWithoutReturn), f.Name), f => Assert.Equal(nameof(SimpleClassWithMethods.MethodWithParameters), f.Name), f => Assert.Equal(nameof(SimpleClassWithMethods.MethodWithResult), f.Name)); }
/// <inheritdoc /> public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); context.RegisterCodeBlockStartAction <SyntaxKind>(ctxt => { var methodAnalyzer = new MethodAnalyzer(); ctxt.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(methodAnalyzer.AnalyzeInvocation), SyntaxKind.InvocationExpression); ctxt.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(methodAnalyzer.AnalyzePropertyGetter), SyntaxKind.SimpleMemberAccessExpression); }); }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { /// 1. if the method is a constructor if (mAnalyzer.IsConstructor == true) { return(true); } else { return(false); } }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { //1. The method has no statment. (should not be abstract) if (mAnalyzer.HasStatements == false) { return(true); } else { return(false); } }
public void ParameterInformationSetForMethods() { MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), new IdentityNameGenerator()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassWithMethods)).ToList(); Assert.Collection(actual.OrderBy(p => p.ParameterCount), f => Assert.Empty(f.Parameters), f => Assert.Collection(f.Parameters, p => Assert.Equal(typeof(string), p.Type)), f => Assert.Collection(f.Parameters, p => Assert.Equal(typeof(int), p.Type), p => Assert.Equal(typeof(double), p.Type), p => Assert.Equal(typeof(string), p.Type))); }
/// <summary> /// Gets number of returned parameters which has field assignment /// </summary> /// <param name="mAnalyzer"></param> /// <returns></returns> protected int GetNumOfRetFieldPara(MethodAnalyzer mAnalyzer) { int count = 0; foreach (var vb in mAnalyzer.ParametersInfo) { if (vb.IsReturned && vb.AssignedFields.Count != 0) { count++; } } return(count); }
/// <summary> /// Gets number of modified non-primitive parameters /// </summary> /// <param name="mAnalyzer"></param> /// <returns></returns> protected int GetNumOfModifiedObjPara(MethodAnalyzer mAnalyzer) { int count = 0; foreach (var vb in mAnalyzer.ParametersInfo) { if (!mAnalyzer.IsPrimitiveType(vb.GetVariableType()) && vb.IsModified) { count++; } } return(count); }
/// <summary> /// Returns number of non primitive parameters in this method /// </summary> /// <param name="mAnalyzer"></param> /// <returns></returns> protected int GetNumOfNonPrimitiveParameters(MethodAnalyzer mAnalyzer) { int count = 0; foreach (var para in mAnalyzer.ParametersInfo) { if (!mAnalyzer.IsPrimitiveType(para.GetVariableType())) { count++; } } return(count); }
/// <summary> /// Returns number of non primitive local variables in this method /// </summary> /// <param name="mAnalyzer"></param> /// <returns></returns> protected int GetNumOfNonPrimitiveVariables(MethodAnalyzer mAnalyzer) { int count = 0; foreach (var vb in mAnalyzer.VariablesInfo) { if (!mAnalyzer.IsPrimitiveType(vb.GetVariableType())) { count++; } } return(count); }
public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(csac => { var outAttributeType = csac.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesOutAttribute); var analyzer = new MethodAnalyzer(outAttributeType); csac.RegisterSymbolAction(analyzer.Analyze, SymbolKind.Method); }); }
private void Analyze(AMethodDecl method) { MethodAnalyzer analyzer = new MethodAnalyzer(method, Methods, data); method.GetBlock().Apply(this); Methods[method] = analyzer.SafeData; /* List of safe variables after each statement * While statements need a list for first statement in the while, and a list for first statement after the while * Also need to account for break and continue statments * If statements need a list for then then branch, and one for the else branch. * * CFG: * Join(v): * First, set safeList = intersection(pred(stm)) * Parse through expression, do the folloing in the order you get out of nodes * pointerLvalue: If unsafe, make a test, and restart check ///NO, its an iterative build. do this after * delete: clear safeList, safeIfTrue and safeIfFalse * p == null: if p is a pointer, add p to a safeIfTrue list * p != null: if p is a pointer, add p to a safeIfFalse list * !<exp>: swap safeIfTrue and safeIfFalse lists * <exp> || <exp>: intersection between left and right safeIfTrue list * <exp> && <exp>: intersection between left and right safeIfFalse list * * if stm: thenList = safeList U safeIfTrue * afterList = safeList U safeIfFalse * if-else stm: thenList = safeList U safeIfTrue * elseList = safeList U safeIfFalse * while stm: thenList = safeList U safeIfTrue * * * Problem: if something is safe before a while, it currently can't become safe in the while, since it will not initially be safe at the end of the while. * * * * ------------------------------- * * List of unsafe variables after each CFG node. * * Preprocess step: List of all used variables (Base: Field/Local, Others:Pointer/StructField) * * All those variables are unsafe before first statment * * * Join(v): * * */ }
/// <inheritdoc /> public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze); context.RegisterCodeBlockStartAction <SyntaxKind>(ctxt => { // We want to scan invocations that occur inside internal, synchronous methods // for calls to JTF.Run or JT.Join. var methodSymbol = ctxt.OwningSymbol as IMethodSymbol; if (!methodSymbol.HasAsyncCompatibleReturnType() && !Utils.IsPublic(methodSymbol) && !Utils.IsEntrypointMethod(methodSymbol, ctxt.SemanticModel, ctxt.CancellationToken) && !methodSymbol.FindInterfacesImplemented().Any(Utils.IsPublic)) { var methodAnalyzer = new MethodAnalyzer(); ctxt.RegisterSyntaxNodeAction(Utils.DebuggableWrapper(methodAnalyzer.AnalyzeInvocation), SyntaxKind.InvocationExpression); } }); }
public void ExecuteSetForMethods() { const int intValue = 1; const double doubleValue = 3.0; const string stringValue = "str"; var mock = new Mock <SimpleClassWithMethods>(); mock.Setup(m => m.MethodWithResult(stringValue)).Returns(stringValue); MethodAnalyzer methodAnalyzer = new MethodAnalyzer(new IntIdGenerator(), new IdentityNameGenerator()); var actual = methodAnalyzer.AnalyzeMethods(typeof(SimpleClassWithMethods)).ToList(); actual[0].Execute(mock.Object, new object[] { }); mock.Verify(m => m.MethodWithoutReturn(), Times.Once); actual[1].Execute(mock.Object, new object[] { intValue, doubleValue, stringValue }); mock.Verify(m => m.MethodWithParameters(intValue, doubleValue, stringValue), Times.Once); Assert.Equal(stringValue, actual[2].Execute(mock.Object, new object[] { stringValue })); }
/// <summary> /// /// </summary> /// <param name="mAnalyzer"></param> /// <returns></returns> public List <MethodStereotype> ApplyRules(MethodAnalyzer mAnalyzer) { List <MethodStereotype> matchedStereotypes = new List <MethodStereotype>(); if (Rules == null) { DefineRuleSet(); } foreach (MethodRule rule in this.Rules) { if (rule.RuleMatchedClass(mAnalyzer)) { matchedStereotypes.Add(rule.GetMethodStereotype()); } } if (matchedStereotypes.Count == 0) { matchedStereotypes.Add(MethodStereotype.Unclassified); } return(matchedStereotypes); }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { // 1. Cannot be primitive type if (mAnalyzer.IsPrimitiveType(mAnalyzer.ReturnType)) { return(false); } // 2. Local varible is instantiated and returned. foreach (var vi in mAnalyzer.VariablesInfo) { if (vi.IsReturned == true && vi.IsInstantiated) { return(true); } } foreach (var vi in mAnalyzer.ParametersInfo) { if (vi.IsReturned == true && vi.IsInstantiated) { return(true); } } // 3. Create and return a new object directly if (mAnalyzer.IsReturnNewObj) { return(true); } //// *4. Parameter is instantiated in the method and it's not primitive type. //foreach(var vi in aMethod.ParametersInfo) { // if(!aMethod.IsPrimitiveType(vi.GetVariableType()) && vi.IsInstantiated) { // return true; // } //} // returns false if it could not pass all the cases. return(false); }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { int num = this.NumOfChangedField(mAnalyzer); //1. Only one data member is changed if (num == 1) { //2. Return type is void or Boolean if (mAnalyzer.RTypeIsBoolean() || mAnalyzer.RTypeIsVoid()) { return(true); } else { return(false); } } else { return(false); } }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { // 1. No class field is changed. if (this.NumOfChangedField(mAnalyzer) != 0) { return(false); } // 2. Return type is not void. if (mAnalyzer.RTypeIsVoid()) { return(false); } // 3. Only return one class field. (Directly) if (this.NumOfDirectRetField(mAnalyzer) == 1 && this.NumOfIndirectRetField(mAnalyzer) == 0) { return(true); } else { return(false); } }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { int num = this.NumOfChangedField(mAnalyzer); // 1. Complex change to the object state is performed. (More than one class field is changed.) if (num > 1) { // 2. Return type is void or Boolean if (mAnalyzer.RTypeIsBoolean() || mAnalyzer.RTypeIsVoid()) { return(true); } else { return(false); } } else { return(false); } }
protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { //1. No data member is changed. if (this.NumOfChangedField(mAnalyzer) != 0) { return(false); } //2. Return type is NOT bool. if (mAnalyzer.RTypeIsBoolean() || mAnalyzer.RTypeIsVoid()) { return(false); } // 3. Do not return one data member directly. (directly > 1 || indirectly > 0) if (this.NumOfDirectRetField(mAnalyzer) > 1 || this.NumOfIndirectRetField(mAnalyzer) > 0) { return(true); } else { return(false); } }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer aMethod) { int numOfNonPrimitiveP = this.GetNumOfNonPrimitiveParameters(aMethod); int numOfNonPrimitiveV = this.GetNumOfNonPrimitiveVariables(aMethod); //int numOfRetFieldVP = this.GetNumOfRetFieldPara(aMethod) + this.GetNumOfRetFieldVar(aMethod); //int numOfModifiedObjPara = this.GetNumOfModifiedObjPara(aMethod); // 1. At least one of the method's parameters or local variables is an object // Collaborator - is a method that works on objects of classes different from itself if (numOfNonPrimitiveP > 0 || numOfNonPrimitiveV > 0) { return(true); } // 2.ChangeScribe implemented "invokes external method AND local method" (otherwise, it could be a controller) if (aMethod.InvokedExternalMethods.Count != 0 && aMethod.InvokedLocalMethods.Count != 0) { return(true); } return(false); }
/// <summary> /// Classifies the given method /// </summary> /// <param name="node">The AnalyzedMethod to test</param> /// <returns>True if the node meets the conditions for this rule, False otherwise.</returns> protected override bool MakeClassification(MethodAnalyzer mAnalyzer) { int numOfNonPrimitiveP = this.GetNumOfNonPrimitiveParameters(mAnalyzer); int numOfNonPrimitiveV = this.GetNumOfNonPrimitiveVariables(mAnalyzer); // 1. None of the method's parameters and local variables is an object if (numOfNonPrimitiveP == 0 && numOfNonPrimitiveV == 0) { //2. Invokes local methods, but no external function has been invoked. if (mAnalyzer.InvokedExternalMethods.Count == 0 && mAnalyzer.InvokedLocalMethods.Count > 0) { return(true); } else { return(false); } } else { return(false); } }
internal override void EmitNewobj(CodeEmitter ilgen, MethodAnalyzer ma, int opcodeIndex) { DoEmit(ilgen); }
internal override void EmitNewobj(CodeEmitter ilgen, MethodAnalyzer ma, int opcodeIndex) { LocalBuilder local = ilgen.DeclareLocal(DeclaringType.TypeAsTBD); ilgen.Emit(OpCodes.Ldloc, local); ilgen.Emit(OpCodes.Box, DeclaringType.TypeAsTBD); }
internal override void EmitNewobj(CodeEmitter ilgen, MethodAnalyzer ma, int opcodeIndex) { TypeWrapper targetType = ma == null ? null : ma.GetStackTypeWrapper(opcodeIndex, 0); if (targetType == null || targetType.IsInterface) { MethodInfo createDelegate = Types.Delegate.GetMethod("CreateDelegate", new Type[] { Types.Type, Types.Object, Types.String }); LocalBuilder targetObj = ilgen.DeclareLocal(Types.Object); ilgen.Emit(OpCodes.Stloc, targetObj); ilgen.Emit(OpCodes.Ldtoken, delegateConstructor.DeclaringType); ilgen.Emit(OpCodes.Call, Types.Type.GetMethod("GetTypeFromHandle", new Type[] { Types.RuntimeTypeHandle })); ilgen.Emit(OpCodes.Ldloc, targetObj); ilgen.Emit(OpCodes.Ldstr, "Invoke"); ilgen.Emit(OpCodes.Call, createDelegate); ilgen.Emit(OpCodes.Castclass, delegateConstructor.DeclaringType); } else { ilgen.Emit(OpCodes.Dup); // we know that a DelegateInnerClassTypeWrapper has only one method Debug.Assert(iface.GetMethods().Length == 1); MethodWrapper mw = targetType.GetMethodWrapper("Invoke", iface.GetMethods()[0].Signature, true); // TODO linking here is not safe mw.Link(); ilgen.Emit(OpCodes.Ldvirtftn, (MethodInfo)mw.GetMethod()); ilgen.Emit(OpCodes.Newobj, delegateConstructor); } }
internal sealed override void EmitNewobj(CodeEmitter ilgen, MethodAnalyzer ma, int opcodeIndex) { AssertLinked(); PreEmit(ilgen); NewobjImpl(ilgen); if(DeclaringType.IsNonPrimitiveValueType) { DeclaringType.EmitBox(ilgen); } }
internal virtual void EmitNewobj(CodeEmitter ilgen, MethodAnalyzer ma, int opcodeIndex) { throw new InvalidOperationException(); }
internal override void EmitNewobj(CodeEmitter ilgen, MethodAnalyzer ma, int opcodeIndex) { if(mbHelper != null) { ilgen.Emit(OpCodes.Call, mbHelper); } else { ilgen.Emit(OpCodes.Newobj, (ConstructorInfo)GetMethod()); } }
public PropertiesDependencieAnalyzer() { this.methodAnalyzer = new MethodAnalyzer( this ); }