private static void SwapParameterTypes(MethodDefinition method,
            TypeDefinition targetDependency,
            TypeReference interfaceType,
            HashSet<MethodReference> modifiedMethods)
        {
            if (method.IsAbstract || !method.HasBody)
                return;

            bool modified = false;
            var parameters = method.Parameters.Cast<ParameterDefinition>();
            foreach (var parameter in parameters)
            {
                var parameterType = parameter.ParameterType;
                if (parameterType != targetDependency)
                    continue;

                parameter.ParameterType = interfaceType;
                modified = true;
            }

            if (!modified)
                return;

            modifiedMethods.Add(method);
        }
Exemplo n.º 2
0
        private string GetMethodName(MethodDefinition method, string thisrefDexClassName)
        {
            if (method == null)
            {
                return(null);
            }

            var attr = method.GetDexImportAttribute();

            if (attr == null) // ignore hybrid properties.
            {
                return(null);
            }

            string methodName, descriptor, className;

            attr.GetDexOrJavaImportNames(method, out methodName, out descriptor, out className);

            if (className != thisrefDexClassName)
            {
                return(null); // can't reference another type.
            }

            return(methodName);
        }
Exemplo n.º 3
0
        public List<ILNode> Build(MethodDefinition methodDef)
        {
            this.methodDef = methodDef;

            // Make editable copy
            List<Instruction> body = new List<Instruction>(methodDef.Body.Instructions);

            if (body.Count == 0) return new List<ILNode>();

            StackAnalysis(body, methodDef);

            // Create branch labels for instructins; use the labels as branch operands
            foreach (Instruction inst in body) {
                if (inst.Operand is Instruction[]) {
                    foreach(Instruction target in (Instruction[])inst.Operand) {
                        if (!labels.ContainsKey(target)) {
                            labels[target] = new ILLabel() { Name = "IL_" + target.Offset.ToString("X2") };
                        }
                    }
                } else if (inst.Operand is Instruction) {
                    Instruction target = (Instruction)inst.Operand;
                    if (!labels.ContainsKey(target)) {
                        labels[target] = new ILLabel() { Name = "IL_" + target.Offset.ToString("X2") };
                    }
                }
            }

            List<ILNode> ast = ConvertToAst(body, methodDef.Body.ExceptionHandlers);

            return ast;
        }
 public MethodDefinition createMethod(String sMethodName, MethodAttributes maMethodAttributes,
                                      TypeReference trReturnType)
 {
     var newMethod = new MethodDefinition(sMethodName, maMethodAttributes, trReturnType);
     newMethod.Body.CilWorker.Emit(OpCodes.Ret);
     return newMethod;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Generate "position independent" representation of IL.
        ///
        /// We need to do this extra work because even if we skip
        /// instrumentation prologue of functions when iterating
        /// instructions, typical "toString()" representation of
        /// Cecil.Cil.Instructions contains absolute instruction
        /// positions.
        /// </summary>
        string ConcatBody(Cecil.MethodDefinition method)
        {
            const string skipAddr = "IL_0000: ";

            var sb = new System.Text.StringBuilder();

            foreach (var ins in Instrument.IterateInstructions(method))
            {
                if (ins.Operand is Cecil.Cil.Instruction)
                {
                    // instructions that refer to other instructions, like
                    // branches.

                    var insOperand = (Cecil.Cil.Instruction)(ins.Operand);
                    var offset     = insOperand.Offset - ins.Offset;

                    sb.AppendLine(String.Format("{0} {1}", ins.OpCode, offset));
                }
                else
                {
                    sb.AppendLine(ins.ToString().Substring(skipAddr.Length));
                }
            }
            return(sb.ToString());
        }
        private static void CopyMethodData(MethodDefinition templateMethod, MethodDefinition newMethod)
        {
            foreach (var parameterDefinition in templateMethod.Parameters)
            {
                newMethod.Parameters.Add(parameterDefinition);
            }

            if (templateMethod.HasBody)
            {
                newMethod.Body.InitLocals = true;

                foreach (var variableDefinition in templateMethod.Body.Variables)
                {
                    newMethod.Body.Variables.Add(variableDefinition);
                }

                foreach (ExceptionHandler exceptionHandler in templateMethod.Body.ExceptionHandlers)
                {
                    newMethod.Body.ExceptionHandlers.Add(exceptionHandler);
                }

                foreach (var instruction in templateMethod.Body.Instructions)
                {
                    newMethod.Body.Instructions.Add(instruction);
                }

                newMethod.Body.OptimizeMacros();
            }
        }
		private bool MemberIsCalled (TypeDefinition type, MethodDefinition method)
		{
			bool isCalled = false;
			
			if (TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsInternal (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsPrivate (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsInternal (method))
				isCalled = InternalMemberIsCalled (method);
			if (TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsPrivate (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (!TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsInternal (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (!TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsPrivate (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (!TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsInternal (method))
			    isCalled = InternalMemberIsCalled (method);
			if (!TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsPrivate (method))
			    isCalled = PrivateMemberIsCalled (type, method);
			if (TypeIsInternal (type) && TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (TypeIsInternal (type) && !TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
				isCalled = InternalMemberIsCalled (method);
			if (!TypeIsInternal (type) && TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
				isCalled = PrivateMemberIsCalled (type, method);
			if (!TypeIsInternal (type) && !TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))  
			    isCalled = true;
			}
        public static MethodDefinition Execute(PropertyDefinition property_definition, MethodDefinition notify_method, DependencyMap map)
        {
            log.Trace("\t\t\t\t\tAdding collection notification method for " + property_definition.Name);

            // Create method
            TypeReference return_type = property_definition.Module.Import(typeof (void));
            MethodDefinition collection_notification = new MethodDefinition(property_definition.Name + "CollectionNotification", Mono.Cecil.MethodAttributes.Private | Mono.Cecil.MethodAttributes.HideBySig, return_type);

            // Add parameters
            TypeReference sender_type = property_definition.Module.Import(typeof(object));
            TypeReference args_type = property_definition.Module.Import(typeof(NotifyCollectionChangedEventArgs));

            ParameterDefinition sender = new ParameterDefinition("sender", Mono.Cecil.ParameterAttributes.None, sender_type);
            ParameterDefinition args = new ParameterDefinition("args", Mono.Cecil.ParameterAttributes.None, args_type);

            collection_notification.Parameters.Add(sender);
            collection_notification.Parameters.Add(args);

            // Add notifications for dependent properties
            ILProcessor processor = collection_notification.Body.GetILProcessor();
            foreach (var target in map.GetDependenciesFor(property_definition.Name))
            {
                log.Trace("\t\t\t\t\t\tAdding dependency " + target);
                processor.Emit(OpCodes.Ldarg_0);
                processor.Emit(OpCodes.Ldstr, target);
                processor.Emit(OpCodes.Call, notify_method);
            }
            processor.Emit(OpCodes.Ret);

            // Add method to class
            property_definition.DeclaringType.Methods.Add(collection_notification);
            return collection_notification;
        }
		protected override void EnqueueMethod (MethodDefinition method)
		{
			if (IsA11yAssembly (method.DeclaringType.Module.Assembly))
				base.EnqueueMethod (method);
			else
				Annotations.Mark (method);
		}
Exemplo n.º 10
0
Arquivo: Method.cs Projeto: Kortni/XDG
        public Method(MethodDefinition method)
        {
            Name = method.Name;
            NameWithTypes = BuildNameWithTypes(method);
            if (method.IsPublic)
                Access = "public";
            else if (method.IsFamily)
                Access = "protected";

            if(method.ReturnType.FullName != "System.Void")
                ReturnType = method.ReturnType.ToXdgUrl();

            XmlNode doc = Xdg.FindXmlDoc(method);
            if (doc != null)
            {
                Summary = doc.GetElementContent("summary");
                Remarks = doc.GetElementContent("remarks");
                ReturnDocs = doc.GetElementContent("returns");
            }

            Parameters = new List<Parameter>();
            foreach (ParameterDefinition p in method.Parameters)
            {
                Parameter param = new Parameter();
                param.Name = p.Name;
                param.Type = p.ParameterType.ToXdgUrl();

                if(doc != null)
                    param.Doc = doc.GetElementContent("param[@name=\""+p.Name+"\"]");

                Parameters.Add(param);
            }
        }
Exemplo n.º 11
0
        public Cecil.MethodDefinition MethodDefinition(AnalysisNet.Types.MethodDefinition methodDefinition)
        {
            Cecil.MethodDefinition cecilMethodDefinition = new Cecil.MethodDefinition(methodDefinition.Name, 0, Context.CurrentModule.TypeSystem.Void);
            GenerateMethodAttributes(methodDefinition, cecilMethodDefinition);
            cecilMethodDefinition.CreateGenericParameters(methodDefinition.GenericParameters.Count);

            Cecil.TypeReference returnType = ReferenceGenerator.TypeReference(methodDefinition.ReturnType);
            cecilMethodDefinition.ReturnType = returnType;
            AddConstraintsToGenericParameters(methodDefinition, cecilMethodDefinition);

            Cecil.TypeReference  typeRef        = ReferenceGenerator.TypeReference(methodDefinition.ContainingType);
            Cecil.TypeDefinition containingType = typeRef.Resolve();
            cecilMethodDefinition.DeclaringType = containingType as Cecil.TypeDefinition;

            SetOverrides(methodDefinition, cecilMethodDefinition);
            SetCustomAttributes(methodDefinition.Attributes, cecilMethodDefinition.CustomAttributes);
            IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.ParameterDefinition> parameterDefinitions = CreateParameters(methodDefinition, cecilMethodDefinition);

            if (methodDefinition.HasBody)
            {
                cecilMethodDefinition.Body.MaxStackSize = methodDefinition.Body.MaxStack;
                cecilMethodDefinition.Body.InitLocals   = methodDefinition.Body.LocalVariables.Count > 0;
                IDictionary <AnalysisNet.ThreeAddressCode.Values.IVariable, Cecil.Cil.VariableDefinition> variableDefinitions = CreateLocalVariables(methodDefinition, cecilMethodDefinition);
                InstructionGenerator instructionGenerator = new InstructionGenerator(ReferenceGenerator);

                // analysis-net instruction -> [cecil instruction]
                IDictionary <AnalysisNet.Bytecode.Instruction, IList <Cecil.Cil.Instruction> > mapInstructions = instructionGenerator.CreateInstructions(methodDefinition, cecilMethodDefinition, variableDefinitions, parameterDefinitions);

                CreateExceptionHandlers(mapInstructions, methodDefinition.Body, cecilMethodDefinition.Body);
            }

            return(cecilMethodDefinition);
        }
Exemplo n.º 12
0
 public CilCompilationContext(MethodDefinition method, AstMethodDefinitionBase methodAst, Action<IAstElement, CilCompilationContext> compile, IReferenceContext referenceContext)
 {
     this.compile = compile;
     this.referenceContext = referenceContext;
     this.Method = method;
     this.MethodAst = methodAst;
 }
		public RuleResult CheckMethod (MethodDefinition method)
		{
			// rule only applies to visible methods with parameters
			// we also exclude all p/invokes since we have a rule for them not to be visible
			if (method.IsPInvokeImpl || !method.HasParameters || !method.IsVisible ())
				return RuleResult.DoesNotApply;

			foreach (ParameterDefinition parameter in method.Parameters) {
				string how = null;
				if (parameter.IsOut) {
					// out is permitted for the "bool Try* (...)" pattern
					if ((method.ReturnType.FullName == "System.Boolean") && 
						method.Name.StartsWith ("Try", StringComparison.Ordinal)) {
						continue;
					}

					how = "out";
				} else if (parameter.IsRef ()) {
					how = "ref";
				}

				if (how != null) {
					// goal is to keep the API as simple as possible so this is more severe for public than protected methods
					Severity severity = method.IsPublic ? Severity.Medium : Severity.Low;
					string msg = String.Format ("Parameter '{0}' passed by reference ({1}).", parameter.Name, how);
					Runner.Report (parameter, severity, Confidence.Total, msg);
				}
			}

			return Runner.CurrentRuleResult;
		}
            /// <summary>
            /// Create the Ctor
            /// </summary>
            private static void CreateDefaultCtor(ReachableContext reachableContext, TypeDefinition type)
            {
                var typeSystem = type.Module.TypeSystem;
                var ctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, typeSystem.Void);
                ctor.DeclaringType = type;

                var body = new MethodBody(ctor);
                body.InitLocals = true;
                ctor.Body = body;

                // Prepare code
                var seq = new ILSequence();
                seq.Emit(OpCodes.Nop);
                seq.Emit(OpCodes.Ret);

                // Append ret sequence
                seq.AppendTo(body);

                // Update offsets
                body.ComputeOffsets();

                // Add ctor
                type.Methods.Add(ctor);
                ctor.SetReachable(reachableContext);
            }
Exemplo n.º 15
0
        /// <summary>
        /// Should the given method be included in the APK?
        /// </summary>
        public bool Include(MethodDefinition method)
        {
            switch (compiler.CompilationMode)
            {
            case CompilationMode.Application:
                break;

            case CompilationMode.ClassLibrary:
                if (method.IsPublic || method.IsFamily || method.IsFamilyOrAssembly)
                {
                    return(true);
                }
                break;

            case CompilationMode.All:
                if (IsRoot(method.DeclaringType))
                {
                    return(true);
                }
                break;

            default:
                throw new CompilerException("Unknown compilation mode " + (int)compiler.CompilationMode);
            }
            return(IncludeMethodTesters.Any(x => x.Include(method, this)));
        }
Exemplo n.º 16
0
        internal static MonoMethodInfo Create(IMonoStructType klass, int index,
                                              Cecil.MethodDefinition minfo)
        {
            MonoFunctionType type = klass.LookupFunction(minfo);

            return(new MonoMethodInfo(klass, index, minfo, type));
        }
Exemplo n.º 17
0
 public override IWeaver GetWeaver(MethodDefinition method, FieldDefinition mixin)
 {
     if (method.CustomAttributes.Any (a => a.AttributeType.FullName == Constants.AsyncStateMachineAttribute))
         return GetAsyncMethodWeaver (method, mixin);
     return new FakeWeaver ();
     throw new NotImplementedException ();
 }
Exemplo n.º 18
0
        public void PropertyDefinitions(AnalysisNet.Types.TypeDefinition analysisNetType, Cecil.TypeDefinition cecilTypeDef)
        {
            foreach (AnalysisNet.Types.PropertyDefinition analysisNetProp in analysisNetType.PropertyDefinitions)
            {
                Cecil.PropertyDefinition cecilProp = new Cecil.PropertyDefinition(analysisNetProp.Name,
                                                                                  Cecil.PropertyAttributes.None,
                                                                                  ReferenceGenerator.TypeReference(analysisNetProp.PropertyType));

                if (analysisNetProp.Getter != null)
                {
                    Cecil.MethodDefinition getterDef = ReferenceGenerator.MethodReference(analysisNetProp.Getter).Resolve();
                    cecilProp.GetMethod = getterDef;
                }
                if (analysisNetProp.Setter != null)
                {
                    Cecil.MethodDefinition setterDef = ReferenceGenerator.MethodReference(analysisNetProp.Setter).Resolve();
                    cecilProp.SetMethod = setterDef;
                }

                SetCustomAttributes(analysisNetProp.Attributes, cecilProp.CustomAttributes);

                // Properties.Add sets this field
                //cecilProp.DeclaringType = ReferenceGenerator.TypeReference(analysisNetType).Resolve();
                cecilTypeDef.Properties.Add(cecilProp);
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="yourMethod"></param>
        /// <param name="targetName"></param>
        /// <returns></returns>
        private MethodDefinition CopyMethod(MethodDefinition yourMethod, string targetName)
        {
            var targetMethod = new MethodDefinition(targetName, yourMethod.Attributes,
                yourMethod.ReturnType) {
                    ImplAttributes = yourMethod.ImplAttributes,
                    SemanticsAttributes = yourMethod.SemanticsAttributes,
                    CallingConvention = yourMethod.CallingConvention,
                    //all the Attributes and Conventions take care of most of the IsX/HasY properties, except for a few.
                    //this can be seen by looking at the Cecil code, where you can see which fields MethodDefinition has.
                    HasThis = yourMethod.HasThis,
                    ExplicitThis = yourMethod.ExplicitThis,
                    NoInlining = yourMethod.NoInlining,
                    NoOptimization = yourMethod.NoOptimization,
                    ReturnType = yourMethod.ReturnType //<---- this is temporary (setting it again to emphasize)
                };

            targetMethod.SecurityDeclarations.AddRange(yourMethod.SecurityDeclarations.Select(x => new SecurityDeclaration(x.Action, x.GetBlob())));

            foreach (var yourTypeParam in yourMethod.GenericParameters) {
                var targetTypeParam = new GenericParameter(yourTypeParam.Name, targetMethod) {
                    Attributes = yourTypeParam.Attributes //includes non-type constraints
                };
                targetMethod.GenericParameters.Add(targetTypeParam);
            }

            //we do this so we can perform collision detection later on.
            foreach (var yourParam in yourMethod.Parameters) {
                targetMethod.Parameters.Add(new ParameterDefinition(yourParam.ParameterType));
            }

            return targetMethod;
        }
Exemplo n.º 20
0
		HashSet<ILVariable> localVariablesToDefine = new HashSet<ILVariable>(); // local variables that are missing a definition
		
		/// <summary>
		/// Creates the body for the method definition.
		/// </summary>
		/// <param name="methodDef">Method definition to decompile.</param>
		/// <param name="context">Decompilation context.</param>
		/// <param name="parameters">Parameter declarations of the method being decompiled.
		/// These are used to update the parameter names when the decompiler generates names for the parameters.</param>
		/// <param name="localVariables">Local variables storage that will be filled/updated with the local variables.</param>
		/// <returns>Block for the method body</returns>
		public static BlockStatement CreateMethodBody(MethodDefinition methodDef,
		                                              DecompilerContext context,
		                                              IEnumerable<ParameterDeclaration> parameters = null,
		                                              ConcurrentDictionary<int, IEnumerable<ILVariable>> localVariables = null)
		{
			if (localVariables == null)
				localVariables = new ConcurrentDictionary<int, IEnumerable<ILVariable>>();
			
			MethodDefinition oldCurrentMethod = context.CurrentMethod;
			Debug.Assert(oldCurrentMethod == null || oldCurrentMethod == methodDef);
			context.CurrentMethod = methodDef;
			try {
				AstMethodBodyBuilder builder = new AstMethodBodyBuilder();
				builder.methodDef = methodDef;
				builder.context = context;
				builder.typeSystem = methodDef.Module.TypeSystem;
				if (Debugger.IsAttached) {
					return builder.CreateMethodBody(parameters, localVariables);
				} else {
					try {
						return builder.CreateMethodBody(parameters, localVariables);
					} catch (OperationCanceledException) {
						throw;
					} catch (Exception ex) {
						throw new ICSharpCode.Decompiler.DecompilerException(methodDef, ex);
					}
				}
			} finally {
				context.CurrentMethod = oldCurrentMethod;
			}
		}
    public RuleResult RecursiveCheckMethod(HashSet<MethodDefinition> seenMethods, MethodDefinition method) {
      if (method == null || seenMethods.Contains(method)){
        return Runner.CurrentRuleResult;
      } else {
        seenMethods.Add(method);
      }

      if (method.HasBody == false) {
        return Runner.CurrentRuleResult;
      }

      foreach(Instruction instruction in method.Body.Instructions) {
        Code code = instruction.OpCode.Code;
        if (code != Code.Call) {
          continue;
        }

        MethodReference def = instruction.Operand as MethodReference;
        if (def == null) {
          continue;
        }

        if (def.DeclaringType.Name == "LQDB") {
          string message = String.Format(CultureInfo.CurrentCulture, "Don't hit LQDB in an update loop.");
          Runner.Report( method, instruction, Severity.Critical, Confidence.Total, message );

          continue;
        } else {
          this.RecursiveCheckMethod(seenMethods, def.Resolve());
        }
      }

      return Runner.CurrentRuleResult;
    }
Exemplo n.º 22
0
        private static void CompileMethod(Mono.Cecil.MethodDefinition sourceMethod, WasmModuleBuilder wasmBuilder)
        {
            Console.WriteLine($"Compiling { sourceMethod.FullName }...");
            var fn = new WasmFunctionBuilder(sourceMethod.FullName, wasmBuilder)
            {
                ExportName = sourceMethod.IsPublic ? $"{sourceMethod.DeclaringType.Name}::{FormatMethodSignature(sourceMethod)}" : null,
                ResultType = ToWebAssemblyType(sourceMethod.ReturnType)
            };

            var paramTypes = sourceMethod.Parameters.Select(p => ToWebAssemblyType(p.ParameterType).Value);

            if (sourceMethod.HasThis)
            {
                paramTypes = paramTypes.Prepend(WebAssembly.ValueType.Int32); // "this"
            }

            var paramIndex = 0;

            foreach (var paramType in paramTypes)
            {
                fn.AddParameter(paramType);
                fn.GetLocalIndex($"arg{paramIndex}", paramType);
                paramIndex++;
            }

            fn.Instructions.AddRange(
                MethodBodyCompiler.Compile(sourceMethod, wasmBuilder, fn));

            ReplaceWithJSInteropCall(sourceMethod);
        }
Exemplo n.º 23
0
 public Blocks(MethodDefinition method)
 {
     var body = method.Body;
     this.method = method;
     this.locals = body.Variables;
     methodBlocks = new InstructionListParser(body.Instructions, body.ExceptionHandlers).parse();
 }
Exemplo n.º 24
0
        private void ExtractParameters(Cecil.MethodDefinition methoddef, IList <AnalysisNetTac.Values.IVariable> ourParameters)
        {
            if (!methoddef.IsStatic)
            {
                AnalysisNet.Types.IType             type = typeExtractor.ExtractType(methoddef.DeclaringType);
                AnalysisNetTac.Values.LocalVariable v    = new AnalysisNetTac.Values.LocalVariable("this", true)
                {
                    Type = type
                };

                ourParameters.Add(v);
                thisParameter = v;
            }

            foreach (Cecil.ParameterDefinition parameter in methoddef.Parameters)
            {
                AnalysisNet.Types.IType             type = typeExtractor.ExtractType(parameter.ParameterType);
                AnalysisNetTac.Values.LocalVariable v    = new AnalysisNetTac.Values.LocalVariable(parameter.Name, true)
                {
                    Type = type
                };

                ourParameters.Add(v);
                parameters.Add(parameter.Index, v);
            }
        }
Exemplo n.º 25
0
        public static bool findRegisterMethod(TypeDefinition type, out MethodDefinition regMethod, out MethodDefinition handler)
        {
            foreach (var method in type.Methods) {
                if (!method.IsStatic || method.Body == null)
                    continue;
                if (method.Body.ExceptionHandlers.Count != 1)
                    continue;

                foreach (var instr in method.Body.Instructions) {
                    if (instr.OpCode.Code != Code.Ldftn)
                        continue;
                    var handlerRef = instr.Operand as MethodReference;
                    if (handlerRef == null)
                        continue;
                    if (!DotNetUtils.isMethod(handlerRef, "System.Reflection.Assembly", "(System.Object,System.ResolveEventArgs)"))
                        continue;
                    if (!MemberReferenceHelper.compareTypes(type, handlerRef.DeclaringType))
                        continue;
                    handler = DotNetUtils.getMethod(type, handlerRef);
                    if (handler == null)
                        continue;
                    if (handler.Body == null || handler.Body.ExceptionHandlers.Count != 1)
                        continue;

                    regMethod = method;
                    return true;
                }
            }

            regMethod = null;
            handler = null;
            return false;
        }
		static private bool Applicable (MethodDefinition method)
		{
			// only internal resources
			if (!method.IsAssembly)
				return false;

			// resources are static getters
			if (!method.IsStatic || !method.IsGetter)
				return false;

			// Ignore well known static getters of resources classes
			string name = method.Name;
			if ("get_Culture".Equals (name, StringComparison.InvariantCulture) ||
				"get_ResourceManager".Equals (name, StringComparison.InvariantCulture))
				return false;

			// rule apply only to static getters in a generated resx class
			TypeDefinition typeDefinition = method.DeclaringType;
			if (!typeDefinition.HasCustomAttributes)
				return false;

			var attributes = typeDefinition.CustomAttributes;
			if (!resXAttributes.All (a => attributes.ContainsType (a)))
				return false;

			return true;
		}
Exemplo n.º 27
0
        public AnalyzedMethodUsesTreeNode(MethodDefinition analyzedMethod)
        {
            if (analyzedMethod == null)
                throw new ArgumentNullException("analyzedMethod");

            this.analyzedMethod = analyzedMethod;
        }
        static IEnumerable <XElement> GetMdocMembers(XElement mdoc, MemberInfo member, RegisterAttribute register, out PropertyInfo property)
        {
            MethodInfo method = member as MethodInfo;

            if (method != null && method.IsSpecialName && !method.IsConstructor)
            {
                // member is a get or set method for a property, and the property
                // won't have a [Register] attribute in the docs.
                property = method.DeclaringType.Properties                // (DefaultBindingFlags)
                           .Single(p => (p.GetMethod == method) || (p.SetMethod == method));
                string name = property.Name;
                return(mdoc.XPathSelectElements("Members/Member")
                       .Where(m => m.Attribute("MemberName").Value == name && m.Element("MemberType").Value == "Property"));
            }
            property = null;
            string attribute = string.IsNullOrEmpty(register.Signature) && string.IsNullOrEmpty(register.Connector)
                                ? string.Format("Android.Runtime.Register(\"{0}\")", register.Name)
                                        : string.Format("Android.Runtime.Register(\"{0}\", \"{1}\", \"{2}\")",
                                                        register.Name, register.Signature, register.Connector);

            return
                (from m in mdoc.XPathSelectElements("Members/Member")
                 where m.Elements("Attributes")
                 .Elements("Attribute")
                 .Elements("AttributeName")
                 // now n.Value may have ", ApiSince=xx" suffix, which requires partial matching...
                 .Any(n => string.CompareOrdinal(n.Value, 0, attribute, 0, attribute.Length - 1) == 0)
                 select m);
        }
		public AnalyzedInterfaceMethodImplementedByTreeNode(MethodDefinition analyzedMethod)
		{
			if (analyzedMethod == null)
				throw new ArgumentNullException("analyzedMethod");

			this.analyzedMethod = analyzedMethod;
		}
Exemplo n.º 30
0
        /// <summary>
        /// Adds a default constructor to the target type.
        /// </summary>
        /// <param name="parentType">The base class that contains the default constructor that will be used for constructor chaining..</param>
        /// <param name="targetType">The type that will contain the default constructor.</param>
        /// <returns>The default constructor.</returns>
        public static MethodDefinition AddDefaultConstructor(this TypeDefinition targetType, Type parentType)
        {
            var module = targetType.Module;
            var voidType = module.Import(typeof(void));
            var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig
                                   | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;

            var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
            var objectConstructor = parentType.GetConstructor(flags, null, new Type[0], null);

            // Revert to the System.Object constructor
            // if the parent type does not have a default constructor
            if (objectConstructor == null)
                objectConstructor = typeof(object).GetConstructor(new Type[0]);

            var baseConstructor = module.Import(objectConstructor);

            // Define the default constructor
            var ctor = new MethodDefinition(".ctor", methodAttributes, voidType)
                           {
                               CallingConvention = MethodCallingConvention.StdCall,
                               ImplAttributes = (MethodImplAttributes.IL | MethodImplAttributes.Managed)
                           };

            var IL = ctor.Body.CilWorker;

            // Call the constructor for System.Object, and exit
            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Call, baseConstructor);
            IL.Emit(OpCodes.Ret);

            targetType.Constructors.Add(ctor);

            return ctor;
        }
Exemplo n.º 31
0
 private MonoMethodInfo(IMonoStructType klass, int index, Cecil.MethodDefinition minfo,
                        MonoFunctionType type)
     : base(type, MonoFunctionType.GetMethodName(minfo), index,
            minfo.IsStatic, GetAccessibility(minfo), type.FullName)
 {
     FunctionType = type;
 }
Exemplo n.º 32
0
 private MethodDefinition FindOldMethodBody(TypeDefinition oldType, MethodDefinition methodDefinition)
 {
     MethodDefinition oldMethodBody = null;
     if (oldType != null)
         oldMethodBody = oldType.Methods.SingleOrDefault(m => m.Name == methodDefinition.Name);
     return oldMethodBody;
 }
Exemplo n.º 33
0
		public RuleResult CheckMethod (MethodDefinition method)
		{
			if (!method.HasBody)
				return RuleResult.DoesNotApply;

			// check if the method contains a Isinst, Ldnull *and* Ceq instruction
			if (!bitmask.IsSubsetOf (OpCodeEngine.GetBitmask (method)))
				return RuleResult.DoesNotApply;

			IList<Instruction> instructions = method.Body.Instructions;
			int n = instructions.Count - 2;
			for (int i = 0; i < n; i++) {
				Code code0 = instructions [i].OpCode.Code;
				if (code0 != Code.Isinst)
					continue;
				Code code1 = instructions [i + 1].OpCode.Code;
				if (code1 != Code.Ldnull)
					continue;
				Code code2 = instructions [i + 2].OpCode.Code;
				if (code2 != Code.Ceq)
					continue;

				Runner.Report (method, instructions[i], Severity.High, Confidence.High);
			}

			return Runner.CurrentRuleResult;
		}
Exemplo n.º 34
0
        public ILBlockTranslator(AssemblyTranslator translator, DecompilerContext context, MethodReference methodReference, MethodDefinition methodDefinition, ILBlock ilb, IEnumerable<ILVariable> parameters, IEnumerable<ILVariable> allVariables)
        {
            Translator = translator;
            Context = context;
            ThisMethodReference = methodReference;
            ThisMethod = methodDefinition;
            Block = ilb;

            SpecialIdentifiers = new JSIL.SpecialIdentifiers(TypeSystem);

            if (methodReference.HasThis)
                Variables.Add("this", JSThisParameter.New(methodReference.DeclaringType, methodReference));

            foreach (var parameter in parameters) {
                if ((parameter.Name == "this") && (parameter.OriginalParameter.Index == -1))
                    continue;

                ParameterNames.Add(parameter.Name);
                Variables.Add(parameter.Name, new JSParameter(parameter.Name, parameter.Type, methodReference));
            }

            foreach (var variable in allVariables) {
                var v = JSVariable.New(variable, methodReference);
                if (Variables.ContainsKey(v.Identifier)) {
                    v = new JSVariable(variable.OriginalVariable.Name, variable.Type, methodReference);
                    RenamedVariables[variable] = v;
                    Variables.Add(v.Identifier, v);
                } else {
                    Variables.Add(v.Identifier, v);
                }
            }
        }
Exemplo n.º 35
0
        public static bool MethodMatch(MethodDefinition candidate, MethodDefinition method)
        {
            if (!candidate.IsVirtual)
            {
                return false;
            }

            if (candidate.Name != method.Name)
            {
                return false;
            }

            if (!Helpers.TypeMatch(candidate.ReturnType, method.ReturnType))
            {
                return false;
            }

            if (candidate.Parameters.Count != method.Parameters.Count)
            {
                return false;
            }

            for (int i = 0; i < candidate.Parameters.Count; i++)
            {
                if (!Helpers.TypeMatch(candidate.Parameters[i].ParameterType, method.Parameters[i].ParameterType))
                {
                    return false;
                }
            }

            return true;
        }
Exemplo n.º 36
0
        private static AssemblyDefinition CreateTestAssembly()
        {
            var name = new AssemblyNameDefinition("TestArithmeticOperatorTurtleAdd", new Version(1, 0));
            var assembly = AssemblyDefinition.CreateAssembly(name, "TestClass", ModuleKind.Dll);
            var type = new TypeDefinition("TestArithmeticOperatorTurtleAdd", "TestClass",
                               TypeAttributes.Class | TypeAttributes.Public);
            var intType = assembly.MainModule.Import(typeof(int));
            var method = new MethodDefinition("TestMethod", MethodAttributes.Public, intType);
            var leftParam = new ParameterDefinition("left", ParameterAttributes.In, intType);
            var rightParam = new ParameterDefinition("right", ParameterAttributes.In, intType);
            method.Parameters.Add(leftParam);
            method.Parameters.Add(rightParam);
            var resultVariable = new VariableDefinition(intType);
            method.Body.Variables.Add(resultVariable);

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

            type.Methods.Add(method);
            assembly.MainModule.Types.Add(type);
            return assembly;
        }
Exemplo n.º 37
0
 public Scope(MethodDefinition method)
 {
     Data = new Stack<HashList<ScopeVariable>>();
       Data.Push(new HashList<ScopeVariable>());
       MaxId = 0;
       Method = method;
 }
Exemplo n.º 38
0
        private static void AddStaticPrototypeCall(MethodDefinition method, FieldDefinition delegateField, FieldDefinition prototypeField)
        {
            Debug.Assert(prototypeField.IsStatic);
            var firstOpcode = method.Body.Instructions.First();
            var il = method.Body.GetILProcessor();

            TypeDefinition delegateType = delegateField.FieldType.Resolve();
            var invokeMethod = delegateType.Methods.Single(m => m.Name == "Invoke");
            int allParamsCount = method.Parameters.Count + (method.IsStatic ? 0 : 1); //all params and maybe this

            var instructions = new[]
            {
                il.Create(OpCodes.Ldsflda, prototypeField),
                il.Create(OpCodes.Ldfld, delegateField),
                il.Create(OpCodes.Brfalse, firstOpcode),

                il.Create(OpCodes.Ldsflda, prototypeField),
                il.Create(OpCodes.Ldfld, delegateField),
            }.Concat(
                Enumerable.Range(0, allParamsCount).Select(i => il.Create(OpCodes.Ldarg, i))
            ).Concat(new[]
            {
                il.Create(OpCodes.Callvirt, invokeMethod),
                il.Create(OpCodes.Ret),
            });

            foreach (var instruction in instructions)
                il.InsertBefore(firstOpcode, instruction);
        }
Exemplo n.º 39
0
        private MethodUsage CreateUsage(MemberReference operand, ModuleDefinition assembly, TypeDefinition type, MethodDefinition method, string testAssemblyPath)
        {
            if (operand == null)
                return null;

            Test test = new Test
                {
                    PathToAssembly = Path.GetDirectoryName(testAssemblyPath),
                    AssemblyName = assembly.Assembly.Name.Name,
                    NamespaceName = type.Namespace,
                    ClassName = type.Name,
                    MethodName = method.Name
                };

            var instructionCall = new MethodUsage
                {
                    AssemblyName = operand.DeclaringType.Scope.Name + ".dll",
                    NamespaceName = operand.DeclaringType.Namespace,
                    ClassName = operand.DeclaringType.Name,
                    MethodName = operand.Name,
                    TestCoverage = new List<Test> {test}
                };

            return instructionCall;
        }
Exemplo n.º 40
0
        internal MonoFunctionType(IMonoStructType klass, Cecil.MethodDefinition mdef)
            : base(klass.File.MonoLanguage)
        {
            this.klass       = klass;
            this.method_info = mdef;
            this.token       = MonoDebuggerSupport.GetMethodToken(mdef);
            this.name        = GetMethodName(mdef) + MonoSymbolFile.GetMethodSignature(mdef);

            Cecil.TypeReference rtype;
            if (mdef.IsConstructor)
            {
                rtype           = mdef.DeclaringType;
                has_return_type = true;
            }
            else
            {
                rtype           = mdef.ReturnType;
                has_return_type = rtype.FullName != "System.Void";
            }
            return_type = klass.File.MonoLanguage.LookupMonoType(rtype);

            parameter_types = new TargetType [mdef.Parameters.Count];
            for (int i = 0; i < mdef.Parameters.Count; i++)
            {
                parameter_types [i] = klass.File.MonoLanguage.LookupMonoType(
                    mdef.Parameters[i].ParameterType);
            }
        }
        private void AddAttributes(MethodDefinition originalMethod, MethodDefinition virtualMethod, MethodDefinition customAttributeCtor)
        {
            var compilerGeneratedCtor = virtualMethod.DeclaringType.Module.Import (typeof (CompilerGeneratedAttribute).GetConstructor (Type.EmptyTypes));
              if (!virtualMethod.CustomAttributes.Any (att => att.Constructor.FullName == compilerGeneratedCtor.FullName))
            virtualMethod.CustomAttributes.Add (new CustomAttribute (compilerGeneratedCtor));

              var editorBrowsableCtor = virtualMethod.DeclaringType.Module.Import (
            typeof (EditorBrowsableAttribute).GetConstructor (new[] { typeof (EditorBrowsableState) }));
              var editorBrowsableAtt = new CustomAttribute (editorBrowsableCtor);
              editorBrowsableAtt.ConstructorArguments.Add (
            new CustomAttributeArgument (virtualMethod.DeclaringType.Module.Import (typeof (EditorBrowsableState)), EditorBrowsableState.Never));
              if (!virtualMethod.CustomAttributes.Any (att => att.Constructor.FullName == editorBrowsableCtor.FullName))
            virtualMethod.CustomAttributes.Add (editorBrowsableAtt);

              if (customAttributeCtor == null)
            return;

              var referringAttributeCtor = originalMethod.DeclaringType.Module.Import (customAttributeCtor);
              if (!originalMethod.CustomAttributes.Any (att => att.Constructor.FullName == referringAttributeCtor.FullName))
              {
            var referringAttribute = new CustomAttribute(referringAttributeCtor);
            referringAttribute.ConstructorArguments.Add (new CustomAttributeArgument (originalMethod.DeclaringType.Module.TypeSystem.String, virtualMethod.Name));
            originalMethod.CustomAttributes.Add (referringAttribute);
              }
        }
Exemplo n.º 42
0
        public static System.Reflection.MethodBase ToSystemMethodInfo(this Mono.Cecil.MethodDefinition md)
        {
            System.Reflection.MethodInfo result = null;
            String md_name = Campy.Utils.Utility.NormalizeMonoCecilName(md.FullName);

            // Get owning type.
            Mono.Cecil.TypeDefinition td = md.DeclaringType;
            Type t = td.ToSystemType();

            foreach (System.Reflection.MethodInfo mi in t.GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.Default))
            {
                String full_name = string.Format("{0} {1}.{2}({3})", mi.ReturnType.FullName, Campy.Utils.Utility.RemoveGenericParameters(mi.ReflectedType), mi.Name, string.Join(",", mi.GetParameters().Select(o => string.Format("{0}", o.ParameterType)).ToArray()));
                full_name = Campy.Utils.Utility.NormalizeSystemReflectionName(full_name);
                if (md_name.Contains(full_name))
                {
                    return(mi);
                }
            }
            foreach (System.Reflection.ConstructorInfo mi in t.GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.CreateInstance | System.Reflection.BindingFlags.Default))
            {
                String full_name = string.Format("{0}.{1}({2})", Campy.Utils.Utility.RemoveGenericParameters(mi.ReflectedType), mi.Name, string.Join(",", mi.GetParameters().Select(o => string.Format("{0}", o.ParameterType)).ToArray()));
                full_name = Campy.Utils.Utility.NormalizeSystemReflectionName(full_name);
                if (md_name.Contains(full_name))
                {
                    return(mi);
                }
            }
            Debug.Assert(result != null);
            return(result);
        }
Exemplo n.º 43
0
        /// <summary>
        /// Add the given method to its declaring class.
        /// </summary>
        protected virtual void SetAccessFlags(DexLib.MethodDefinition dmethod, MethodDefinition method)
        {
            // subclass accesses have already been fixed on an actual use basis.
            if (method.IsPrivate)
            {
                dmethod.IsPrivate = true;
            }
            else if (method.IsFamily || method.IsFamilyOrAssembly)
            {
                dmethod.IsProtected = true;
            }
            else
            {
                dmethod.IsPublic = true;
            }

            if (method.DeclaringType.IsInterface)
            {
                dmethod.IsAbstract = true;
                //dmethod.
            }
            else
            {
                if (method.IsConstructor)
                {
                    dmethod.IsConstructor = true;
                    dmethod.IsStatic      = method.IsStatic;
                    if (method.IsStatic)
                    {
                        // reset access modifiers for static constructors.
                        dmethod.IsPrivate   = false;
                        dmethod.IsProtected = false;
                    }
                }
                else if (method.IsAbstract)
                {
                    dmethod.IsAbstract = true;
                }
                else if (method.IsVirtual)
                {
                    dmethod.IsVirtual = true;
                }
                else if (method.IsStatic)
                {
                    dmethod.IsStatic = true;
                }
                else
                {
                    dmethod.IsFinal = true;
                }
                //if (method.IsInitOnly) dmethod.IsFinal = true;
            }

            if (method.IsCompilerGenerated())
            {
                dmethod.IsSynthetic = true;
            }
        }
Exemplo n.º 44
0
 /// <summary>
 /// Try to find a DllImport attribute on the given method and return it's dllName argument (if found).
 /// </summary>
 internal static bool TryGetDllImportName(this Mono.Cecil.MethodDefinition method, out string dllName)
 {
     dllName = null;
     if (!method.HasPInvokeInfo)
     {
         return(false);
     }
     dllName = method.PInvokeInfo.Module.Name;
     return(true);
 }
Exemplo n.º 45
0
 public void ExtractBasicBlocks()
 {
     this.StartChangeSet(this);
     while (_to_do.Count > 0)
     {
         Mono.Cecil.MethodDefinition definition = _to_do.Pop();
         ExtractBasicBlocksOfMethod(definition);
     }
     _cfa.ConvertToSSA();
 }
        public void UpdateMemberDocs(XElement mdoc, IMemberDefinition member, RegisterAttribute tregister)
        {
            XElement jd = Element;

            RegisterAttribute mregister;
            string            anchor;
            var section = GetSection(member, tregister);

            if (section == null)
            {
                return;
            }

            PropertyInfo           property;
            IEnumerable <XElement> destinations         = GetMdocMembers(mdoc, member, section.RegisterAttribute, out property);
            MemberInfo             secondPropertyMember = null;
            DocumentSection        secondSection        = null;
            RegisterAttribute      secondmregister;
            string prefix = null, secondPrefix = null;

            if (property != null)
            {
                MethodInfo mi = member as MethodInfo;
                if (mi == property.SetMethod)
                {
                    return;
                }
                secondPropertyMember = property.SetMethod;
                if (secondPropertyMember != null)
                {
                    secondSection = GetSection(secondPropertyMember, tregister);
                    if (secondSection != null)
                    {
                        prefix       = "Get";
                        secondPrefix = "Set";
                    }
                }
            }

            foreach (XElement dest in destinations)
            {
                section.UpdateMemberSection(member, tregister, dest, prefix, true);
                if (secondSection != null)
                {
                    secondSection.UpdateMemberSection(secondPropertyMember, tregister, dest, secondPrefix, false);
                    foreach (var e in dest.Descendants("format"))
                    {
                        foreach (var attr in e.Attributes("tmp").ToList())
                        {
                            attr.Remove();
                        }
                    }
                }
            }
        }
Exemplo n.º 47
0
        public static MethodDefinition[] GetHooks(TypeDefinitionCollection scrollsTypes, int version)
        {
            MethodDefinition[] definitions = new Mono.Cecil.MethodDefinition[] {
                scrollsTypes["CardTypeManager"].Methods.GetMethod("feed")[1],
                scrollsTypes["CardImageCache"].Methods.GetMethod("GetLoadedImage")[0],
                scrollsTypes["ResourceManager"].Methods.GetMethod("tryGetTexture2D")[0],
                scrollsTypes["AssetLoader"].Methods.GetMethod("LoadTexture2D")[0]
            };

            return(definitions);
        }
Exemplo n.º 48
0
        /// <summary>
        /// Create a module initializer in an assembly that contains a global::Module.Init() method.
        /// </summary>
        /// <param name="targetAssembly">The assembly to create the module initializer.</param>
        static void Main(FileInfo targetAssembly)
        {
            //https://www.coengoedegebure.com/module-initializers-in-dotnet/
            Console.WriteLine($"Processing {targetAssembly}");
            using (var symbolStream = GetSymbolInformation(targetAssembly.FullName, out ISymbolReaderProvider reader,
                                                           out ISymbolWriterProvider writer))
            {
                var module = ModuleDefinition.ReadModule(targetAssembly.FullName, new ReaderParameters
                {
                    ReadSymbols          = symbolStream != null || reader is EmbeddedPortablePdbReaderProvider,
                    SymbolReaderProvider = reader,
                    SymbolStream         = symbolStream,
                    InMemory             = true,
                });

                var type = module.GetType("Module");
                if (type == null)
                {
                    Console.WriteLine("Could not find global::Module class");
                    return;
                }

                var initMethod = type.GetMethods().FirstOrDefault(x => x.Name == "Init");
                if (initMethod == null)
                {
                    Console.WriteLine("Could not find Init() method on global::Module class");
                    return;
                }


                var assemblyModuleClass = module.GetType("<Module>");
                if (assemblyModuleClass == null)
                {
                    Console.WriteLine("Could not find <Module> class");
                    return;
                }

                const MethodAttributes Attributes =
                    MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
                var cctor = new MethodDefinition(".cctor", Attributes, module.ImportReference(typeof(void)));
                var il    = cctor.Body.GetILProcessor();
                il.Append(il.Create(OpCodes.Call, initMethod));
                il.Append(il.Create(OpCodes.Ret));

                assemblyModuleClass.Methods.Add(cctor);

                module.Write(targetAssembly.FullName, new WriterParameters
                {
                    WriteSymbols         = writer != null,
                    SymbolWriterProvider = writer,
                });
                Console.WriteLine($"Wrote updated assembly '{targetAssembly.FullName}'");
            }
        }
Exemplo n.º 49
0
        private Mono.Cecil.MethodDefinition GetMainDefinitionInCecilModule(ModuleDefinition module)
        {
            IEnumerable <Mono.Cecil.MethodDefinition> mainQuery = from t in module.Types
                                                                  from m in t.Methods
                                                                  where m.IsStatic && m.Name.Equals("Main")
                                                                  select m;

            Mono.Cecil.MethodDefinition main = mainQuery.SingleOrDefault();

            return(main);
        }
Exemplo n.º 50
0
 public FaultifyMethodDefinition(MethodDefinition methodDefinition,
                                 HashSet <IMutationAnalyzer <ConstantMutation, FieldDefinition> > constantReferenceMutationAnalyers,
                                 HashSet <IMutationAnalyzer <OpCodeMutation, Instruction> > opcodeMethodAnalyzers,
                                 HashSet <IMutationAnalyzer <VariableMutation, MethodDefinition> > variableMutationAnalyzers,
                                 HashSet <IMutationAnalyzer <ArrayMutation, MethodDefinition> > arrayMutationAnalyzers)
 {
     MethodDefinition = methodDefinition;
     _constantReferenceMutationAnalyers = constantReferenceMutationAnalyers;
     _opcodeMethodAnalyzers             = opcodeMethodAnalyzers;
     _variableMutationAnalyzers         = variableMutationAnalyzers;
     _arrayMutationAnalyzers            = arrayMutationAnalyzers;
 }
Exemplo n.º 51
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MethodDocumentation"/> class.
        /// </summary>
        /// <param name="methodDefinition">The <see cref="MethodDefinition"/> which to document.</param>
        /// <param name="xElement">The XML element representing the XML comments for the current member.</param>
        /// <param name="handle">The <see cref="EntityHandle"/> that represents the member to document.</param>
        /// <param name="declaringType">The type which declares this member.</param>
        public MethodDocumentation(MethodDefinition methodDefinition, XElement xElement, EntityHandle handle, TypeDocumentation declaringType)
            : base(methodDefinition, xElement, declaringType)
        {
            this.ParameterDocumentations  = this.GetParameterDocumentations(methodDefinition, xElement);
            this.ReturnValueDocumentation = new ReturnValueDocumentation(methodDefinition.MethodReturnType, (from x in xElement.Descendants()
                                                                                                             where x.Name == "returns"
                                                                                                             select x).SingleOrDefault());

            var declaringAssembly = declaringType.DeclaringAssembly;

            this.Declaration = declaringAssembly.Decompiler.DecompileAsString(handle).Trim();
        }
Exemplo n.º 52
0
 private bool IsSameOverload(MethodDefinition methodDefinition, XElement xElement) =>
 methodDefinition.HasParameters == xElement.Descendants().Any(x => x.Name == "param") &&
 methodDefinition.Parameters.Count == xElement.Descendants().Count(x => x.Name == "param") &&
 methodDefinition.Parameters.Select(p => p.Name).SequenceEqual(
     from x in xElement.Descendants()
         where x.Name == "param"
     select x.Attribute("name").Value) &&
 methodDefinition.Parameters.Select(p => p.ParameterType.FullName).SequenceEqual(
     xElement.Attribute("name").Value.Substring(
         xElement.Attribute("name").Value.IndexOf('(') + 1,
         xElement.Attribute("name").Value.Length - xElement.Attribute("name").Value.IndexOf('(') - 2)
     .Split(','));
Exemplo n.º 53
0
        /// <summary>
        /// Add the given method to its declaring class.
        /// </summary>
        protected virtual void SetAccessFlags(DexLib.MethodDefinition dmethod, MethodDefinition method)
        {
            if (method.IsPrivate)
            {
                if (method.DeclaringType.HasNestedTypes)
                {
                    dmethod.IsProtected = true;
                }
                else
                {
                    dmethod.IsPrivate = true;
                }
            }
            else if (method.IsFamily)
            {
                dmethod.IsProtected = true;
            }
            else
            {
                dmethod.IsPublic = true;
            }

            if (method.DeclaringType.IsInterface)
            {
                dmethod.IsAbstract = true;
                //dmethod.
            }
            else
            {
                if (method.IsConstructor)
                {
                    dmethod.IsConstructor = true;
                }
                else if (method.IsAbstract)
                {
                    dmethod.IsAbstract = true;
                }
                else if (method.IsVirtual)
                {
                    dmethod.IsVirtual = true;
                }
                else if (method.IsStatic)
                {
                    dmethod.IsStatic = true;
                }
                else
                {
                    dmethod.IsFinal = true;
                }
                //if (method.IsInitOnly) dmethod.IsFinal = true;
            }
        }
Exemplo n.º 54
0
        public Method_Common_CLRSharp(Type_Common_CLRSharp type, Mono.Cecil.MethodDefinition method)
        {
            if (method == null)
            {
                throw new Exception("not allow null method.");
            }
            this._DeclaringType = type;

            method_CLRSharp = method;
            ReturnType      = type.env.GetType(method.ReturnType.FullName);

            ParamList = new MethodParamList(type.env, method);
        }
Exemplo n.º 55
0
        internal static string GetMethodName(Cecil.MethodDefinition mdef)
        {
            var gen_params = mdef.GenericParameters;

            if ((gen_params == null) || (gen_params.Count == 0))
            {
                return(mdef.Name);
            }
            else
            {
                return(mdef.Name + "`" + gen_params.Count);
            }
        }
Exemplo n.º 56
0
        /// <summary>
        /// Default ctor
        /// </summary>
        public static MethodBuilder Create(AssemblyCompiler compiler, MethodDefinition method)
        {
            string dllName;

            if (method.IsAndroidExtension())
            {
                return(new DexImportMethodBuilder(compiler, method));
            }
            if (method.TryGetDllImportName(out dllName))
            {
                return(new DllImportMethodBuilder(compiler, method, dllName));
            }
            return(new MethodBuilder(compiler, method));
        }
Exemplo n.º 57
0
        private bool IsSameOverload(MethodDefinitionHandle methodDefinitionHandle, MethodDefinition methodDefinition)
        {
            var m2 = this.DeclaringAssembly.PEFile.Metadata.GetMethodDefinition(methodDefinitionHandle);
            var parameterHandles = m2.GetParameters();

            var parameters = (from p in parameterHandles
                              select this.DeclaringAssembly.PEFile.Metadata.GetParameter(p)).ToArray();

            return(methodDefinition.HasParameters && parameterHandles.Any() &&
                   methodDefinition.Parameters.Count == parameterHandles.Count &&
                   (from p in parameters
                    select this.DeclaringAssembly.PEFile.Metadata.GetString(p.Name)).SequenceEqual(from p in methodDefinition.Parameters
                                                                                                   select p.Name));
        }
Exemplo n.º 58
0
 /// <summary>
 /// Should the given method be implemented?
 /// </summary>
 protected override bool ShouldImplementMethod(MethodDefinition method)
 {
     if (!base.ShouldImplementMethod(method))
     {
         return(false);
     }
     if ((method.Name == ".cctor") || (method.Name == ".ctor"))
     {
         return(false);
     }
     if (method.IsPrivate && method.HasOverrides)
     {
         return(false);
     }
     return(true);
 }
Exemplo n.º 59
0
        public static MonoDevelop.Projects.Dom.Modifiers GetModifiers(Mono.Cecil.MethodDefinition method)
        {
            MonoDevelop.Projects.Dom.Modifiers result = MonoDevelop.Projects.Dom.Modifiers.None;

            if (method.IsStatic)
            {
                result |= Modifiers.Static;
            }

            if (method.IsAbstract)
            {
                result |= Modifiers.Abstract;
            }
            else if (method.IsFinal)
            {
                result |= Modifiers.Final;
            }
            else if (method.IsVirtual)
            {
                result |= Modifiers.Virtual;
            }

            if (method.IsPublic)
            {
                result |= Modifiers.Public;
            }
            else if (method.IsPrivate)
            {
                result |= Modifiers.Private;
            }
            else
            {
                result |= Modifiers.Protected;
            }
            if (method.IsAssembly)
            {
                result |= Modifiers.Internal;
            }

            if (method.IsSpecialName)
            {
                result |= Modifiers.SpecialName;
            }

            return(result);
        }
        /// <summary>
        /// Walk from the method up to the containing type, looking for an instance
        /// of the specified attribute type, returning it if found.
        /// </summary>
        /// <param name="method">The method to check.</param>
        /// <param name="type">The attribute type to look for.</param>
        private static CustomAttribute GetHierarchicalAttributeOrNull(Mono.Cecil.MethodDefinition method, Type type)
        {
            var attribute = method.GetCustomAttribute(type);

            if (attribute != null)
            {
                return(attribute);
            }

            attribute = method.DeclaringType.GetCustomAttribute(type);
            if (attribute != null)
            {
                return(attribute);
            }

            return(null);
        }