Inheritance: MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext
Esempio n. 1
0
 public void HeuristicAdd(Mono.Cecil.ModuleDefinition module)
 {
     // Search module for PFEs and add enclosing method.
     // Find all pfe's in graph.
     foreach (Mono.Cecil.MethodDefinition method in Campy.Types.Utils.ReflectionCecilInterop.GetMethods(module))
     {
         if (method.Body == null)
         {
             return;
         }
         foreach (Mono.Cecil.Cil.Instruction i in method.Body.Instructions)
         {
             Mono.Cecil.Cil.OpCode      op = i.OpCode;
             Mono.Cecil.Cil.FlowControl fc = op.FlowControl;
             object operand = i.Operand;
             Mono.Cecil.MethodReference call_to = operand as Mono.Cecil.MethodReference;
             if (fc == Mono.Cecil.Cil.FlowControl.Call)
             {
                 if (call_to != null && call_to.Name.Equals("For") &&
                     call_to.DeclaringType != null && call_to.DeclaringType.FullName.Equals("Campy.Parallel"))
                 {
                     Add(method);
                 }
             }
         }
     }
 }
    public void FindGetLoggerMethod()
    {
        var loggerFactoryAttribute = ModuleDefinition
            .Assembly
            .CustomAttributes
            .FirstOrDefault(x => x.AttributeType.Name == "LoggerFactoryAttribute");

        if (loggerFactoryAttribute == null)
        {
            LogInfo("Could not find a 'LoggerFactoryAttribute' on the current assembly. Going to search current assembly for 'LoggerFactory'.");

            var typeDefinition = ModuleDefinition
                .GetTypes()
                .FirstOrDefault(x => !x.IsGenericInstance && x.Name == "LoggerFactory");
            if (typeDefinition == null)
            {
                throw new WeavingException("Could not find a type named LoggerFactory");
            }

            FindGetLogger(typeDefinition);
        }
        else
        {
            var typeReference = (TypeReference) loggerFactoryAttribute.ConstructorArguments.First().Value;

            FindGetLogger(typeReference.Resolve());

            GetLoggerMethod = ModuleDefinition.ImportReference(GetLoggerMethod);
            ModuleDefinition.Assembly.CustomAttributes.Remove(loggerFactoryAttribute);
        }

    }
Esempio n. 3
0
        private AnalysisNet.Types.IMethodReference ExtractNonGenericInstanceMethod(Cecil.MethodReference methodref)
        {
            AnalysisNet.Types.IType      extractedType = ExtractType(methodref.DeclaringType);
            AnalysisNet.Types.IBasicType containingType;
            if (extractedType is AnalysisNet.Types.ArrayType arrayType)
            {
                containingType = new FakeArrayType(arrayType);
            }
            else
            {
                containingType = (AnalysisNet.Types.IBasicType)extractedType;
            }

            AnalysisNet.Types.MethodReference method = new AnalysisNet.Types.MethodReference(methodref.Name, AnalysisNet.Types.PlatformType.Void);
            genericParameterExtractor.MapGenericParameters(methodref, method);
            method.ReturnType = ExtractType(methodref.ReturnType);

            ExtractParameters(method.Parameters, methodref.Parameters);

            method.GenericParameterCount = methodref.GenericParameters.Count();
            method.ContainingType        = containingType;
            method.IsStatic = !(methodref.HasThis || methodref.ExplicitThis);

            method.Resolve(host);
            return(method);
        }
Esempio n. 4
0
        private AnalysisNet.IInstruction ProcessMethodCall(Cecil.Cil.Instruction op)
        {
            AnalysisNetBytecode.MethodCallOperation operation = OperationHelper.ToMethodCallOperation(op.OpCode.Code);
            Cecil.MethodReference cciMethod = op.Operand as Cecil.MethodReference;
            AnalysisNet.Types.IMethodReference ourMethod = typeExtractor.ExtractMethod(cciMethod);

            AnalysisNet.IInstruction instruction;

            if (ourMethod.ContainingType is FakeArrayType fakeArrayType)
            {
                AnalysisNet.Types.ArrayType arrayType = fakeArrayType.Type;

                if (ourMethod.Name == "Set")
                {
                    instruction = ProcessStoreArrayElement(op, arrayType);
                    return(instruction);
                }
                else
                {
                    AnalysisNetBytecode.LoadArrayElementOperation arrayOp = OperationHelper.ToLoadArrayElementOperation(ourMethod.Name);

                    instruction = ProcessLoadArrayElement(op, arrayOp, arrayType);
                    return(instruction);
                }
            }

            instruction = new AnalysisNetBytecode.MethodCallInstruction((uint)op.Offset, operation, ourMethod);
            return(instruction);
        }
Esempio n. 5
0
 public static GenericBindingContext Create(MethodReference methodReference)
 {
     var genericMethod = methodReference as GenericInstanceMethod;
     return genericMethod != null
         ? new GenericBindingContext(genericMethod)
         : new GenericBindingContext();
 }
Esempio n. 6
0
 public MethodReference GetLogEnabledForLog(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "Debug" || name == "DebugException")
     {
         return IsDebugEnabledMethod;
     }
     if (name == "Info" || name == "InfoException")
     {
         return IsInfoEnabledMethod;
     }
     if (name == "Warn" || name == "WarnException")
     {
         return IsWarnEnabledMethod;
     }
     if (name == "Error" || name == "ErrorException")
     {
         return IsErrorEnabledMethod;
     }
     if (name == "Fatal" || name == "FatalException")
     {
         return IsFatalEnabledMethod;
     }
     throw new Exception("Invalid method name");
 }
 internal static string BuildMethodParameterList(MethodReference interopMethod, MethodReference interfaceMethod, Unity.IL2CPP.ILPreProcessor.TypeResolver typeResolver, MarshalType marshalType, bool includeTypeNames)
 {
     List<string> elements = new List<string>();
     int num = 0;
     foreach (ParameterDefinition definition in interopMethod.Parameters)
     {
         MarshalInfo marshalInfo = interfaceMethod.Parameters[num].MarshalInfo;
         DefaultMarshalInfoWriter writer = MarshalDataCollector.MarshalInfoWriterFor(typeResolver.Resolve(definition.ParameterType), marshalType, marshalInfo, true, false, false, null);
         foreach (MarshaledType type in writer.MarshaledTypes)
         {
             elements.Add(string.Format(!includeTypeNames ? "{1}" : "{0} {1}", type.DecoratedName, Naming.ForParameterName(definition) + type.VariableName));
         }
         num++;
     }
     TypeReference reference2 = typeResolver.Resolve(interopMethod.ReturnType);
     if (reference2.MetadataType != MetadataType.Void)
     {
         MarshalInfo info2 = interfaceMethod.MethodReturnType.MarshalInfo;
         MarshaledType[] marshaledTypes = MarshalDataCollector.MarshalInfoWriterFor(reference2, marshalType, info2, true, false, false, null).MarshaledTypes;
         for (int i = 0; i < (marshaledTypes.Length - 1); i++)
         {
             elements.Add(string.Format(!includeTypeNames ? "{1}" : "{0}* {1}", marshaledTypes[i].DecoratedName, Naming.ForComInterfaceReturnParameterName() + marshaledTypes[i].VariableName));
         }
         elements.Add(string.Format(!includeTypeNames ? "{1}" : "{0}* {1}", marshaledTypes[marshaledTypes.Length - 1].DecoratedName, Naming.ForComInterfaceReturnParameterName()));
     }
     return EnumerableExtensions.AggregateWithComma(elements);
 }
    void FindGetLogger(TypeDefinition typeDefinition)
    {
        if (!typeDefinition.IsPublic)
        {
            var message = $"The logger factory type '{typeDefinition.FullName}' needs to be public.";
            throw new WeavingException(message);
        }
        GetLoggerMethod = typeDefinition
            .Methods
            .FirstOrDefault(x =>
                x.Name ==  "GetLogger" && 
                x.IsStatic &&
                x.HasGenericParameters &&
                x.GenericParameters.Count == 1 &&
                x.Parameters.Count == 0);

        if (GetLoggerMethod == null)
        {
            throw new WeavingException("Found 'LoggerFactory' but it did not have a static 'GetLogger' method that takes 'string' as a parameter");
        }
        if (!GetLoggerMethod.Resolve().IsPublic)
        {
            var message = $"The logger factory method '{GetLoggerMethod.FullName}' needs to be public.";
            throw new WeavingException(message);
        }
    }
