Exemplo n.º 1
0
        public override void CompileTimeInitialize(System.Reflection.MethodBase method, AspectInfo aspectInfo)
        {
            base.CompileTimeInitialize(method, aspectInfo);
            MethodInfo info = method as MethodInfo;

            if (info.ReturnType == typeof(void))
            {
                returnType = MethodReturnType.Void;
            }
            else if (info.ReturnType.IsGenericType && info.ReturnType.GetGenericTypeDefinition() == typeof(Task <>))
            {
                returnType = MethodReturnType.TaskOfT;
                var taskTResult = info.ReturnType.GetGenericArguments()[0];
                helper = Activator.CreateInstance(typeof(Extensions.Helper <>).MakeGenericType(taskTResult)) as Extensions.IHelper;
            }
            else if (info.ReturnType == typeof(Task))
            {
                returnType = MethodReturnType.Task;
                helper     = new Extensions.Helper <bool>();
            }
            else
            {
                returnType = MethodReturnType.Other;
            }
        }
        public RuleResult CheckMethod(MethodDefinition method)
        {
            // rule applies only to p/invoke methods
            if (!method.IsPInvokeImpl)
            {
                return(RuleResult.DoesNotApply);
            }

            // check all parameters
            if (method.HasParameters)
            {
                foreach (ParameterDefinition parameter in method.Parameters)
                {
                    if (!CheckBooleanMarshalling(parameter, parameter.ParameterType))
                    {
                        // we can't be sure (confidence) that the MarshalAs is needed
                        // since most of the time the default (4 bytes) is ok - but
                        // the severity is high because this mess up the stack
                        Runner.Report(parameter, Severity.High, Confidence.Normal);
                    }
                }
            }

            // and check return value
            MethodReturnType mrt = method.MethodReturnType;

            if (!CheckBooleanMarshalling(mrt, mrt.ReturnType))
            {
                Runner.Report(mrt, Severity.High, Confidence.Normal);
            }

            return(Runner.CurrentRuleResult);
        }
        public RuleResult CheckMethod(MethodDefinition method)
        {
            // note: using anonymous methods creates a lot of defects but they are all non-visible
            if (!method.IsVisible())
            {
                return(RuleResult.DoesNotApply);
            }

            MethodReturnType return_type = method.MethodReturnType;
            Severity?        severity    = Check(return_type.ReturnType);

            if (severity.HasValue)
            {
                Runner.Report(return_type, severity.Value, Confidence.Total);
            }

            if (method.HasParameters)
            {
                foreach (ParameterDefinition parameter in method.Parameters)
                {
                    severity = Check(parameter.ParameterType);
                    if (severity.HasValue)
                    {
                        Runner.Report(parameter, severity.Value, Confidence.Total);
                    }
                }
            }

            return(Runner.CurrentRuleResult);
        }
        public RuleResult CheckMethod(MethodDefinition method)
        {
            if (!method.IsVisible())
            {
                return(RuleResult.DoesNotApply);
            }

            MethodReturnType mrt = method.MethodReturnType;

            if (IsSpecificXmlType(mrt.ReturnType))
            {
                Runner.Report(mrt, GetSeverity(method), Confidence.High);
            }

            if (method.HasParameters)
            {
                foreach (ParameterDefinition parameter in method.Parameters)
                {
                    if (parameter.IsOut)
                    {
                        continue;                         //out params already have their rule
                    }
                    if (IsSpecificXmlType(parameter.ParameterType))
                    {
                        Runner.Report(parameter, GetSeverity(method), Confidence.High);
                    }
                }
            }

            return(Runner.CurrentRuleResult);
        }
Exemplo n.º 5
0
        private static CustomAttribute ExtractCustomAttribute(this MethodReturnType returnType, Func <CustomAttribute, bool> predicate)
        {
            if (!returnType.HasCustomAttributes)
            {
                return(null);
            }

            return(returnType.CustomAttributes.FirstOrDefault(predicate));
        }
Exemplo n.º 6
0
 void addMethodReturnType(MethodReturnType methodReturnType)
 {
     if (methodReturnType == null)
     {
         return;
     }
     pushMember(methodReturnType.Method as MemberReference);
     pushMember(methodReturnType.ReturnType);
     addParameterDefinition(methodReturnType.Parameter);
 }
 /// <summary>
 /// Gets the children of the given item.
 /// </summary>
 /// <param name="item">Item to get children of.</param>
 /// <returns>Children of <paramref name="item"/>.</returns>
 protected override IEnumerable <object> InvokeForItem(MethodReturnType item)
 {
     if (item.HasCustomAttributes)
     {
         foreach (var customAttribute in item.CustomAttributes)
         {
             yield return(customAttribute);
         }
     }
 }
