Ejemplo n.º 1
0
        private void ImplementSignal(SignalDescription signalDescription, bool isPropertiesChanged)
        {
            var         method = _typeBuilder.ImplementInterfaceMethod(signalDescription.MethodInfo);
            ILGenerator ilg    = method.GetILGenerator();

            // call Watch(...)

            // BusObject (this)
            ilg.Emit(OpCodes.Ldarg_0);
            ilg.Emit(OpCodes.Castclass, s_dbusObjectProxyType);

            // Interface
            ilg.Emit(OpCodes.Ldstr, signalDescription.Interface.Name);

            // Member
            ilg.Emit(OpCodes.Ldstr, signalDescription.Name);

            // Action<Exception>
            if (signalDescription.HasOnError)
            {
                ilg.Emit(OpCodes.Ldarg_2);
            }
            else
            {
                ilg.Emit(OpCodes.Ldnull);
            }

            // Action/Action<>
            ilg.Emit(OpCodes.Ldarg_1);

            if (signalDescription.SignalType != null)
            {
                // ReadMethodDelegate
                ilg.Emit(OpCodes.Ldnull);
                ilg.Emit(OpCodes.Ldftn, ReadMethodFactory.CreateReadMethodForType(signalDescription.SignalType));
                var readDelegateConstructor = s_readMethodDelegateGenericType.MakeGenericType(new[] { signalDescription.SignalType }).GetConstructors()[0];
                ilg.Emit(OpCodes.Newobj, readDelegateConstructor);

                // isPropertiesChanged
                ilg.Emit(isPropertiesChanged ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);

                // Watch
                ilg.Emit(OpCodes.Call, s_watchNonVoidSignal.MakeGenericMethod(new[] { signalDescription.SignalType }));
            }
            else
            {
                // Watch
                ilg.Emit(OpCodes.Call, s_watchVoidSignal);
            }

            ilg.Emit(OpCodes.Ret);
        }
Ejemplo n.º 2
0
        public InterfaceDescription(Type type, string name, IList <MethodDescription> methods, IList <SignalDescription> signals,
                                    IList <PropertyDescription> properties, MethodDescription propertyGetMethod, MethodDescription propertyGetAllMethod, MethodDescription propertySetMethod,
                                    SignalDescription propertiesChangedSignal)
        {
            Type     = type;
            Name     = name;
            _methods = methods;
            _signals = signals;
            GetAllPropertiesMethod  = propertyGetAllMethod;
            SetPropertyMethod       = propertySetMethod;
            GetPropertyMethod       = propertyGetMethod;
            PropertiesChangedSignal = propertiesChangedSignal;
            _properties             = properties;

            foreach (var signal in Signals)
            {
                signal.Interface = this;
            }
            if (propertiesChangedSignal != null)
            {
                PropertiesChangedSignal.Interface = this;
            }
            foreach (var method in Methods)
            {
                method.Interface = this;
            }
            foreach (var method in new[] { GetPropertyMethod,
                                           SetPropertyMethod,
                                           GetAllPropertiesMethod })
            {
                if (method != null)
                {
                    method.Interface = this;
                }
            }
        }