Esempio n. 9
0
 public void Init()
 {
     var methods = MsCoreReferenceFinder.StringDefinition.Methods;
     reference_String = ModuleDefinition.ImportReference(methods.First(x => x.Name == "IndexOf" && x.Parameters.Matches("String", "StringComparison")));
     reference_StringInt = ModuleDefinition.ImportReference(methods.First(x => x.Name == "IndexOf" && x.Parameters.Matches("String", "Int32", "StringComparison")));
     reference_StringIntInt = ModuleDefinition.ImportReference(methods.First(x => x.Name == "IndexOf" && x.Parameters.Matches("String", "Int32", "Int32", "StringComparison")));
 }
Esempio n. 10
0
 public MethodReference GetExceptionOperand(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "DebugException")
     {
         return DebugExceptionMethod;
     }
     if (name == "InfoException")
     {
         return InfoExceptionMethod;
     }
     if (name == "WarnException")
     {
         return WarnExceptionMethod;
     }
     if (name == "ErrorException")
     {
         return ErrorExceptionMethod;
     }
     if (name == "FatalException")
     {
         return FatalExceptionMethod;
     }
     throw new Exception("Invalid method name");
 }
Esempio n. 11
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);
                }
            }
        }
Esempio n. 12
0
 public OpCode GetLevelForLog(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "Debug" ||  name == "DebugException")
     {
         return OpCodes.Ldc_I4_2;
     }
     if (name == "Info" || name == "InfoException")
     {
         return OpCodes.Ldc_I4_3;
     }
     if (name == "Warn" || name == "WarnException")
     {
         return OpCodes.Ldc_I4_4;
     }
     if (name == "Error" || name == "ErrorException")
     {
         return OpCodes.Ldc_I4_5;
     }
     if (name == "Fatal" || name == "FatalException")
     {
         return OpCodes.Ldc_I4_6;
     }
     throw new Exception("Invalid method name");
 }
		public MethodDefinition GetExternalMethod (MethodReference mr) {
			string library = GetSymbolLibrary (mr.Name);

			if (library != null) {
				List<MethodDefinition> methods = null;
				if (externalMethods.ContainsKey (mr.Name)) {
					methods = externalMethods [mr.Name];
					foreach (MethodDefinition method in methods) {
						if (CompareMethodSignatures (mr, method)) {
							return method;
						}
					}
				} else {
					methods = new List<MethodDefinition> ();
					externalMethods [mr.Name] = methods;
				}
				if (! referredLibraries.ContainsKey (library)) {
					referredLibraries [library] = new ModuleReference (library);
				}
				MethodDefinition md = CreateExternalMethod (mr, library, referredLibraries [library]);
				methods.Add (md);
				return md;
			} else {
				return null;
			}
		}
Esempio n. 14
0
        public static MethodDefinition GetMethod(IList<MethodDefinition> methods, MethodReference reference)
        {
            for (int i = 0; i < methods.Count; i++) {
                var method = methods [i];

                if (method.Name != reference.Name)
                    continue;

                if (!AreSame (method.ReturnType, reference.ReturnType))
                    continue;

                if (method.HasParameters != reference.HasParameters)
                    continue;

                if (!method.HasParameters && !reference.HasParameters)
                    return method;

                if (!AreSame (method.Parameters, reference.Parameters))
                    continue;

                return method;
            }

            return null;
        }
Esempio n. 15
0
        void EmitInstruction(ILGenerator il, OpCode opcode, Cecil.MethodReference operandMethod)
        {
            var ourType = FindType(operandMethod.DeclaringType);

            Type[] opParamTypes = operandMethod.Parameters.Select((prm) => {
                if (prm.ParameterType is Cecil.GenericParameter)
                {
                    throw new Exception("Unsupported generic parameter");
                    //return ourType.GenericTypeArguments[((Cecil.GenericParameter)prm.ParameterType).Position];
                }

                return(FindType(prm.ParameterType));
            }).ToArray();

            if (operandMethod.Name == ".ctor")
            {
                il.Emit(opcode, ourType.GetConstructor(
                            Reflection.BindingFlags.Instance |
                            Reflection.BindingFlags.Static /*| Reflection.BindingFlags.NonPublic */ |
                            Reflection.BindingFlags.Public,
                            binder: null,
                            types: opParamTypes,
                            modifiers: null));
            }
            else
            {
                il.Emit(opcode, ourType.GetMethod(operandMethod.Name,
                                                  bindingAttr: bflags_all,
                                                  binder: null,
                                                  types: opParamTypes,
                                                  modifiers: null));
            }
        }
    public static MethodReference MakeHostInstanceGeneric(this MethodReference @this, params TypeReference[] genericArguments)
    {
        var genericDeclaringType = new GenericInstanceType(@this.DeclaringType);
        foreach (var genericArgument in genericArguments)
        {
            genericDeclaringType.GenericArguments.Add(genericArgument);
        }

        var reference = new MethodReference(@this.Name, @this.ReturnType, genericDeclaringType)
        {
            HasThis = @this.HasThis,
            ExplicitThis = @this.ExplicitThis,
            CallingConvention = @this.CallingConvention
        };

        foreach (var parameter in @this.Parameters)
        {
            reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
        }

        foreach (var genericParam in @this.GenericParameters)
        {
            reference.GenericParameters.Add(new GenericParameter(genericParam.Name, reference));
        }

        return reference;
    }
Esempio n. 17
0
    public void FindCoreReferences()
    {
        var coreTypes = new List<TypeDefinition>();
        AppendTypes("mscorlib", coreTypes);
        AppendTypes("System.IO", coreTypes);
        AppendTypes("System.Runtime", coreTypes);
        AppendTypes("System.Reflection", coreTypes);

        var textReaderTypeDefinition = coreTypes.First(x => x.Name == "TextReader");
        ReadToEndMethod = ModuleDefinition.ImportReference(textReaderTypeDefinition.Find("ReadToEnd"));

        var exceptionTypeDefinition = coreTypes.First(x => x.Name == "Exception");
        ExceptionConstructorReference = ModuleDefinition.ImportReference(exceptionTypeDefinition.Find(".ctor", "String"));

        var stringTypeDefinition = coreTypes.First(x => x.Name == "String");
        ConcatReference = ModuleDefinition.ImportReference(stringTypeDefinition.Find("Concat", "String", "String", "String"));

        DisposeTextReaderMethod = ModuleDefinition.ImportReference(textReaderTypeDefinition.Find("Dispose"));
        var streamTypeDefinition = coreTypes.First(x => x.Name == "Stream");
        DisposeStreamMethod = ModuleDefinition.ImportReference(streamTypeDefinition.Find("Dispose"));
        StreamTypeReference = ModuleDefinition.ImportReference(streamTypeDefinition);
        var streamReaderTypeDefinition = coreTypes.First(x => x.Name == "StreamReader");
        StreamReaderTypeReference = ModuleDefinition.ImportReference(streamReaderTypeDefinition);
        StreamReaderConstructorReference = ModuleDefinition.ImportReference(streamReaderTypeDefinition.Find(".ctor", "Stream"));
        var assemblyTypeDefinition = coreTypes.First(x => x.Name == "Assembly");
        AssemblyTypeReference = ModuleDefinition.ImportReference(assemblyTypeDefinition);
        GetExecutingAssemblyMethod = ModuleDefinition.ImportReference(assemblyTypeDefinition.Find("GetExecutingAssembly"));
        GetManifestResourceStreamMethod = ModuleDefinition.ImportReference(assemblyTypeDefinition.Find("GetManifestResourceStream", "String"));
    }