Exemplo n.º 8
0
 public static string ToFormattedName(this MethodReturnType type)
 {
     // 对 (T, T) 类型的需要特殊考虑。
     if (type.ReturnType.FullName.StartsWith("System.ValueTuple`", StringComparison.InvariantCulture) &&
         type.ReturnType is GenericInstanceType vgt)
     {
         var names = type.CustomAttributes.FirstOrDefault(x => x.AttributeType.FullName is "System.Runtime.CompilerServices.TupleElementNamesAttribute")
                     ?.ConstructorArguments.SelectMany(x => (CustomAttributeArgument[])x.Value).Select(x => x.Value as string).ToArray()
                     ?? new string[vgt.GenericArguments.Count];
         return($"({string.Join(", ", vgt.GenericArguments.Select((x, i) => $"{x.ToFormattedName()}{(names[i] is null ? "" : $" {names[i]}")}"))})");
     }
		public override void Build(MethodReturnType returnType)
		{
			var type = returnType.Type;
			if (Build(ref type))
				_methodReturnTypes.Add(new TupleStruct<TypeSignature, MethodReturnType>(type, returnType));

			if (returnType.MarshalType != null)
				Build(returnType.MarshalType);

			Build(returnType.CustomAttributes);
		}
Exemplo n.º 10
0
        /// <summary>Returns the contents of an XML documentation for the specified member.</summary>
        /// <param name="methodReturnType">The reflected member.</param>
        /// <param name="document">The document.</param>
        /// <returns>The contents of the "summary" tag for the member.</returns>
        public static string GetXmlDocs(this MethodReturnType methodReturnType, XDocument document)
        {
            if (DynamicApis.SupportsXPathApis == false)
            {
                return(string.Empty);
            }

            var element = methodReturnType.GetXmlDocsElement(document);

            return(element.ToXmlDocsContent());
        }
Exemplo n.º 11
0
 public static AssemblyDefinition GetAssemblyFromCustomAttributeProvider(ICustomAttributeProvider provider)
 {
     return(provider switch {
         MemberReference mr => mr.Module.Assembly,
         AssemblyDefinition ad => ad,
         ModuleDefinition md => md.Assembly,
         InterfaceImplementation ii => ii.InterfaceType.Module.Assembly,
         GenericParameterConstraint gpc => gpc.ConstraintType.Module.Assembly,
         ParameterDefinition pd => pd.ParameterType.Module.Assembly,
         MethodReturnType mrt => mrt.ReturnType.Module.Assembly,
         _ => throw new NotImplementedException(provider.GetType().ToString()),
     });
Exemplo n.º 12
0
        public void BuildCustomAttributes(ILConversion conversion, ParameterBuilder returnParameter,
                                          MethodReturnType methodReturnType)
        {
            var builders = CreateCustomAttributeList(conversion, methodReturnType.CustomAttributes);

            for (int i = 0; i < builders.Count; i++)
            {
                var builder1 = builders[i];

                returnParameter.SetCustomAttribute(builder1);
            }
        }
Exemplo n.º 13
0
        protected internal override IEnumerable <StaticAttributeWrapper> GetParameterCustomAttributes(StaticParameterWrapper parameter)
        {
            ParameterDefinition parameterHandle = parameter.Handle as ParameterDefinition;

            if (parameterHandle != null)
            {
                return(EnumerateAttributes(parameterHandle.CustomAttributes));
            }

            MethodReturnType returnTypeHandle = (MethodReturnType)parameter.Handle;

            return(EnumerateAttributes(returnTypeHandle.CustomAttributes));
        }
Exemplo n.º 14
0
        protected override void WriteInteropCallStatement(CppCodeWriter writer, string[] localVariableNames, IRuntimeMetadataAccess metadataAccess)
        {
            MethodReturnType methodReturnType = this.GetMethodReturnType();

            if (methodReturnType.ReturnType.MetadataType != MetadataType.Void)
            {
                base.MarshalInfoWriterFor(methodReturnType).WriteNativeVariableDeclarationOfType(writer, InteropMethodBodyWriter.Naming.ForInteropReturnValue());
            }
            writer.WriteStatement(this.GetMethodCallExpression(localVariableNames));
            this.OnBeforeHResultCheck(writer);
            writer.WriteLine();
            writer.WriteStatement(Emit.Call("il2cpp_codegen_com_raise_exception_if_failed", InteropMethodBodyWriter.Naming.ForInteropHResultVariable()));
        }
Exemplo n.º 15
0
        public static void      InspectMethodReturnType(AssemblyUsages result, MethodReturnType methodReturnType)
        {
            if (AssemblyUsagesExtractor.debug > 1)
            {
                AssemblyUsagesExtractor.Log("Return {0}", methodReturnType.ReturnType);
            }

            using (AutoIndent.Instance)
            {
                result.RegisterTypeRef(methodReturnType.ReturnType);
                AssemblyUsagesExtractor.InspectAttributes(result, methodReturnType);
            }
        }
        public static string GetClassIniatializerByReturnType(MethodReturnType returnType)
        {
            //todo : need to add support for more types
            switch (returnType)
            {
            case MethodReturnType.Void:
                return(null);

            case MethodReturnType.IEnumerable:
                return("new List()");
            }

            return(null);
        }
Exemplo n.º 17
0
        private static void Diff(MethodReturnType returnType1, MethodReturnType returnType2)
        {
            if (!AreSameTypeIgnoreNested(returnType1.ReturnType, returnType2.ReturnType))
            {
                throw new InvalidOperationException($"No matching method for {returnType1.Method}");
            }

            if (returnType1.Attributes != returnType2.Attributes)
            {
                throw new InvalidOperationException($"No matching method for {returnType1.Method}");
            }

            Diff(returnType1.CustomAttributes, returnType2.CustomAttributes, returnType1);
        }
Exemplo n.º 18
0
        /// <summary>
        ///     Initialize a new instance of <see cref="ActionMethodMetadata"/>
        /// </summary>
        /// <param name="controllerType">The controller type</param>
        /// <param name="methodInfo">The method</param>
        public ActionMethodMetadata(Type controllerType, MethodInfo methodInfo)
        {
            //Debug.Assert(controllerType == methodInfo.DeclaringType);

            ControllerType = controllerType;
            MethodInfo     = methodInfo;

            MethodReturnType = methodInfo.ReturnType;
            IsAsync          = typeof(Task).IsAssignableFrom(MethodReturnType);

            if (IsAsync && MethodReturnType.IsGenericType)
            {
                AsyncResultType = MethodReturnType.GetGenericArguments().First();
            }
        }
Exemplo n.º 19
0
        internal static Parameter WrapReturnParameter(
            MethodReturnType returnParameter,
            ClrAssembly assembly,
            IGenericMember enclosingMember)
        {
            var attrBuilder = new AttributeMapBuilder();

            // TODO: actually analyze the parameter's attributes.
            return(new Parameter(
                       TypeHelpers.BoxIfReferenceType(
                           assembly.Resolve(
                               returnParameter.ReturnType,
                               enclosingMember)),
                       returnParameter.Name,
                       new AttributeMap(attrBuilder)));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Check arguments of custom attributes of a method for the return type.
        /// </summary>
        /// <param name="returnType">The method return type.</param>
        private void CheckMethodReturnAttributes(MethodReturnType returnType)
        {
            if (returnType.HasCustomAttributes)
            {
                var customAttributeArgs = returnType.CustomAttributes.SelectMany(ca => GetCustomAttributeArgument(ca));
                CheckCustomAttributes(customAttributeArgs);
            }

            MarshalInfo marshalInfo    = null;
            bool        hasMarshalInfo = returnType.HasMarshalInfo && returnType.TryGetMarshalInfo(out marshalInfo);

            if (hasMarshalInfo && marshalInfo != null)
            {
                CheckMarshalInfo(marshalInfo);
            }
        }
        private void InitializeReturnType(MethodBuilder methodBuilder, MethodReturnType returnType)
        {
            methodBuilder.SetReturnType(ResolveReturnType(returnType));

            ParameterBuilder parameterBuilder = methodBuilder.DefineParameter(0,
                                                                              System.Reflection.ParameterAttributes.Retval, null);

            if (returnType.HasConstant)
            {
                parameterBuilder.SetConstant(returnType.Constant);
            }

            metadataPass.Add(delegate
            {
                InitializeCustomAttributes(parameterBuilder.SetCustomAttribute, returnType.CustomAttributes);
            });
        }
Exemplo n.º 22
0
        private static XElement GetXmlDocsElement(this MethodReturnType parameter, XDocument xml)
        {
            var name   = GetMemberElementName(parameter.Method);
            var result = (IEnumerable)DynamicApis.XPathEvaluate(xml, $"/doc/members/member[@name='{name}']");

            var element = result.OfType <XElement>().FirstOrDefault();

            if (element != null)
            {
                //await ReplaceInheritdocElementsAsync(parameter.Member, element).ConfigureAwait(false);

                var elements = (IEnumerable)DynamicApis.XPathEvaluate(xml, $"/doc/members/member[@name='{name}']/returns");
                return(elements.OfType <XElement>().FirstOrDefault());
            }

            return(null);
        }
Exemplo n.º 23
0
        public static IEnumerable <CustomAttribute> GetEffectiveAttributes(this MethodReturnType methodReturnType)
        {
            var  method = (MethodDefinition)methodReturnType.Method;
            bool same   = true;

            foreach (var def in method.GetInheritanceHierarchy())
            {
                foreach (var attr in def.MethodReturnType.CustomAttributes)
                {
                    if (same || attr.IsInheritable())
                    {
                        yield return(attr);
                    }
                }
                same = false;
            }
        }
        private static MethodDefinition FindMethodFromLocation(IMetadataTokenProvider location)
        {
            ParameterDefinition parameter = (location as ParameterDefinition);

            if (parameter != null)
            {
                return(parameter.Method as MethodDefinition);
            }

            MethodReturnType return_type = (location as MethodReturnType);

            if (return_type != null)
            {
                return(return_type.Method as MethodDefinition);
            }

            return(location as MethodDefinition);
        }
            public bool Equals(MethodDefinition x, MethodDefinition y)
            {
                if (x is null || y is null)
                {
                    return(ReferenceEquals(x, y));
                }

                if ((x.Attributes & MethodAttributes.MemberAccessMask) != (y.Attributes & MethodAttributes.MemberAccessMask))
                {
                    return(false);
                }

                if (x.IsStatic != y.IsStatic)
                {
                    return(false);
                }

                if (x.Name != y.Name)
                {
                    return(false);
                }

                if (x.GenericParameters.Count != y.GenericParameters.Count)
                {
                    return(false);
                }

                if (x.Parameters.Count != y.Parameters.Count)
                {
                    return(false);
                }

                if (!MethodReturnType.Equals(x.MethodReturnType, y.MethodReturnType))
                {
                    return(false);
                }

                if (!x.Parameters.SequenceEqual(y.Parameters, ParameterDefinition))
                {
                    return(false);
                }

                return(true);
            }
Exemplo n.º 26
0
        public static MarshalProcessor GetMarshaler(MethodProcessor methodProcessor, MethodReturnType parameter)
        {
            var assemblyProcessor = methodProcessor.TypeContext.ModuleContext.AssemblyContext;

            if (!parameter.HasMarshalInfo && parameter.ReturnType.IsValueType)
            {
                return(null);
            }
            if (!parameter.ReturnType.IsValueType && !parameter.HasMarshalInfo)
            {
                return(null);
            }
            var attribute = parameter.MarshalInfo;

            switch (attribute)
            {
            case CustomMarshalInfo c:
                var managedType        = c.ManagedType.Resolve();
                var interfaces         = managedType.Interfaces;
                var marshalerInterface =
                    assemblyProcessor.ImportAssembly.MainModule.GetType("ImpWiz.Import.Marshalers",
                                                                        "IImpWizMarshaler");
                if (interfaces.Any(x =>
                                   x.InterfaceType.Namespace == "System.Runtime.InteropServices" &&
                                   x.InterfaceType.Name == "ICustomMarshaler"))
                {
                    return(new MarshalProcessor(new MarshalerType(assemblyProcessor.ImportAssembly.MainModule.GetType(typeof(ImpWizCustomMarshaler <>).FullName)
                                                                  .MakeGenericInstanceType(c.ManagedType).Resolve()), methodProcessor, parameter));
                }
                else if (marshalerInterface.IsAssignableFrom(managedType))
                {
                    return(new MarshalProcessor(new MarshalerType(managedType), methodProcessor, parameter));
                }

                break;
            }

            if (assemblyProcessor.SupportedMarshalers.TryGetValue((UnmanagedType)attribute.NativeType, out var marshalers))
            {
                return(new MarshalProcessor(marshalers.First(), methodProcessor, parameter));
            }
            return(null);
        }
Exemplo n.º 27
0
        private void WriteMethodBodyImpl(CppCodeWriter writer, IRuntimeMetadataAccess metadataAccess)
        {
            this.WriteMethodPrologue(writer, metadataAccess);
            string[] localVariableNames = this.WriteMarshalInputParameters(writer, metadataAccess);
            string   unmarshaledReturnValueVariableName = null;

            object[] args = new object[] { this._marshaler.GetPrettyCalleeName() };
            writer.WriteLine("// {0} invocation", args);
            this.WriteInteropCallStatement(writer, localVariableNames, metadataAccess);
            writer.WriteLine();
            MethodReturnType methodReturnType = this.GetMethodReturnType();

            if (methodReturnType.ReturnType.MetadataType != MetadataType.Void)
            {
                unmarshaledReturnValueVariableName = this._marshaler.WriteMarshalReturnValue(writer, methodReturnType, this._parameters, metadataAccess);
                this._marshaler.WriteMarshalCleanupReturnValue(writer, methodReturnType, metadataAccess);
            }
            this.WriteMarshalOutputParameters(writer, localVariableNames, metadataAccess);
            this.WriteMethodEpilogue(writer, metadataAccess);
            this.WriteReturnStatement(writer, unmarshaledReturnValueVariableName, metadataAccess);
        }
Exemplo n.º 28
0
        protected DefaultMarshalInfoWriter FirstOrDefaultUnmarshalableMarshalInfoWriter()
        {
            foreach (MarshaledParameter parameter in this._parameters)
            {
                if (!this._marshaler.CanMarshalAsInputParameter(parameter))
                {
                    return(this._marshaler.MarshalInfoWriterFor(parameter));
                }
                if (this.IsOutParameter(parameter) && !this._marshaler.CanMarshalAsOutputParameter(parameter))
                {
                    return(this._marshaler.MarshalInfoWriterFor(parameter));
                }
            }
            MethodReturnType methodReturnType = this.GetMethodReturnType();

            if ((methodReturnType.ReturnType.MetadataType != MetadataType.Void) && !this._marshaler.CanMarshalAsOutputParameter(methodReturnType))
            {
                return(this._marshaler.MarshalInfoWriterFor(methodReturnType));
            }
            return(null);
        }
Exemplo n.º 29
0
        private PrimitiveType?GetPrimitiveTypeByMethodReturnType(MethodReturnType methodReturnType, Type returnType)
        {
            switch (methodReturnType)
            {
            case MethodReturnType.Primitive:
            {
                return(GetPrimitiveType(returnType.Name));
            }

            //This is a special case. You would want to deserialize HTTPResult into a string
            case MethodReturnType.HttpResult:
            case MethodReturnType.Task:
            case MethodReturnType.IEnumerable:
            {
                return(PrimitiveType.String);
            }

            default:
                return(null);
            }
        }
Exemplo n.º 30
0
        protected override void WriteInteropCallStatement(CppCodeWriter writer, string[] localVariableNames, IRuntimeMetadataAccess metadataAccess)
        {
            MethodReturnType methodReturnType = this.GetMethodReturnType();

            if (methodReturnType.ReturnType.MetadataType != MetadataType.Void)
            {
                object[] args = new object[] { InteropMethodBodyWriter.Naming.ForVariable(base._typeResolver.Resolve(methodReturnType.ReturnType)), InteropMethodBodyWriter.Naming.ForInteropReturnValue() };
                writer.WriteLine("{0} {1};", args);
            }
            writer.WriteLine("try");
            using (new BlockWriter(writer, false))
            {
                if (base._managedMethod.DeclaringType.IsValueType())
                {
                    object[] objArray2 = new object[] { InteropMethodBodyWriter.Naming.ForTypeNameOnly(base._managedMethod.DeclaringType), InteropMethodBodyWriter.Naming.ThisParameterName, metadataAccess.TypeInfoFor(base._managedMethod.DeclaringType) };
                    writer.WriteLine("{0}* {1} = ({0}*)UnBox(GetManagedObjectInline(), {2});", objArray2);
                }
                else
                {
                    object[] objArray3 = new object[] { InteropMethodBodyWriter.Naming.ForVariable(base._managedMethod.DeclaringType), InteropMethodBodyWriter.Naming.ThisParameterName };
                    writer.WriteLine("{0} {1} = ({0})GetManagedObjectInline();", objArray3);
                }
                string block = base.GetMethodCallExpression(metadataAccess, InteropMethodBodyWriter.Naming.ThisParameterName, localVariableNames);
                if (methodReturnType.ReturnType.MetadataType != MetadataType.Void)
                {
                    object[] objArray4 = new object[] { InteropMethodBodyWriter.Naming.ForInteropReturnValue(), block };
                    writer.WriteLine("{0} = {1};", objArray4);
                }
                else
                {
                    writer.WriteStatement(block);
                }
            }
            writer.WriteLine("catch (const Il2CppExceptionWrapper& ex)");
            using (new BlockWriter(writer, false))
            {
                writer.WriteLine("return ex.ex->hresult;");
            }
        }