Ejemplo n.º 3
0
        private static void AddInterfaceDescription(Type type, DBusInterfaceAttribute interfaceAttribute, List <InterfaceDescription> interfaces)
        {
            if (interfaces.Any(interf => interf.Name == interfaceAttribute.Name))
            {
                throw new ArgumentException($"DBus interface {interfaceAttribute.Name} is inherited multiple times");
            }

            IList <MethodDescription>   methods                 = null;
            IList <SignalDescription>   signals                 = null;
            IList <PropertyDescription> properties              = null;
            MethodDescription           propertyGetMethod       = null;
            MethodDescription           propertySetMethod       = null;
            MethodDescription           propertyGetAllMethod    = null;
            SignalDescription           propertiesChangedSignal = null;
            Type propertyType = interfaceAttribute.PropertyType;
            Type elementType;

            if (propertyType != null && ArgTypeInspector.InspectEnumerableType(propertyType, out elementType, isCompileTimeType: true) != ArgTypeInspector.EnumerableType.AttributeDictionary)
            {
                throw new ArgumentException($"Property type '{propertyType.FullName}' does not have the '{typeof(DictionaryAttribute).FullName}' attribute");
            }

            foreach (var member in type.GetMethods())
            {
                string memberName = member.ToString();
                if (!member.Name.EndsWith("Async", StringComparison.Ordinal))
                {
                    throw new ArgumentException($"{memberName} does not end with 'Async'");
                }
                var isSignal = member.Name.StartsWith("Watch", StringComparison.Ordinal);
                if (isSignal)
                {
                    if (member.ReturnType != s_signalReturnType)
                    {
                        throw new ArgumentException($"Signal {memberName} does not return 'Task<IDisposable>'");
                    }

                    var name = member.Name.Substring(5, member.Name.Length - 10);
                    if (name.Length == 0)
                    {
                        throw new ArgumentException($"Signal {memberName} has an empty name");
                    }

                    Signature?parameterSignature          = null;
                    IList <ArgumentDescription> arguments = null;
                    var  parameters           = member.GetParameters();
                    var  actionParameter      = parameters.Length > 0 ? parameters[0] : null;
                    Type parameterType        = null;
                    bool validActionParameter = false;
                    if (actionParameter != null)
                    {
                        if (actionParameter.ParameterType == s_exceptionActionType)
                        {
                            // actionParameter is missing
                        }
                        else if (actionParameter.ParameterType == s_emptyActionType)
                        {
                            validActionParameter = true;
                        }
                        else if (actionParameter.ParameterType.GetTypeInfo().IsGenericType &&
                                 actionParameter.ParameterType.GetGenericTypeDefinition() == s_singleParameterActionType)
                        {
                            validActionParameter = true;
                            parameterType        = actionParameter.ParameterType.GetGenericArguments()[0];
                            InspectParameterType(parameterType, actionParameter, out parameterSignature, out arguments);
                        }
                    }
                    if (parameters.Length > 0 && parameters[parameters.Length - 1].ParameterType == s_cancellationTokenType)
                    {
                        throw new NotSupportedException($"Signal {memberName} does not support cancellation. See https://github.com/tmds/Tmds.DBus/issues/15.");
                    }
                    var  lastParameter = parameters.Length > 0 ? parameters[parameters.Length - 1] : null;
                    bool hasOnError    = lastParameter?.ParameterType == s_exceptionActionType;
                    if (!validActionParameter || parameters.Length != 1 + (hasOnError ? 1 : 0))
                    {
                        throw new ArgumentException($"Signal {memberName} must accept an argument of Type 'Action'/'Action<>' and optional argument of Type 'Action<Exception>'");
                    }

                    var signal = new SignalDescription(member, name, actionParameter.ParameterType, parameterType, parameterSignature, arguments, hasOnError);
                    if (member.Name == interfaceAttribute.WatchPropertiesMethod)
                    {
                        if (propertiesChangedSignal != null)
                        {
                            throw new ArgumentException($"Multiple property changes signals are declared: {memberName}, {propertyGetMethod.MethodInfo.ToString()}");
                        }
                        propertiesChangedSignal = signal;
                        if (propertiesChangedSignal.SignalSignature != s_propertiesChangedSignature)
                        {
                            throw new ArgumentException($"PropertiesChanged signal {memberName} must accept an Action<T> where T is a struct with an IDictionary<string, object> and an string[] field");
                        }
                    }
                    else
                    {
                        signals = signals ?? new List <SignalDescription>();
                        signals.Add(signal);
                    }
                }
                else
                {
                    var name = member.Name.Substring(0, member.Name.Length - 5);
                    if (name.Length == 0)
                    {
                        throw new ArgumentException($"DBus Method {memberName} has an empty name");
                    }

                    IList <ArgumentDescription> outArguments = null;
                    Signature?outSignature  = null;
                    var       taskParameter = member.ReturnType;
                    Type      outType       = null;
                    bool      valid         = false;
                    bool      isGenericOut  = false;
                    if (taskParameter != null)
                    {
                        if (taskParameter == s_emptyTaskType)
                        {
                            valid   = true;
                            outType = null;
                        }
                        else if (taskParameter.GetTypeInfo().IsGenericType &&
                                 taskParameter.GetGenericTypeDefinition() == s_parameterTaskType)
                        {
                            valid   = true;
                            outType = taskParameter.GetGenericArguments()[0];
                            if (outType.IsGenericParameter)
                            {
                                outType      = s_objectType;
                                isGenericOut = true;
                            }
                            InspectParameterType(outType, member.ReturnParameter, out outSignature, out outArguments);
                        }
                    }
                    if (!valid)
                    {
                        throw new ArgumentException($"DBus Method {memberName} does not return 'Task'/'Task<>'");
                    }

                    IList <ArgumentDescription> inArguments = null;
                    Signature?inSignature = null;
                    var       parameters  = member.GetParameters();
                    if (parameters.Length > 0 && parameters[parameters.Length - 1].ParameterType == s_cancellationTokenType)
                    {
                        throw new NotSupportedException($"DBus Method {memberName} does not support cancellation. See https://github.com/tmds/Tmds.DBus/issues/15.");
                    }

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        var param          = parameters[i];
                        var parameterType  = param.ParameterType;
                        var paramSignature = Signature.GetSig(parameterType, isCompileTimeType: true);
                        if (inSignature == null)
                        {
                            inSignature = paramSignature;
                        }
                        else
                        {
                            inSignature = Signature.Concat(inSignature.Value, paramSignature);
                        }
                        inArguments = inArguments ?? new List <ArgumentDescription>();
                        var argumentAttribute = param.GetCustomAttribute <ArgumentAttribute>(false);
                        var argName           = argumentAttribute != null ? argumentAttribute.Name : param.Name;
                        inArguments.Add(new ArgumentDescription(argName, paramSignature, parameterType));
                    }

                    var methodDescription = new MethodDescription(member, name, inArguments, inSignature, outType, isGenericOut, outSignature, outArguments);
                    if (member.Name == interfaceAttribute.GetPropertyMethod)
                    {
                        if (propertyGetMethod != null)
                        {
                            throw new ArgumentException($"Multiple property Get methods are declared: {memberName}, {propertyGetMethod.MethodInfo.ToString()}");
                        }
                        propertyGetMethod = methodDescription;
                        if ((propertyGetMethod.InSignature != Signature.StringSig) ||
                            (propertyGetMethod.OutSignature != Signature.VariantSig))
                        {
                            throw new ArgumentException($"Property Get method {memberName} must accept a 'string' parameter and return 'Task<object>'");
                        }
                    }
                    else if (member.Name == interfaceAttribute.GetAllPropertiesMethod)
                    {
                        if (propertyGetAllMethod != null)
                        {
                            throw new ArgumentException($"Multiple property GetAll are declared: {memberName}, {propertyGetAllMethod.MethodInfo.ToString()}");
                        }
                        propertyGetAllMethod = methodDescription;
                        if ((propertyGetAllMethod.InArguments.Count != 0) ||
                            (propertyGetAllMethod.OutSignature != s_getAllOutSignature))
                        {
                            throw new ArgumentException($"Property GetAll method {memberName} must accept no parameters and return 'Task<IDictionary<string, object>>'");
                        }
                        if (propertyType == null)
                        {
                            if (ArgTypeInspector.InspectEnumerableType(methodDescription.OutType, out elementType, isCompileTimeType: true) == ArgTypeInspector.EnumerableType.AttributeDictionary)
                            {
                                propertyType = methodDescription.OutType;
                            }
                        }
                    }
                    else if (member.Name == interfaceAttribute.SetPropertyMethod)
                    {
                        if (propertySetMethod != null)
                        {
                            throw new ArgumentException($"Multiple property Set are declared: {memberName}, {propertySetMethod.MethodInfo.ToString()}");
                        }
                        propertySetMethod = methodDescription;
                        if ((propertySetMethod.InArguments?.Count != 2 || propertySetMethod.InArguments[0].Type != s_stringType || propertySetMethod.InArguments[1].Type != s_objectType) ||
                            (propertySetMethod.OutArguments.Count != 0))
                        {
                            throw new ArgumentException($"Property Set method {memberName} must accept a 'string' and 'object' parameter and return 'Task'");
                        }
                    }
                    else
                    {
                        methods = methods ?? new List <MethodDescription>();
                        methods.Add(methodDescription);
                    }
                }
            }
            if (propertyType != null)
            {
                var fields = propertyType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                foreach (var field in fields)
                {
                    string propertyName;
                    Type   fieldType;
                    PropertyTypeInspector.InspectField(field, out propertyName, out fieldType);
                    var propertySignature = Signature.GetSig(fieldType, isCompileTimeType: true);
                    var propertyAccess    = field.GetCustomAttribute <PropertyAttribute>()?.Access ?? PropertyAccess.ReadWrite;
                    var description       = new PropertyDescription(propertyName, propertySignature, propertyAccess);
                    properties = properties ?? new List <PropertyDescription>();
                    properties.Add(description);
                }
            }
            interfaces.Add(new InterfaceDescription(type, interfaceAttribute.Name, methods, signals, properties,
                                                    propertyGetMethod, propertyGetAllMethod, propertySetMethod, propertiesChangedSignal));
        }