Esempio n. 18
0
 public OpCode GetLevel(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "get_IsDebugEnabled")
     {
         return OpCodes.Ldc_I4_2;
     }
     if (name == "get_IsInfoEnabled")
     {
         return OpCodes.Ldc_I4_3;
     }
     if (name == "get_IsWarnEnabled")
     {
         return OpCodes.Ldc_I4_4;
     }
     if (name == "get_IsErrorEnabled")
     {
         return OpCodes.Ldc_I4_5;
     }
     if (name == "get_IsFatalEnabled")
     {
         return OpCodes.Ldc_I4_6;
     }
     throw new Exception("Invalid method name");
 }
		private void FixArguments(MethodReference method, ExpressionCollection arguments)
		{
			TypeDefinition declaringTypeDefinition = method.DeclaringType.Resolve();
			if (declaringTypeDefinition == null)
			{
				return;
			}
			List<MethodDefinition> sameNameMethods = GetSameNameMethods(declaringTypeDefinition, method, arguments);
			if (sameNameMethods.Count > 0)
			{
				for (int i = 0; i < arguments.Count; i++)
				{
					TypeReference paramType = method.Parameters[i].ResolveParameterType(method);
					if (!arguments[i].HasType)
					{
						continue;
					}
					if (arguments[i].ExpressionType.FullName == paramType.FullName)
					{
						continue;
					}
					if (ShouldAddCast(arguments[i], sameNameMethods, i, paramType))
					{
						arguments[i] = new CastExpression(arguments[i], paramType, null);
					}
				}
			}
		}
Esempio n. 20
0
    private static MethodReference CloneMethodWithDeclaringType(MethodDefinition methodDef, TypeReference declaringTypeRef)
    {
        if (!declaringTypeRef.IsGenericInstance || methodDef == null)
        {
            return methodDef;
        }

        var methodRef = new MethodReference(methodDef.Name, methodDef.ReturnType, declaringTypeRef)
        {
            CallingConvention = methodDef.CallingConvention,
            HasThis = methodDef.HasThis,
            ExplicitThis = methodDef.ExplicitThis
        };

        foreach (var paramDef in methodDef.Parameters)
        {
            methodRef.Parameters.Add(new ParameterDefinition(paramDef.Name, paramDef.Attributes, paramDef.ParameterType));
        }

        foreach (var genParamDef in methodDef.GenericParameters)
        {
            methodRef.GenericParameters.Add(new GenericParameter(genParamDef.Name, methodRef));
        }

        return methodRef;
    }
		private void CastMethodArguments(MethodReference method, ExpressionCollection arguments)
		{
			for (int i = 0; i < arguments.Count; i++)
			{
				Expression argument = arguments[i];

				TypeReference parameterType = method.Parameters[i].ResolveParameterType(method);

				if (argument.HasType && parameterType != null && !(argument is LiteralExpression))
				{
					TypeReference argumentType = argument.ExpressionType;
					if ((IsUnsignedIntegerType(argumentType) && IsSignedIntegerType(parameterType)) || (IsSignedIntegerType(argumentType) && IsUnsignedIntegerType(parameterType)))
					{
						Expression toCast = argument;

						if (argument is CastExpression)
						{
							CastExpression argumentCast = argument as CastExpression;
							if (IsIntegerType(argumentCast.TargetType))
							{
								toCast = argumentCast.Expression;
							}
						}

						arguments[i] = new CastExpression(toCast, parameterType, null);
					}
				}
			}
		}
Esempio n. 22
0
 public MethodReference GetNormalOperand(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "Trace")
     {
         return TraceMethod;
     }
     if (name == "Debug")
     {
         return DebugMethod;
     }
     if (name == "Info")
     {
         return InfoMethod;
     }
     if (name == "Warn")
     {
         return WarnMethod;
     }
     if (name == "Error")
     {
         return ErrorMethod;
     }
     if (name == "Fatal")
     {
         return FatalMethod;
     }
     throw new Exception("Invalid method name");
 }
Esempio n. 23
0
 public FunctionPointerType()
     : base(null)
 {
     this.function = new MethodReference ();
     this.function.Name = "method";
     this.etype = MD.ElementType.FnPtr;
 }
Esempio n. 24
0
    public IEnumerable<Instruction> Convert(MethodReference method)
    {
        if (method.Name != "IndexOf")
        {
            yield break;
        }

        if (method.Parameters.Matches("String"))
        {
            yield return Instruction.Create(OpCodes.Ldc_I4, StringComparisonConstant);
            yield return Instruction.Create(OpCodes.Callvirt, reference_String);
            yield break;
        }
        if (method.Parameters.Matches("String","Int32"))
        {
            yield return Instruction.Create(OpCodes.Ldc_I4, StringComparisonConstant);
            yield return Instruction.Create(OpCodes.Callvirt, reference_StringInt);
            yield break;
        }
        if (method.Parameters.Matches("String", "Int32", "Int32"))
        {
            yield return Instruction.Create(OpCodes.Ldc_I4, StringComparisonConstant);
            yield return Instruction.Create(OpCodes.Callvirt, reference_StringIntInt);
        }
    }
Esempio n. 25
0
        public static MethodDefinition InjectEqualsObject(TypeDefinition type, TypeReference typeRef, MethodReference newEquals, int typeCheck)
        {
            var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual;
            var method = new MethodDefinition("Equals", methodAttributes, ReferenceFinder.Boolean.TypeReference);
            method.CustomAttributes.MarkAsGeneratedCode();

            var obj = method.Parameters.Add("obj", ReferenceFinder.Object.TypeReference);

            var body = method.Body;
            var result = body.Variables.Add("result", ReferenceFinder.Boolean.TypeReference);

            var ins = body.Instructions;

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

            AddCheckEqualsReference(type, ins);

            ins.If(
                c => AddTypeChecking(type, typeRef, typeCheck, c),
                t => AddInternalEqualsCall(type, typeRef, newEquals, t, result),
                e => AddReturnFalse(e));

            AddReturn(ins, labelRet, result);

            body.OptimizeMacros();

            type.Methods.Add(method);

            return method;
        }
Esempio n. 26
0
 protected override CallResult createCallResult(MethodReference method, Block block, int callInstrIndex)
 {
     int methodId;
     if (!methodTokenToId.TryGetValue(method.MetadataToken.ToInt32(), out methodId))
         return null;
     return new MyCallResult(block, callInstrIndex, methodId);
 }
Esempio n. 27
0
 public MethodReference GetFormatOperand(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "Debug")
     {
         return DebugFormatMethod;
     }
     if (name == "Info")
     {
         return InfoFormatMethod;
     }
     if (name == "Warn")
     {
         return WarnFormatMethod;
     }
     if (name == "Error")
     {
         return ErrorFormatMethod;
     }
     if (name == "Fatal")
     {
         return FatalFormatMethod;
     }
     throw new Exception("Invalid method name");
 }
 internal static bool MethodSignaturesMatchIgnoreStaticness(MethodReference candidate, MethodReference method)
 {
     if (candidate.Parameters.Count != method.Parameters.Count)
     {
         return false;
     }
     if (candidate.GenericParameters.Count != method.GenericParameters.Count)
     {
         return false;
     }
     Unity.IL2CPP.ILPreProcessor.TypeResolver resolver = new Unity.IL2CPP.ILPreProcessor.TypeResolver(candidate.DeclaringType as GenericInstanceType, candidate as GenericInstanceMethod);
     Unity.IL2CPP.ILPreProcessor.TypeResolver resolver2 = new Unity.IL2CPP.ILPreProcessor.TypeResolver(method.DeclaringType as GenericInstanceType, method as GenericInstanceMethod);
     if (!Unity.IL2CPP.Common.TypeReferenceEqualityComparer.AreEqual(resolver.ResolveReturnType(candidate), resolver2.ResolveReturnType(method), TypeComparisonMode.SignatureOnly))
     {
         return false;
     }
     for (int i = 0; i < candidate.Parameters.Count; i++)
     {
         if (!Unity.IL2CPP.Common.TypeReferenceEqualityComparer.AreEqual(resolver.ResolveParameterType(candidate, candidate.Parameters[i]), resolver2.ResolveParameterType(method, method.Parameters[i]), TypeComparisonMode.SignatureOnly))
         {
             return false;
         }
     }
     return true;
 }
Esempio n. 29
0
        public AnalysisNet.Types.IMethodReference ExtractMethod(Cecil.MethodReference methodReference)
        {
            return(performanceCache.GetOrCreate(methodReference, (cacheEntry) =>
            {
                if (methodReference is Cecil.GenericInstanceMethod instanceMethod)
                {
                    List <AnalysisNet.Types.IType> genericArguments = new List <AnalysisNet.Types.IType>();

                    foreach (Cecil.TypeReference typeParameterref in instanceMethod.GenericArguments)
                    {
                        AnalysisNet.Types.IType typeArgumentref = ExtractType(typeParameterref);
                        genericArguments.Add(typeArgumentref);
                    }

                    AnalysisNet.Types.IMethodReference method = ExtractMethod(instanceMethod.GetElementMethod());
                    AnalysisNet.Types.MethodReference instantiatedMethod = AnalysisNet.Extensions.Instantiate(method, genericArguments);
                    instantiatedMethod.Resolve(host);

                    return instantiatedMethod;
                }
                else
                {
                    return ExtractNonGenericInstanceMethod(methodReference);
                }
            }));
        }
Esempio n. 30
0
    public void Execute()
    {
        var assemblyContainsAttribute = ModuleDefinition.Assembly.CustomAttributes.ContainsAttribute("LogMinimalMessageAttribute");
        var moduleContainsAttribute = ModuleDefinition.CustomAttributes.ContainsAttribute("LogMinimalMessageAttribute");
        if (assemblyContainsAttribute || moduleContainsAttribute)
        {
            LogMinimalMessage = true;
        }
        FindReference();
        Init();
        var stringType = ModuleDefinition.TypeSystem.String.Resolve();
        ConcatMethod = ModuleDefinition.Import(stringType.FindMethod("Concat", "String", "String"));
        FormatMethod = ModuleDefinition.Import(stringType.FindMethod("Format", "String", "Object[]"));
        ObjectArray = new ArrayType(ModuleDefinition.TypeSystem.Object);

        FindExceptionType();
        foreach (var type in ModuleDefinition
            .GetTypes()
            .Where(x => (x.BaseType != null) && !x.IsEnum && !x.IsInterface))
        {
            ProcessType(type);
        }

        //TODO: ensure attributes dont exist on interfaces
        RemoveReference();
    }
    public void Execute()
    {
        var validationTemplateAttribute = ModuleDefinition
            .Assembly
            .CustomAttributes
            .FirstOrDefault(x=>x.AttributeType.Name == "ValidationTemplateAttribute");

        if (validationTemplateAttribute == null)
        {
            LogInfo("Could not find a 'ValidationTemplateAttribute' on the current assembly. Going to search current assembly for 'ValidationTemplate'.");

            TypeDefinition = ModuleDefinition
                .GetTypes()
                .FirstOrDefault(x =>
                    x.Name == "ValidationTemplate" ||
                    x.Name == "ValidationTemplate`1");
            if (TypeDefinition == null)
            {
                throw new WeavingException("Could not find a type named 'ValidationTemplate'");
            }
            TypeReference = TypeDefinition;

            FindConstructor();
        }
        else
        {
            var typeReference = (TypeReference) validationTemplateAttribute.ConstructorArguments.First().Value;

            TypeReference = typeReference;
            TypeDefinition = typeReference.Resolve();

            FindConstructor();
            TemplateConstructor = ModuleDefinition.Import(TemplateConstructor);
        }
    }
        public static bool AreSame(this MethodReference method, MethodReference other)
        {
            var possiblyEqual =
                method.DeclaringType.FullName.Equals(other.DeclaringType.FullName, StringComparison.Ordinal)
                && method.FullName.Equals(other.FullName, StringComparison.Ordinal)
                && method.Parameters.Count == other.Parameters.Count
                && method.GenericParameters.Count == other.GenericParameters.Count
                && method.IsGenericInstance == other.IsGenericInstance;

            if (!possiblyEqual)
            {
                return false;
            }

            for (var i = 0; i < method.Parameters.Count; ++i)
            {
                var pThis = method.Parameters[i];
                var pThat = other.Parameters[i];

                if (!pThis.ParameterType.FullName.Equals(pThat.ParameterType.FullName, StringComparison.Ordinal))
                {
                    return false;
                }
            }

            return true;
        }
Esempio n. 33
0
 public void add(MethodReference calledMethod)
 {
     int count;
     var key = new MethodReferenceAndDeclaringTypeKey(calledMethod);
     calls.TryGetValue(key, out count);
     calls[key] = count + 1;
 }
Esempio n. 34
0
 public MethodReference GetLogEnabled(MethodReference methodReference)
 {
     var name = methodReference.Name;
     if (name == "get_IsDebugEnabled")
     {
         return IsDebugEnabledMethod;
     }
     if (name == "get_IsInfoEnabled")
     {
         return IsInfoEnabledMethod;
     }
     if (name == "get_IsWarnEnabled")
     {
         return IsWarnEnabledMethod;
     }
     if (name == "get_IsErrorEnabled")
     {
         return IsErrorEnabledMethod;
     }
     if (name == "get_IsFatalEnabled")
     {
         return IsFatalEnabledMethod;
     }
     throw new Exception("Invalid method name");
 }
Esempio n. 35
0
        public Cecil.MethodReference MethodReference(AnalysisNet.Types.IMethodReference methodReference)
        {
            if (methodsCache.TryGetValue(methodReference, out Cecil.MethodReference cecilMethodReference))
            {
                return(cecilMethodReference);
            }

            Cecil.TypeReference dummyReturnType = Context.CurrentModule.TypeSystem.Void;
            Cecil.TypeReference declaringType   = TypeReference(methodReference.ContainingType);

            string name = methodReference.Name;

            cecilMethodReference = new Cecil.MethodReference(name, dummyReturnType, declaringType)
            {
                HasThis = !methodReference.IsStatic
            };

            if (methodReference.GenericParameterCount > 0)
            {
                cecilMethodReference.CreateGenericParameters(methodReference.GenericParameterCount);
                MapGenericParameters(cecilMethodReference, methodReference);
                // should we add constraints?
                if (methodReference.GenericArguments.Count == 0)
                {
                    Cecil.GenericInstanceMethod instantiated = new Cecil.GenericInstanceMethod(cecilMethodReference);
                    instantiated.GenericArguments.AddRange(cecilMethodReference.GenericParameters);
                    cecilMethodReference = instantiated;
                }
                else
                {
                    IEnumerable <Cecil.TypeReference> arguments    = methodReference.GenericArguments.Select(ga => TypeReference(ga));
                    Cecil.GenericInstanceMethod       instantiated = new Cecil.GenericInstanceMethod(cecilMethodReference);
                    instantiated.GenericArguments.AddRange(arguments);
                    cecilMethodReference = instantiated;
                }
            }

            cecilMethodReference.ReturnType = TypeReference(methodReference.ReturnType);

            foreach (AnalysisNet.Types.IMethodParameterReference parameter in methodReference.Parameters)
            {
                Cecil.ParameterDefinition cecilParam = new Cecil.ParameterDefinition(TypeReference(parameter.Type));
                if (parameter.Kind == AnalysisNet.Types.MethodParameterKind.In)
                {
                    cecilParam.IsIn = true;
                }
                else if (parameter.Kind == AnalysisNet.Types.MethodParameterKind.Out)
                {
                    cecilParam.IsOut = true;
                }

                cecilMethodReference.Parameters.Add(cecilParam);
            }

            cecilMethodReference          = Context.CurrentModule.ImportReference(cecilMethodReference);
            methodsCache[methodReference] = cecilMethodReference;

            return(cecilMethodReference);
        }