Ejemplo n.º 4
0
        private MethodInfo GenSendSignal(SignalDescription signalDescription, bool isPropertiesChangedSignal)
        {
            var key    = $"{signalDescription.Interface.Name}.{signalDescription.Name}";
            var method = _typeBuilder.DefineMethod($"Emit{key}".Replace('.', '_'), MethodAttributes.Private, null,
                                                   signalDescription.SignalType == null ? Type.EmptyTypes : new[] { signalDescription.SignalType });

            var ilg = method.GetILGenerator();

            ilg.Emit(OpCodes.Ldarg_0);
            if (isPropertiesChangedSignal)
            {
                ilg.Emit(OpCodes.Ldstr, "org.freedesktop.DBus.Properties");
                ilg.Emit(OpCodes.Ldstr, "PropertiesChanged");
            }
            else
            {
                ilg.Emit(OpCodes.Ldstr, signalDescription.Interface.Name);
                ilg.Emit(OpCodes.Ldstr, signalDescription.Name);
            }

            if (signalDescription.SignalType == null)
            {
                ilg.Emit(OpCodes.Call, s_emitVoidSignal);
            }
            else
            {
                // Signature
                if (isPropertiesChangedSignal)
                {
                    ilg.Emit(OpCodes.Ldstr, "sa{sv}as");
                    ilg.Emit(OpCodes.Newobj, s_signatureConstructor);
                    ilg.Emit(OpCodes.Newobj, s_nullableSignatureConstructor);
                }
                else if (signalDescription.SignalSignature.HasValue)
                {
                    ilg.Emit(OpCodes.Ldstr, signalDescription.SignalSignature.Value.Value);
                    ilg.Emit(OpCodes.Newobj, s_signatureConstructor);
                    ilg.Emit(OpCodes.Newobj, s_nullableSignatureConstructor);
                }
                else
                {
                    LocalBuilder signature = ilg.DeclareLocal(s_nullableSignatureType);
                    ilg.Emit(OpCodes.Ldloca_S, signature);
                    ilg.Emit(OpCodes.Initobj, s_nullableSignatureType);
                    ilg.Emit(OpCodes.Ldloc, signature);
                }

                // Writer
                ilg.Emit(OpCodes.Newobj, s_messageWriterConstructor);

                if (isPropertiesChangedSignal)
                {
                    ilg.Emit(OpCodes.Dup);
                    ilg.Emit(OpCodes.Ldstr, signalDescription.Interface.Name);
                    ilg.Emit(OpCodes.Call, s_writerWriteString);
                    ilg.Emit(OpCodes.Dup);
                    ilg.Emit(OpCodes.Call, s_writerSetSkipNextStructPadding);
                }
                ilg.Emit(OpCodes.Dup);
                ilg.Emit(OpCodes.Ldarg_1);
                ilg.Emit(OpCodes.Call, WriteMethodFactory.CreateWriteMethodForType(signalDescription.SignalType, isCompileTimeType: true));

                ilg.Emit(OpCodes.Call, s_emitNonVoidSignal);
            }

            ilg.Emit(OpCodes.Ret);

            return(method);
        }