Esempio n. 36
0
 public override void Visit(Model.Bytecode.CreateObjectInstruction instruction)
 {
     Cecil.MethodReference methodReference = referenceGenerator.MethodReference(instruction.Constructor);
     Cecil.Cil.Instruction cilIns          = processor.Create(Mono.Cecil.Cil.OpCodes.Newobj, methodReference);
     Result = new List <Mono.Cecil.Cil.Instruction>()
     {
         cilIns
     };
 }
Esempio n. 37
0
        private AnalysisNet.IInstruction ProcessLoadMethodAddress(Cecil.Cil.Instruction op)
        {
            AnalysisNetBytecode.LoadMethodAddressOperation operation = OperationHelper.ToLoadMethodAddressOperation(op.OpCode.Code);
            Cecil.MethodReference cciMethod = op.Operand as Cecil.MethodReference;
            AnalysisNet.Types.IMethodReference ourMethod = typeExtractor.ExtractMethod(cciMethod);

            AnalysisNetBytecode.LoadMethodAddressInstruction instruction = new AnalysisNetBytecode.LoadMethodAddressInstruction((uint)op.Offset, operation, ourMethod);
            return(instruction);
        }
Esempio n. 38
0
        public override void Visit(Model.Bytecode.StoreArrayElementInstruction instruction)
        {
            Mono.Cecil.Cil.Instruction res = null;

            if (!instruction.Array.IsVector)
            {
                Cecil.MethodReference arraySet = ArrayHelper.ArraySet(referenceGenerator.TypeReference(instruction.Array) as Cecil.ArrayType);
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Call, arraySet);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.IntPtr)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_I);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Int8)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_I1);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Int16)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_I2);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Int32)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_I4);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Int64)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_I8);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Float32)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_R4);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Float64)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_R8);
            }
            else if (instruction.Array.ElementsType == Model.Types.PlatformType.Float64)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_R8);
            }
            else if (instruction.Array.ElementsType.TypeKind == Model.Types.TypeKind.ReferenceType)
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_Ref);
            }
            else
            {
                res = processor.Create(Mono.Cecil.Cil.OpCodes.Stelem_Any, referenceGenerator.TypeReference(instruction.Array.ElementsType));
            }

            Result = new List <Mono.Cecil.Cil.Instruction>()
            {
                res
            };
        }
Esempio n. 39
0
 public CFGVertex FindEntry(Mono.Cecil.MethodReference mr)
 {
     foreach (CFG.CFGVertex node in this.VertexNodes)
     {
         if (node.Method == mr)
         {
             return(node);
         }
     }
     return(null);
 }
Esempio n. 40
0
File: cfg.cs Progetto: baufeng/Campy
 public Vertex FindEntry(Mono.Cecil.MethodReference mr)
 {
     foreach (CFG.Vertex node in this.Vertices)
     {
         if (node._original_method_reference == mr)
         {
             return(node);
         }
     }
     return(null);
 }
Esempio n. 41
0
        public void FindNewBlocks(Assembly assembly)
        {
            // Do not analyze Campy modules generally...
            if (Options.Singleton.Get(Options.OptionType.DoNotAnalyzeCampyAssemblies))
            {
                return;
            }

            // Starting from all blocks in this assembly,
            // find all PFE's, then compute control-flow/
            // data-flow analysis in order to compute call
            // structure and new blocks to analyze.

            List <Inst>          pfe_list    = new List <Inst>();
            List <CFG.CFGVertex> pfe_entries = new List <CFGVertex>();

            // Find all pfe's all nodes in assembly.
            foreach (CFG.CFGVertex node in this.VertexNodes)
            {
                foreach (Inst inst in node._instructions)
                {
                    Mono.Cecil.Cil.OpCode      op = inst.OpCode;
                    Mono.Cecil.Cil.FlowControl fc = op.FlowControl;
                    object operand = inst.Operand;
                    Mono.Cecil.MethodReference call_to = operand as Mono.Cecil.MethodReference;
                    if (fc == Mono.Cecil.Cil.FlowControl.Call)
                    {
                        if (call_to != null && call_to.Name.Equals("For") &&
                            call_to.DeclaringType != null && call_to.DeclaringType.FullName.Equals("Campy.Parallel"))
                        {
                            System.Console.WriteLine("Found PFE in block " + node.Name);
                            pfe_list.Add(inst);
                        }
                    }
                }
            }

            // Convert PFE instructions into a list of entries.
            foreach (Inst inst in pfe_list)
            {
                CFG.CFGVertex entry = FindEntry(inst);
                if (!pfe_entries.Contains(entry))
                {
                    pfe_entries.Add(entry);
                }
            }

            // Perform sparse data flow propagation in order to
            // get all indirect calls. Add those blocks to the graph.
            this._cfa.SparseDataFlowPropagation(pfe_entries);
        }
Esempio n. 42
0
        private static bool AnalyzeMethodCreateNewObjects(MethodDefinition methodDefinition, XElement entity, XElement newMethodNode)
        {
            XElement createNode = null;

            bool result = false;

            Mono.Cecil.Cil.MethodBody body = methodDefinition.Body;
            if (null != body)
            {
                // method calls
                foreach (Instruction itemInstruction in body.Instructions)
                {
                    if (itemInstruction.OpCode.Name.StartsWith("newobj"))
                    {
                        Mono.Cecil.MethodReference methodReference = itemInstruction.Operand as Mono.Cecil.MethodReference;
                        string   typeName         = GetNameFromNewObjMethodReference(methodReference);
                        string   componentName    = NetOfficeSupportTable.GetLibrary(typeName);
                        string[] supportByLibrary = _netOfficeSupportTable.GetTypeSupport(typeName);
                        if (typeName.StartsWith(_apiName) && !typeName.Equals(_apiName + ".dll", StringComparison.InvariantCultureIgnoreCase) &&
                            CountOf(typeName, ".") > 1 && (null != supportByLibrary))
                        {
                            result = true;
                            if (null == createNode)
                            {
                                createNode = new XElement("NewObjects");
                                newMethodNode.Add(createNode);
                            }

                            XElement newObject = new XElement("Entity",
                                                              new XAttribute("Type", typeName),
                                                              new XAttribute("Api", componentName));

                            createNode.Add(newObject);
                            XElement supportByNode = new XElement("SupportByLibrary");
                            newObject.Add(supportByNode);

                            if (null != supportByLibrary)
                            {
                                supportByNode.Add(new XAttribute("Name", typeName), new XAttribute("Api", componentName));
                                foreach (string item in supportByLibrary)
                                {
                                    supportByNode.Add(new XElement("Version", item));
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 43
0
        private AnalysisNet.IInstruction ProcessCreateObject(Cecil.Cil.Instruction op)
        {
            Cecil.MethodReference cciMethod = op.Operand as Cecil.MethodReference;
            AnalysisNet.Types.IMethodReference ourMethod = typeExtractor.ExtractMethod(cciMethod);

            if (ourMethod.ContainingType is FakeArrayType fakeArrayType)
            {
                bool withLowerBounds = ourMethod.Parameters.Count > fakeArrayType.Type.Rank;
                return(CreateArray((uint)op.Offset, fakeArrayType.Type, withLowerBounds));
            }

            AnalysisNetBytecode.CreateObjectInstruction instruction = new AnalysisNetBytecode.CreateObjectInstruction((uint)op.Offset, ourMethod);
            return(instruction);
        }
Esempio n. 44
0
        void EmitInstruction(ILGenerator il, OpCode opcode, Cecil.MethodReference operandMethod)
        {
            var ourType = FindType(operandMethod.DeclaringType);

            Type[] opParamTypes = operandMethod.Parameters.Select((prm) => {
                if (prm.ParameterType is Cecil.GenericParameter)
                {
                    return(ourType.GenericTypeArguments[((Cecil.GenericParameter)prm.ParameterType).Position]);
                }

                return(FindType(prm.ParameterType));
            }).ToArray();

            if (operandMethod.Name == ".ctor")
            {
                var target = ourType.GetConstructor(
                    Reflection.BindingFlags.Instance |
                    Reflection.BindingFlags.Static /*| Reflection.BindingFlags.NonPublic */ |
                    Reflection.BindingFlags.Public,
                    binder: null,
                    types: opParamTypes,
                    modifiers: null);
                if (target == null)
                {
                    throw new Exception($"Cannot find call target constructor: {operandMethod.Name} {opParamTypes}");
                }
                il.Emit(opcode, target);
            }
            else
            {
                var target = ourType.GetMethod(operandMethod.Name,
                                               bindingAttr: bflags_all,
                                               binder: null,
                                               types: opParamTypes,
                                               modifiers: null);
                if (target == null)
                {
                    throw new Exception($"Cannot find call target method: {operandMethod.Name} {opParamTypes}");
                }
                il.Emit(opcode, target);
            }
        }
Esempio n. 45
0
        public override void Visit(Model.Bytecode.CreateArrayInstruction instruction)
        {
            Cecil.ArrayType cilArrayType = referenceGenerator.TypeReference(instruction.Type) as Cecil.ArrayType;

            Mono.Cecil.Cil.Instruction cilIns = null;
            if (!instruction.Type.IsVector)
            {
                Cecil.MethodReference arrayCtor = ArrayHelper.ArrayCtor(cilArrayType as Cecil.ArrayType);
                cilIns = processor.Create(Mono.Cecil.Cil.OpCodes.Newobj, arrayCtor);
            }
            else
            {
                cilIns = processor.Create(Mono.Cecil.Cil.OpCodes.Newarr, cilArrayType.ElementType);
            }

            Result = new List <Mono.Cecil.Cil.Instruction>()
            {
                cilIns
            };
        }
Esempio n. 46
0
        public Reflection.MethodBase FindMethod(Type type, Cecil.MethodReference methodRef)
        {
            Type[] opParamTypes = methodRef.Parameters.Select((prm) => {
                if (prm.ParameterType is Cecil.GenericParameter)
                {
                    throw new Exception("Unsupported generic parameter");
                    //return ourType.GenericTypeArguments[((Cecil.GenericParameter)prm.ParameterType).Position];
                }
                if (prm.ParameterType is Cecil.ArrayType)
                {
                    var arr = (Cecil.ArrayType)prm.ParameterType;
                    if (arr.ElementType.IsGenericParameter)
                    {
                        throw new Exception("Unsupported generic array parameter");
                    }
                }

                return(FindType(prm.ParameterType));
            }).ToArray();

            if (methodRef.Name == ".ctor")
            {
                return(type.GetConstructor(
                           Reflection.BindingFlags.Instance |
                           Reflection.BindingFlags.Static /*| Reflection.BindingFlags.NonPublic */ |
                           Reflection.BindingFlags.Public,
                           binder: null,
                           types: opParamTypes,
                           modifiers: null));
            }
            else
            {
                return(type.GetMethod(methodRef.Name,
                                      bindingAttr: bflags_all,
                                      binder: null,
                                      types: opParamTypes,
                                      modifiers: null));
            }
        }
Esempio n. 47
0
        /// <summary>
        /// Create a method reference for the given method using this this as declaring type.
        /// Usually the method will be returned, unless this type is a generic instance type.
        /// </summary>
        internal static ILMethodReference CreateReference(this ILTypeReference declaringType, ILMethodDefinition method)
        {
            var git = declaringType as GenericInstanceType;

            if (git == null)
            {
                return(method);
            }
            var methodRef = new ILMethodReference(method.Name, method.ReturnType, git);

            methodRef.HasThis      = method.HasThis;
            methodRef.ExplicitThis = method.ExplicitThis;
            foreach (var p in method.Parameters)
            {
                methodRef.Parameters.Add(new ParameterDefinition(p.Name, p.Attributes, p.ParameterType));
            }
            foreach (var gp in method.GenericParameters)
            {
                methodRef.GenericParameters.Add(new GenericParameter(gp.Name, methodRef));
            }
            return(methodRef);
        }
Esempio n. 48
0
        public override void Visit(Model.Bytecode.MethodCallInstruction instruction)
        {
            Mono.Cecil.Cil.Instruction cilIns;
            Cecil.MethodReference      methodReference = referenceGenerator.MethodReference(instruction.Method);

            if (instruction.Operation == Model.Bytecode.MethodCallOperation.Static)
            {
                cilIns = processor.Create(Mono.Cecil.Cil.OpCodes.Call, methodReference);
            }
            else if (instruction.Operation == Model.Bytecode.MethodCallOperation.Virtual)
            {
                cilIns = processor.Create(Mono.Cecil.Cil.OpCodes.Callvirt, methodReference);
            }
            else
            {
                throw new NotImplementedException();
            }

            Result = new List <Mono.Cecil.Cil.Instruction>()
            {
                cilIns
            };
        }
Esempio n. 49
0
        protected void SetCustomAttributes(ICollection <AnalysisNet.Types.CustomAttribute> ourAttributes, ICollection <Cecil.CustomAttribute> cecilAttributes)
        {
            foreach (AnalysisNet.Types.CustomAttribute analysisNetAttr in ourAttributes)
            {
                Cecil.MethodReference ctor = ReferenceGenerator.MethodReference(analysisNetAttr.Constructor);
                Cecil.TypeReference   type = ReferenceGenerator.TypeReference(analysisNetAttr.Type);

                Cecil.CustomAttribute cecilAttr = new Cecil.CustomAttribute(ctor);
                foreach (AnalysisNet.ThreeAddressCode.Values.Constant constant in analysisNetAttr.Arguments)
                {
                    // todo: cci is not working correctly
                    if (constant == null)
                    {
                        continue;
                    }

                    Cecil.CustomAttributeArgument cecilArg = new Cecil.CustomAttributeArgument(ReferenceGenerator.TypeReference(constant.Type), constant.Value);
                    cecilAttr.ConstructorArguments.Add(cecilArg);
                }

                cecilAttributes.Add(cecilAttr);
            }
        }
Esempio n. 50
0
    public static bool EqualsReference(this Mono.Cecil.MethodDefinition definition, Mono.Cecil.MethodReference reference)
    {
        bool parameterMatch = (reference.Parameters.Count == definition.Parameters.Count);

        if (parameterMatch)
        {
            for (int i = 0; i < reference.Parameters.Count; i++)
            {
                Mono.Cecil.ParameterDefinition refParam = reference.Parameters  [i];
                Mono.Cecil.ParameterDefinition defParam = definition.Parameters [i];
                if (!refParam.ParameterType.FullName.Equals(defParam.ParameterType.FullName))
                {
                    parameterMatch = false;
                }
            }
        }

        return((reference.CallingConvention.Equals(definition.CallingConvention) &&
                (reference.DeclaringType.FullName.Equals(definition.DeclaringType.FullName)) &&
                (reference.Name.Equals(definition.Name)) &&
                (reference.ReturnType.ReturnType.FullName.Equals(definition.ReturnType.ReturnType.FullName)) &&
                (reference.GenericParameters.Count == definition.GenericParameters.Count) && parameterMatch));
    }
Esempio n. 51
0
        private static Mono.Cecil.Cil.Instruction GetParameterInstruction(Instruction itemInstruction, int index)
        {
            Mono.Cecil.Cil.Instruction methodInstruction = itemInstruction as Mono.Cecil.Cil.Instruction;
            Mono.Cecil.MethodReference methodReference   = methodInstruction.Operand as Mono.Cecil.MethodReference;

            int         i         = 0;
            Instruction startItem = itemInstruction.Previous;

            while (startItem != null)
            {
                if (startItem.OpCode.Name.StartsWith("ld"))
                {
                    i++;
                    if (i == methodReference.Parameters.Count)
                    {
                        break;
                    }
                }
                startItem = startItem.Previous;
            }

            i = 0;
            while (startItem != null)
            {
                if (startItem.OpCode.Name.StartsWith("ld"))
                {
                    i++;
                    if (i == index)
                    {
                        return(startItem);
                    }
                }
                startItem = startItem.Next;
            }

            return(null);
        }
        public static string Disassemble(DomCecilMethod method, bool markup)
        {
            if (method.MethodDefinition.IsPInvokeImpl)
            {
                return(GettextCatalog.GetString("Method is P/Invoke"));
            }
            if (method.MethodDefinition.Body == null)
            {
                IType type = method.DeclaringType;
                return(type == null ||  type.ClassType == ClassType.Interface ? GettextCatalog.GetString("Interface method") : GettextCatalog.GetString("Abstract method"));
            }

            StringBuilder result = new StringBuilder();

            foreach (Instruction instruction in method.MethodDefinition.Body.Instructions)
            {
                if (markup)
                {
                    result.Append("<b>");
                }
                result.Append(GetInstructionOffset(instruction));
                result.Append(markup ? ":</b> " : ": ");
                result.Append(instruction.OpCode);
                if (markup)
                {
                    result.Append("<i>");
                }
                if (instruction.Operand != null)
                {
                    result.Append(' ');
                    if (instruction.Operand is string)
                    {
                        result.Append('"');
                        result.Append(AssemblyBrowserWidget.FormatText(instruction.Operand.ToString()));
                        result.Append('"');
                    }
                    else if (instruction.Operand is Mono.Cecil.Cil.Instruction)
                    {
                        result.Append(GetInstructionOffset((Mono.Cecil.Cil.Instruction)instruction.Operand));
                    }
                    else if (instruction.Operand is Mono.Cecil.TypeDefinition)
                    {
                        AppendLink(result,
                                   new DomCecilType((Mono.Cecil.TypeDefinition)instruction.Operand).HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.MethodDefinition)
                    {
                        Mono.Cecil.MethodDefinition md = instruction.Operand as Mono.Cecil.MethodDefinition;
                        AppendLink(result,
                                   new DomCecilMethod(md)
                        {
                            DeclaringType = new DomCecilType(md.DeclaringType)
                        }.HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.FieldDefinition)
                    {
                        Mono.Cecil.FieldDefinition fd = instruction.Operand as Mono.Cecil.FieldDefinition;
                        AppendLink(result,
                                   new DomCecilField(fd)
                        {
                            DeclaringType = new DomCecilType(fd.DeclaringType)
                        }.HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.PropertyDefinition)
                    {
                        Mono.Cecil.PropertyDefinition pd = instruction.Operand as Mono.Cecil.PropertyDefinition;
                        AppendLink(result,
                                   new DomCecilProperty(pd)
                        {
                            DeclaringType = new DomCecilType(pd.DeclaringType)
                        }.HelpUrl,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.TypeReference)
                    {
                        AppendLink(result,
                                   "T:" + ((TypeReference)instruction.Operand).FullName,
                                   instruction.Operand.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.MethodReference)
                    {
                        Mono.Cecil.MethodReference mr = instruction.Operand as Mono.Cecil.MethodReference;
                        StringBuilder id            = new StringBuilder(mr.DeclaringType.ToString());
                        bool          isConstructor = mr.Name == ".ctor";
                        if (!isConstructor)
                        {
                            id.Append("." + mr.Name);
                        }
                        id.Append("(");
                        for (int i = 0; i < mr.Parameters.Count; i++)
                        {
                            if (i > 0)
                            {
                                id.Append(',');
                            }
                            id.Append(mr.Parameters[i].ParameterType.FullName);
                        }
                        id.Append(")");
                        AppendLink(result, (isConstructor ? "C:" : "M:") + id, id.ToString());
                    }
                    else if (instruction.Operand is Mono.Cecil.FieldReference)
                    {
                        Mono.Cecil.FieldReference fr = instruction.Operand as Mono.Cecil.FieldReference;
                        string id = fr.DeclaringType + "." + fr.Name;
                        AppendLink(result, "F:" + id, id);
                    }
                    else if (instruction.Operand is Mono.Cecil.PropertyReference)
                    {
                        Mono.Cecil.PropertyReference pr = instruction.Operand as Mono.Cecil.PropertyReference;
                        string id = pr.DeclaringType + "." + pr.Name;
                        AppendLink(result, "P:" + id, id);
                    }
                    else
                    {
                        result.Append(AssemblyBrowserWidget.FormatText(instruction.Operand.ToString()));
                    }
                }
                if (markup)
                {
                    result.Append("</i>");
                }
                result.AppendLine();
            }
            result.AppendLine();
            return(result.ToString());
        }
Esempio n. 53
0
        internal IMethod GetMethod(object token, ILType contextType, ILMethod contextMethod, out bool invalidToken)
        {
            string       methodname = null;
            string       typename   = null;
            List <IType> paramList  = null;
            int          hashCode   = token.GetHashCode();
            IMethod      method;

            IType[] genericArguments = null;
            IType   returnType;

            invalidToken = false;
            bool isConstructor = false;

            if (mapMethod.TryGetValue(hashCode, out method))
            {
                return(method);
            }
            IType type = null;

            if (token is Mono.Cecil.MethodReference)
            {
                Mono.Cecil.MethodReference _ref = (token as Mono.Cecil.MethodReference);
                if (_ref.FullName == "System.Void System.Object::.ctor()")
                {
                    mapMethod[hashCode] = null;
                    return(null);
                }
                if (_ref.FullName == "System.Void System.Attribute::.ctor()")
                {
                    mapMethod[hashCode] = null;
                    return(null);
                }
                methodname = _ref.Name;
                var typeDef = _ref.DeclaringType;
                type = GetType(typeDef, contextType, contextMethod);
                if (type == null)
                {
                    throw new KeyNotFoundException("Cannot find type:" + typename);
                }

                if (token is Mono.Cecil.MethodDefinition)
                {
                    var def = _ref as MethodDefinition;
                    isConstructor = def.IsConstructor;
                }
                else
                {
                    isConstructor = methodname == ".ctor";
                }

                if (_ref.IsGenericInstance)
                {
                    GenericInstanceMethod gim = (GenericInstanceMethod)_ref;
                    genericArguments = new IType[gim.GenericArguments.Count];
                    for (int i = 0; i < genericArguments.Length; i++)
                    {
                        if (gim.GenericArguments[i].IsGenericParameter)
                        {
                            invalidToken = true;
                        }
                        var gt = GetType(gim.GenericArguments[i], contextType, contextMethod);
                        if (gt == null)
                        {
                            gt = contextMethod.FindGenericArgument(gim.GenericArguments[i].Name);
                            if (gt == null)//This means it contains unresolved generic arguments, which means it's not searching the generic instance
                            {
                                genericArguments = null;
                                break;
                            }
                            else
                            {
                                genericArguments[i] = gt;
                            }
                        }
                        else
                        {
                            genericArguments[i] = gt;
                        }
                    }
                }

                paramList  = _ref.GetParamList(this, contextType, contextMethod, genericArguments);
                returnType = GetType(_ref.ReturnType, contextType, null);
            }
            else
            {
                throw new NotImplementedException();
                //Mono.Cecil.GenericInstanceMethod gmethod = _def as Mono.Cecil.GenericInstanceMethod;
                //genlist = new MethodParamList(environment, gmethod);
            }

            if (isConstructor)
            {
                method = type.GetConstructor(paramList);
            }
            else
            {
                method = type.GetMethod(methodname, paramList, genericArguments, returnType);
                if (method != null && method.IsGenericInstance)
                {
                    mapMethod[method.GetHashCode()] = method;
                }
            }

            if (method == null)
            {
                if (isConstructor && contextType.FirstCLRBaseType != null && contextType.FirstCLRBaseType is CrossBindingAdaptor && type.TypeForCLR == ((CrossBindingAdaptor)contextType.FirstCLRBaseType).BaseCLRType)
                {
                    method = contextType.BaseType.GetConstructor(paramList);
                    if (method == null)
                    {
                        throw new KeyNotFoundException("Cannot find method:" + methodname);
                    }
                    invalidToken = true;
                    mapMethod[method.GetHashCode()] = method;
                }
                else
                {
                    throw new KeyNotFoundException("Cannot find method:" + methodname);
                }
            }
            if (!invalidToken)
            {
                mapMethod[hashCode] = method;
            }
            return(method);
        }
Esempio n. 54
0
 public MethodReference Import(MethodReference method, IGenericParameterProvider context)
 {
     return(ImportReference(method, context));
 }
Esempio n. 55
0
 public MethodReference ImportReference(MethodReference method)
 {
     return(ImportReference(method, null));
 }
Esempio n. 56
0
        private static bool AnalyzeMethodCallParameters(Instruction itemInstruction, XElement newMethodCallNode)
        {
            bool result = false;

            Mono.Cecil.Cil.Instruction methodInstruction = itemInstruction as Mono.Cecil.Cil.Instruction;
            Mono.Cecil.MethodReference methodReference   = methodInstruction.Operand as Mono.Cecil.MethodReference;

            int i = 1;

            foreach (ParameterDefinition itemParameter in methodReference.Parameters)
            {
                string paramType = itemParameter.ParameterType.FullName;
                if (paramType.StartsWith(_apiName) && CountOf(paramType, ".") > 1 && !paramType.Equals(_apiName + ".dll", StringComparison.InvariantCultureIgnoreCase))
                {
                    result = true;
                    Mono.Cecil.Cil.Instruction parameterInstruction = GetParameterInstruction(itemInstruction, i);
                    if (itemParameter.ParameterType.IsValueType)
                    {
                        string[] supportByLibrary = _netOfficeSupportTable.GetEnumMemberSupport(itemParameter.ParameterType.FullName, GetOperatorValue(parameterInstruction));
                        if (null != supportByLibrary)
                        {
                            XElement newParameter  = new XElement("Parameter");
                            string   componentName = NetOfficeSupportTable.GetLibrary(itemParameter.ParameterType.FullName);
                            XElement supportByNode = new XElement("SupportByLibrary", new XAttribute("Api", componentName));

                            string enumMemberName = _netOfficeSupportTable.GetEnumMemberNameFromValue(itemParameter.ParameterType.FullName, GetOperatorValue(parameterInstruction));
                            if (null != enumMemberName)
                            {
                                supportByNode.Add(new XAttribute("Name", paramType + "." + enumMemberName));
                            }
                            else
                            {
                                supportByNode.Add(new XAttribute("Name", paramType + "." + GetOperatorValue(parameterInstruction).ToString()));
                            }

                            foreach (string item in supportByLibrary)
                            {
                                supportByNode.Add(new XElement("Version", item));
                            }
                            newParameter.Add(supportByNode);
                            newMethodCallNode.Element("Parameters").Add(newParameter);
                        }
                    }
                    else
                    {
                        string[] supportByLibrary = _netOfficeSupportTable.GetTypeSupport(itemParameter.ParameterType.FullName);
                        if (null != supportByLibrary)
                        {
                            XElement newParameter  = new XElement("Parameter");
                            string   componentName = NetOfficeSupportTable.GetLibrary(itemParameter.ParameterType.FullName);
                            XElement supportByNode = new XElement("SupportByLibrary", new XAttribute("Api", componentName));
                            supportByNode.Add(new XAttribute("Name", paramType));
                            foreach (string item in supportByLibrary)
                            {
                                supportByNode.Add(new XElement("Version", item));
                            }
                            newParameter.Add(supportByNode);
                            newMethodCallNode.Element("Parameters").Add(newParameter);
                        }
                    }
                }
                else
                {
                    Instruction prevInstruction = methodInstruction.Previous;
                    while (prevInstruction.OpCode.Name.StartsWith("ld") || prevInstruction.OpCode.Name.StartsWith("box"))
                    {
                        if (null != prevInstruction.Operand)
                        {
                            string   targetName    = prevInstruction.Operand.ToString();
                            string[] dumyByLibrary = _netOfficeSupportTable.GetTypeSupport(targetName);
                            if (null != dumyByLibrary)
                            {
                                if (null != prevInstruction.Previous.Operand)
                                {
                                    int temp = 0;
                                    if (Int32.TryParse(prevInstruction.Previous.Operand.ToString(), out temp))
                                    {
                                        int    opValue        = Convert.ToInt32(temp);
                                        string enumMemberName = _netOfficeSupportTable.GetEnumMemberNameFromValue(targetName, opValue);
                                        if (null != enumMemberName)
                                        {
                                            string[] supportByLibrary = _netOfficeSupportTable.GetEnumMemberSupport(targetName, opValue);
                                            if (null != supportByLibrary)
                                            {
                                                XElement newParameter  = new XElement("Parameter");
                                                string   componentName = NetOfficeSupportTable.GetLibrary(targetName);
                                                XElement supportByNode = new XElement("SupportByLibrary", new XAttribute("Api", componentName));
                                                supportByNode.Add(new XAttribute("Name", targetName + "." + enumMemberName));

                                                foreach (string item in supportByLibrary)
                                                {
                                                    supportByNode.Add(new XElement("Version", item));
                                                }
                                                newParameter.Add(supportByNode);
                                                newMethodCallNode.Element("Parameters").Add(newParameter);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        prevInstruction = prevInstruction.Previous;
                    }
                }
                i++;
            }

            return(result);
        }
Esempio n. 57
0
        private static bool AnalyzeMethodCalls(MethodDefinition methodDefinition, XElement entity, XElement newMethodNode)
        {
            XElement callsNode = null;

            bool result = false;

            Mono.Cecil.Cil.MethodBody body = methodDefinition.Body;
            if (null != body)
            {
                // method calls
                foreach (Instruction itemInstruction in body.Instructions)
                {
                    if (itemInstruction.OpCode.Name.StartsWith("callvirt"))
                    {
                        Mono.Cecil.Cil.Instruction methodInstruction = itemInstruction as Mono.Cecil.Cil.Instruction;
                        Mono.Cecil.MethodReference methodReference   = methodInstruction.Operand as Mono.Cecil.MethodReference;
                        string callName      = GetCallNameFromAnalyzeMethodCalls(methodReference);
                        string typeName      = GetNameFromNewObjMethodReference(methodReference);
                        string componentName = NetOfficeSupportTable.GetLibrary(typeName);

                        string[] testArray = typeName.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                        if (testArray.Length >= 3 && testArray[2] == "Tools")
                        {
                            continue;
                        }
                        if ((typeName.StartsWith(_apiName)) && !typeName.Equals(_apiName + ".dll", StringComparison.InvariantCultureIgnoreCase) &&
                            CountOf(typeName, ".") > 1 && (!typeName.StartsWith("NetOffice.DeveloperToolbox")))
                        {
                            string[] supportByLibrary = _netOfficeSupportTable.GetTypeCallSupport(callName);
                            result = true;
                            if (null == callsNode)
                            {
                                callsNode = new XElement("Calls");
                                newMethodNode.Add(callsNode);
                            }

                            XElement newObject = new XElement("Entity",
                                                              new XElement("Parameters"),
                                                              new XAttribute("Type", typeName),
                                                              new XAttribute("Name", callName),
                                                              new XAttribute("Api", componentName));

                            callsNode.Add(newObject);
                            XElement supportByNode = new XElement("SupportByLibrary", new XAttribute("Api", componentName));
                            newObject.Add(supportByNode);
                            if (null != supportByLibrary)
                            {
                                supportByNode.Add(new XAttribute("Name", callName));
                                foreach (string item in supportByLibrary)
                                {
                                    supportByNode.Add(new XElement("Version", item));
                                }
                            }

                            bool resultParameter = AnalyzeMethodCallParameters(itemInstruction, newObject);
                        }
                    }
                }
            }

            return(result);
        }
Esempio n. 58
0
 private static string GetNameFromNewObjMethodReference(Mono.Cecil.MethodReference methodReference)
 {
     string[] array  = methodReference.ToString().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
     string[] array2 = array[1].Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
     return(array2[0].Trim());
 }
Esempio n. 59
0
 private static string GetCallNameFromAnalyzeMethodCalls(Mono.Cecil.MethodReference methodReference)
 {
     string[] array = methodReference.ToString().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
     return(array[1].Trim());
 }
Esempio n. 60
-1
 public MMethod getMethod(MethodReference methodReference)
 {
     initMethods();
     MMethod method;
     methodReferenceToMethod.TryGetValue(new MethodReferenceKey(methodReference), out method);
     return method;
 }