internal static RegisterAttribute ToRegisterAttribute(CustomAttribute attr)
        {
            // attr.Resolve ();
            RegisterAttribute r = null;

            if (attr.ConstructorArguments.Count == 1)
            {
                r = new RegisterAttribute((string)attr.ConstructorArguments [0].Value);
            }
            else if (attr.ConstructorArguments.Count == 3)
            {
                r = new RegisterAttribute(
                    (string)attr.ConstructorArguments [0].Value,
                    (string)attr.ConstructorArguments [1].Value,
                    (string)attr.ConstructorArguments [2].Value);
            }
            if (r != null)
            {
                var v = attr.Properties.FirstOrDefault(p => p.Name == "DoNotGenerateAcw");
                r.DoNotGenerateAcw = v.Name == null ? false : (bool)v.Argument.Value;
            }
            return(r);
        }
        static void ProcessAssemblies(IEnumerable <string> types, IEnumerable <string> skip)
        {
            bool checkTypes = types.Count() > 0;
            var  packages   = new HashSet <string> ();

            foreach (Assembly a in Assemblies)
            {
                foreach (Type t in a.Modules.SelectMany(m => m.Types).SelectMany(t => t.FlattenTypeHierarchy()))
                {
                    if (checkTypes && !types.Contains(t.FlattenFullName()))
                    {
                        continue;
                    }
                    if (skip.Contains(t.FlattenFullName()))
                    {
                        continue;
                    }
                    RegisterAttribute tregister = ImportDocsForType(t);
                    if (tregister == null)
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(t.Namespace))
                    {
                        continue;
                    }
                    string package = GetPackageName(tregister.Name);
                    if (package == null || packages.Contains(package))
                    {
                        continue;
                    }

                    packages.Add(package);
                    ImportDocsForPackage(package, t.Namespace);
                }
            }
        }
Example #3
0
        public ThreadService(ITarget target)
        {
            Target = target;

            target.OnFlushEvent.Register(() => {
                _threads?.Clear();
                _threads = null;
            });

            Type contextType;

            switch (target.Architecture)
            {
            case Architecture.X64:
                // Dumps generated with newer dbgeng have bigger context buffers and clrmd requires the context size to at least be that size.
                _contextSize  = target.OperatingSystem == OSPlatform.Windows ? 0x700 : AMD64Context.Size;
                _contextFlags = AMD64Context.ContextControl | AMD64Context.ContextInteger | AMD64Context.ContextSegments | AMD64Context.ContextFloatingPoint;
                contextType   = typeof(AMD64Context);
                break;

            case Architecture.X86:
                _contextSize  = X86Context.Size;
                _contextFlags = X86Context.ContextControl | X86Context.ContextInteger | X86Context.ContextSegments | X86Context.ContextFloatingPoint;
                contextType   = typeof(X86Context);
                break;

            case Architecture.Arm64:
                _contextSize  = Arm64Context.Size;
                _contextFlags = Arm64Context.ContextControl | Arm64Context.ContextInteger | Arm64Context.ContextFloatingPoint;
                contextType   = typeof(Arm64Context);
                break;

            case Architecture.Arm:
                _contextSize  = ArmContext.Size;
                _contextFlags = ArmContext.ContextControl | ArmContext.ContextInteger | ArmContext.ContextFloatingPoint;
                contextType   = typeof(ArmContext);
                break;

            default:
                throw new PlatformNotSupportedException($"Unsupported architecture: {target.Architecture}");
            }

            var registers = new List <RegisterInfo>();
            int index     = 0;

            FieldInfo[] fields = contextType.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (FieldInfo field in fields)
            {
                RegisterAttribute registerAttribute = field.GetCustomAttributes <RegisterAttribute>(inherit: false).SingleOrDefault();
                if (registerAttribute == null)
                {
                    continue;
                }
                RegisterType registerType = registerAttribute.RegisterType & RegisterType.TypeMask;
                switch (registerType)
                {
                case RegisterType.Control:
                case RegisterType.General:
                case RegisterType.Segments:
                    break;

                default:
                    continue;
                }
                if ((registerAttribute.RegisterType & RegisterType.ProgramCounter) != 0)
                {
                    InstructionPointerIndex = index;
                }
                if ((registerAttribute.RegisterType & RegisterType.StackPointer) != 0)
                {
                    StackPointerIndex = index;
                }
                if ((registerAttribute.RegisterType & RegisterType.FramePointer) != 0)
                {
                    FramePointerIndex = index;
                }
                FieldOffsetAttribute offsetAttribute = field.GetCustomAttributes <FieldOffsetAttribute>(inherit: false).Single();
                var registerInfo = new RegisterInfo(index, offsetAttribute.Value, Marshal.SizeOf(field.FieldType), registerAttribute.Name ?? field.Name.ToLower());
                registers.Add(registerInfo);
                index++;
            }

            _lookupByName  = registers.ToDictionary((info) => info.RegisterName);
            _lookupByIndex = registers.ToDictionary((info) => info.RegisterIndex);
            Registers      = registers;
        }
Example #4
0
 public Signature(MethodDefinition method, RegisterAttribute register, string managedParameters, string outerType)
     : this(register.Name, register.Signature, register.Connector, managedParameters, outerType, null)
 {
     Annotations = JavaCallableWrapperGenerator.GetAnnotationsString("\t", method.CustomAttributes);
 }
Example #5
0
 public Signature(MethodDefinition method, RegisterAttribute register) : this(method, register, null, null)
 {
 }
Example #6
0
        void AddConstructor(MethodDefinition ctor, TypeDefinition type, string outerType, List <MethodDefinition> baseCtors, List <MethodDefinition> curCtors, bool onlyRegisteredOrExportedCtors, bool skipParameterCheck)
        {
            string managedParameters = GetManagedParameters(ctor, outerType);

            if (!skipParameterCheck && (managedParameters == null || ctors.Any(c => c.ManagedParameters == managedParameters)))
            {
                return;
            }

            ExportAttribute eattr = GetExportAttributes(ctor).FirstOrDefault();

            if (eattr != null)
            {
                if (!string.IsNullOrEmpty(eattr.Name))
                {
                    // Diagnostic.Warning (log, "Use of ExportAttribute.Name property is invalid on constructors");
                }
                ctors.Add(new Signature(ctor, eattr));
                curCtors.Add(ctor);
                return;
            }

            RegisterAttribute rattr = GetRegisterAttributes(ctor).FirstOrDefault();

            if (rattr != null)
            {
                if (ctors.Any(c => c.JniSignature == rattr.Signature))
                {
                    return;
                }
                ctors.Add(new Signature(ctor, rattr, managedParameters, outerType));
                curCtors.Add(ctor);
                return;
            }

            if (onlyRegisteredOrExportedCtors)
            {
                return;
            }

            string jniSignature = GetJniSignature(ctor);

            if (jniSignature == null)
            {
                return;
            }

            if (ctors.Any(c => c.JniSignature == jniSignature))
            {
                return;
            }

            if (baseCtors.Any(m => m.Parameters.AreParametersCompatibleWith(ctor.Parameters)))
            {
                ctors.Add(new Signature(".ctor", jniSignature, "", managedParameters, outerType, null));
                curCtors.Add(ctor);
                return;
            }
            if (baseCtors.Any(m => !m.HasParameters))
            {
                ctors.Add(new Signature(".ctor", jniSignature, "", managedParameters, outerType, ""));
                curCtors.Add(ctor);
                return;
            }
        }
Example #7
0
        JavaCallableWrapperGenerator(TypeDefinition type, string outerType, Action <string, object[]> log)
        {
            this.type = type;
            this.log  = log;

            if (type.IsEnum || type.IsInterface || type.IsValueType)
            {
                Diagnostic.Error(4200, LookupSource(type), "Can only generate Java wrappers for 'class' types, not type '{0}'.", type.FullName);
            }

            string jniName = JniType.ToJniName(type);

            if (jniName == null)
            {
                Diagnostic.Error(4201, LookupSource(type), "Unable to determine Java name for type {0}", type.FullName);
            }
            if (!string.IsNullOrEmpty(outerType))
            {
                string p;
                jniName = jniName.Substring(outerType.Length + 1);
                ExtractJavaNames(outerType, out p, out outerType);
            }
            ExtractJavaNames(jniName, out package, out name);
            if (string.IsNullOrEmpty(package) &&
                (type.IsSubclassOf("Android.App.Activity") ||
                 type.IsSubclassOf("Android.App.Application") ||
                 type.IsSubclassOf("Android.App.Service") ||
                 type.IsSubclassOf("Android.Content.BroadcastReceiver") ||
                 type.IsSubclassOf("Android.Content.ContentProvider")))
            {
                Diagnostic.Error(4203, LookupSource(type), "The Name property must be a fully qualified 'package.TypeName' value, and no package was found for '{0}'.", jniName);
            }

            foreach (MethodDefinition minfo in type.Methods.Where(m => !m.IsConstructor))
            {
                var baseMethods         = GetBaseMethods(minfo);
                var baseRegiteredMethod = baseMethods.FirstOrDefault(m => GetRegisterAttributes(m).Any());
                if (baseRegiteredMethod != null)
                {
                    AddMethod(baseRegiteredMethod, minfo);
                }
                else if (GetExportFieldAttributes(minfo).Any())
                {
                    AddMethod(null, minfo);
                    HasExport = true;
                }
                else if (GetExportAttributes(minfo).Any())
                {
                    AddMethod(null, minfo);
                    HasExport = true;
                }
            }

            foreach (MethodDefinition imethod in type.Interfaces.Cast <TypeReference> ()
                     .Select(r => {
                var d = r.Resolve();
                if (d == null)
                {
                    Diagnostic.Error(4204,
                                     LookupSource(type),
                                     "Unable to resolve interface type '{0}'. Are you missing an assembly reference?",
                                     r.FullName);
                }
                return(d);
            })
                     .Where(d => GetRegisterAttributes(d).Any())
                     .SelectMany(d => d.Methods.Cast <MethodDefinition>()))
            {
                AddMethod(imethod, imethod);
            }

            var ctorTypes = new List <TypeDefinition> ()
            {
                type,
            };

            foreach (var bt in type.GetBaseTypes())
            {
                ctorTypes.Add(bt);
                RegisterAttribute rattr = GetRegisterAttributes(bt).FirstOrDefault();
                if (rattr != null && rattr.DoNotGenerateAcw)
                {
                    break;
                }
            }
            ctorTypes.Reverse();

            var curCtors = new List <MethodDefinition> ();

            foreach (MethodDefinition minfo in type.Methods.Where(m => m.IsConstructor))
            {
                if (GetExportAttributes(minfo).Any())
                {
                    if (minfo.IsStatic)
                    {
                        // Diagnostic.Warning (log, "ExportAttribute does not work on static constructor");
                    }
                    else
                    {
                        AddConstructor(minfo, ctorTypes [0], outerType, null, curCtors, false, true);
                        HasExport = true;
                    }
                }
            }

            AddConstructors(ctorTypes [0], outerType, null, curCtors, true);

            for (int i = 1; i < ctorTypes.Count; ++i)
            {
                var baseCtors = curCtors;
                curCtors = new List <MethodDefinition> ();
                AddConstructors(ctorTypes [i], outerType, baseCtors, curCtors, false);
            }
        }
 public abstract DocumentSection CreateSection(XElement sectionAnchor, string anchor, RegisterAttribute mregister);
Example #9
0
        unsafe IntPtr Register(Type type, string name, bool is_wrapper)
        {
            IntPtr parent = IntPtr.Zero;
            IntPtr handle = IntPtr.Zero;

            lock (lock_obj) {
                handle = Class.objc_getClass(name);

                if (handle != IntPtr.Zero)
                {
                    if (!type_map.ContainsKey(handle))
                    {
                        type_map [handle] = type;
                    }
                    return(handle);
                }

                /*FIXME pick a more suitable exception type */
                /*FIXME try to guess the name of the missing library - quite trivial for monotouch.dll*/
                if (is_wrapper)
                {
                    if (Runtime.Arch == Arch.DEVICE)
                    {
                        // types decorated with [Model] attribute are not registered (see registrar.cs and regression from #769)
                        // a missing [Model] attribute will cause this error on devices (e.g. bug #4864)
                        if (!Attribute.IsDefined(type, typeof(ModelAttribute), false))
                        {
                            throw new Exception(string.Format("Wrapper type '{0}' is missing its native ObjectiveC class '{1}'.", type.FullName, name));
                        }
                    }
                    else
                    {
                        /*On simulator this is a common issue since we eagerly register all types. This is an issue with unlinked
                         * monotouch.dll since we don't link all frameworks most of the time.
                         */
                        return(IntPtr.Zero);
                    }
                }

                Dictionary <IntPtr, MethodDescription> methods = new Dictionary <IntPtr, MethodDescription> (Runtime.IntPtrEqualityComparer);

                Type   parent_type = type.BaseType;
                string parent_name = null;
                while (Attribute.IsDefined(parent_type, typeof(ModelAttribute), false))
                {
                    parent_type = parent_type.BaseType;
                }
                RegisterAttribute parent_attr = (RegisterAttribute)Attribute.GetCustomAttribute(parent_type, typeof(RegisterAttribute), false);
                parent_name = parent_attr == null ? parent_type.FullName : parent_attr.Name ?? parent_type.FullName;
                parent      = Class.objc_getClass(parent_name);
                if (parent == IntPtr.Zero && parent_type.Assembly != NSObject.PlatformAssembly)
                {
                    bool parent_is_wrapper = parent_attr == null ? false : parent_attr.IsWrapper;
                    // Its possible as we scan that we might be derived from a type that isn't reigstered yet.
                    Register(parent_type, parent_name, parent_is_wrapper);
                    parent = Class.objc_getClass(parent_name);
                }
                if (parent == IntPtr.Zero)
                {
                    // This spams mtouch, we need a way to differentiate from mtouch's (ab)use
                    // Console.WriteLine ("CRITICAL WARNING: Falling back to NSObject for type {0} reported as {1}", type, parent_type);
                    parent = Class.objc_getClass("NSObject");
                }
                handle = Class.objc_allocateClassPair(parent, name, IntPtr.Zero);

                Class.class_addIvar(handle, "__monoObjectGCHandle", (IntPtr)Marshal.SizeOf(typeof(Int32)), (byte)4, "i");

                foreach (PropertyInfo prop in type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
                {
                    ConnectAttribute cattr = (ConnectAttribute)Attribute.GetCustomAttribute(prop, typeof(ConnectAttribute));
                    if (cattr != null)
                    {
                        string ivar_name = cattr.Name ?? prop.Name;
                        Class.class_addIvar(handle, ivar_name, (IntPtr)Marshal.SizeOf(typeof(IntPtr)), (byte)Math.Log(Marshal.SizeOf(typeof(IntPtr)), 2), "@");
                    }

                    var exportAtt = (ExportAttribute)Attribute.GetCustomAttribute(prop, typeof(ExportAttribute));
                    if (exportAtt != null)
                    {
                        var m = prop.GetGetMethod(true);
                        if (m != null)
                        {
                            var ea = exportAtt.ToGetter(prop);
                            RegisterMethod(m, ea, type, handle, false);
                            var sel = Selector.GetHandle(ea.Selector);
                            methods [sel] = new MethodDescription(m, ea.ArgumentSemantic);
                        }
                        m = prop.GetSetMethod(true);
                        if (m != null)
                        {
                            var ea = exportAtt.ToSetter(prop);
                            RegisterMethod(m, ea, type, handle, false);
                            var sel = Selector.GetHandle(ea.Selector);
                            methods [sel] = new MethodDescription(m, ea.ArgumentSemantic);
                        }

                        // http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
                        int count = 0;
                        var props = new Class.objc_attribute_prop [3];
                        props [count++] = new Class.objc_attribute_prop {
                            name = "T", value = TypeConverter.ToNative(prop.PropertyType)
                        };
                        switch (exportAtt.ArgumentSemantic)
                        {
                        case ArgumentSemantic.Copy:
                            props [count++] = new Class.objc_attribute_prop {
                                name = "C", value = ""
                            };
                            break;

                        case ArgumentSemantic.Retain:
                            props [count++] = new Class.objc_attribute_prop {
                                name = "&", value = ""
                            };
                            break;
                        }
                        props [count++] = new Class.objc_attribute_prop {
                            name = "V", value = exportAtt.Selector
                        };

                        Class.class_addProperty(handle, exportAtt.Selector, props, count);

#if DEBUG_REGISTER
                        Console.WriteLine("[PROPERTY] Registering {0} of type {2} ({3}) on {1}", exportAtt.Selector, type, prop.PropertyType, TypeConverter.ToNative(prop.PropertyType));
#endif
                    }
                }

                Class.class_addMethod(handle, Selector.GetHandle(Selector.Release), Method.ReleaseTrampoline, "v@:");
                Class.class_addMethod(handle, Selector.GetHandle(Selector.Retain), Method.RetainTrampoline, "@@:");
                Class.class_addMethod(handle, Selector.GetHandle("xamarinGetGCHandle"), Method.GetGCHandleTrampoline, "i@:");
                Class.class_addMethod(handle, Selector.GetHandle("xamarinSetGCHandle:"), Method.SetGCHandleTrampoline, "v@:i");

                var method_interface_map = SharedDynamic.PrepareInterfaceMethodMapping(type);
                foreach (MethodInfo minfo in type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
                {
                    ExportAttribute ea = (ExportAttribute)Attribute.GetCustomAttribute(minfo.GetBaseDefinition(), typeof(ExportAttribute));

                    if (ea == null)
                    {
                        ea = GetMappedExportAttribute(method_interface_map, minfo);
                    }

                    if (ea == null)
                    {
                        continue;
                    }

                    if (minfo.IsGenericMethod || minfo.IsGenericMethodDefinition)
                    {
                        Console.WriteLine("The registrar found an exported generic method: '{0}.{1}'. Exporting generic methods is not supported.", minfo.DeclaringType.FullName, minfo.Name);
                        continue;
                    }

                    bool is_conforms_to_protocol;
                    bool is_model = false;

                    is_conforms_to_protocol = minfo.DeclaringType.Assembly == NSObject.PlatformAssembly && minfo.DeclaringType.Name == "NSObject" && minfo.Name == "ConformsToProtocol";

                    if (!is_conforms_to_protocol)
                    {
                        is_model = minfo.IsVirtual && ((minfo.DeclaringType != type && minfo.DeclaringType.Assembly == NSObject.PlatformAssembly) || (Attribute.IsDefined(minfo.DeclaringType, typeof(ModelAttribute), false)));
                    }

                    if (is_model)
                    {
                        continue;
                    }

                    RegisterMethod(minfo, ea, type, handle, false);

                    var sel = Selector.GetHandle(ea.Selector ?? minfo.Name);

                    methods [sel] = new MethodDescription(minfo, ea.ArgumentSemantic);
                }

                bool default_ctor_found = false;
                foreach (ConstructorInfo cinfo in type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static))
                {
                    if (!default_ctor_found && !cinfo.IsStatic && cinfo.GetParameters().Length == 0)
                    {
#if DEBUG_REGISTER
                        Console.WriteLine("[CTOR] Registering {0}[0x{1:x}|{2}] on {3} -> ({4})", "init", (int)Selector.Init, Method.Signature(cinfo), type, cinfo);
#endif
                        default_ctor_found = true;
                        Class.class_addMethod(handle, Selector.GetHandle("init"), Method.ConstructorTrampoline, Method.Signature(cinfo));
                        methods [Selector.GetHandle("init")] = new MethodDescription(cinfo, ArgumentSemantic.Assign);
                    }

                    ExportAttribute ea = (ExportAttribute)Attribute.GetCustomAttribute(cinfo, typeof(ExportAttribute));
                    if (ea == null)
                    {
                        continue;
                    }

                    IntPtr sel = Selector.GetHandle(ea.Selector);

                    Class.class_addMethod(handle, sel, Method.ConstructorTrampoline, Method.Signature(cinfo));
#if DEBUG_REGISTER
                    Console.WriteLine("[CTOR] Registering {0}[0x{1:x}|{2}] on {3} -> ({4})", ea.Selector, (int)sel, Method.Signature(cinfo), type, cinfo);
#endif
                    methods [sel] = new MethodDescription(cinfo, ea.ArgumentSemantic);
                }

                Class.objc_registerClassPair(handle);

                type_map [handle] = type;
                method_map [type] = methods;
                AddCustomType(type);

                return(handle);
            }
        }
        public override DocumentSection CreateSection(XElement sectionAnchor, string anchor, RegisterAttribute mregister)
        {
            if (hrefs == null)
            {
                hrefs = this.Element.Descendants(name_a).Where(IsNamedAnchor)
                        .Select(a => Tuple.Create(TypeUtilities.StripGenericArgument(a.Attribute(name_href).Value), a))
                        .ToList();
            }
            var section = sectionAnchor.ElementsAfterSelf("div").First(d => d.Elements().Any(p => Application.HasHtmlClass(p, "api-signature")));
            var summary = hrefs.FirstOrDefault(p => p.Item1 == '#' + anchor)?.Item2?.Parent?.Parent ??
                          // sometimes DroidDoc hrefs have generic arguments within their links, which is annoying...
                          this.Element.Descendants(name_a).FirstOrDefault(a => IsNamedAnchor(a) && (a.Attribute(name_href)?.Value.EndsWith('#' + anchor, StringComparison.Ordinal) ?? false))?.Parent?.Parent;

            if (summary == null)
            {
                return(null);
            }
            return(new DroidDoc2DocumentSection(section, summary)
            {
                Mdoc = Mdoc, Anchor = anchor, RegisterAttribute = mregister
            });
        }
        public override DocumentSection CreateSection(XElement sectionAnchor, string anchor, RegisterAttribute mregister)
        {
            var section      = sectionAnchor.ElementsAfterSelf("div").First(d => Application.HasHtmlClass(d, "jd-details"));
            var jdSummaryDiv = section.Descendants("div").First(d => Application.HasHtmlClass(d, "jd-tagdescr"));

            return(new DroidDocDocumentSection(section, jdSummaryDiv)
            {
                Mdoc = Mdoc, Anchor = anchor, RegisterAttribute = mregister
            });
        }
        static IEnumerable <XElement> GetMdocMembers(XElement mdoc, MemberInfo member, RegisterAttribute register, out PropertyInfo property)
        {
            MethodInfo method = member as MethodInfo;

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

            return
                (from m in mdoc.XPathSelectElements("Members/Member")
                 where m.Elements("Attributes")
                 .Elements("Attribute")
                 .Elements("AttributeName")
                 // now n.Value may have ", ApiSince=xx" suffix, which requires partial matching...
                 .Any(n => string.CompareOrdinal(n.Value, 0, attribute, 0, attribute.Length - 1) == 0)
                 select m);
        }
Example #13
0
        JavaCallableWrapperGenerator(TypeDefinition type, string outerType, Action <string, object[]> log, IMetadataResolver resolver)
        {
            this.type  = type;
            this.log   = log;
            this.cache = resolver ?? new TypeDefinitionCache();

            if (type.IsEnum || type.IsInterface || type.IsValueType)
            {
                Diagnostic.Error(4200, LookupSource(type), Localization.Resources.JavaCallableWrappers_XA4200, type.FullName);
            }

            string jniName = JavaNativeTypeManager.ToJniName(type);

            if (jniName == null)
            {
                Diagnostic.Error(4201, LookupSource(type), Localization.Resources.JavaCallableWrappers_XA4201, type.FullName);
            }
            if (!string.IsNullOrEmpty(outerType))
            {
                string p;
                jniName = jniName.Substring(outerType.Length + 1);
                ExtractJavaNames(outerType, out p, out outerType);
            }
            ExtractJavaNames(jniName, out package, out name);
            if (string.IsNullOrEmpty(package) &&
                (type.IsSubclassOf("Android.App.Activity", cache) ||
                 type.IsSubclassOf("Android.App.Application", cache) ||
                 type.IsSubclassOf("Android.App.Service", cache) ||
                 type.IsSubclassOf("Android.Content.BroadcastReceiver", cache) ||
                 type.IsSubclassOf("Android.Content.ContentProvider", cache)))
            {
                Diagnostic.Error(4203, LookupSource(type), Localization.Resources.JavaCallableWrappers_XA4203, jniName);
            }

            foreach (MethodDefinition minfo in type.Methods.Where(m => !m.IsConstructor))
            {
                var baseRegisteredMethod = GetBaseRegisteredMethod(minfo);
                if (baseRegisteredMethod != null)
                {
                    AddMethod(baseRegisteredMethod, minfo);
                }
                else if (GetExportFieldAttributes(minfo).Any())
                {
                    AddMethod(null, minfo);
                    HasExport = true;
                }
                else if (GetExportAttributes(minfo).Any())
                {
                    AddMethod(null, minfo);
                    HasExport = true;
                }
            }

            foreach (MethodDefinition imethod in type.Interfaces.Select(ifaceInfo => ifaceInfo.InterfaceType)
                     .Select(r => {
                var d = r.Resolve();
                if (d == null)
                {
                    Diagnostic.Error(4204,
                                     LookupSource(type),
                                     Localization.Resources.JavaCallableWrappers_XA4204,
                                     r.FullName);
                }
                return(d);
            })
                     .Where(d => GetRegisterAttributes(d).Any())
                     .SelectMany(d => d.Methods)
                     .Where(m => !m.IsStatic))
            {
                AddMethod(imethod, imethod);
            }

            var ctorTypes = new List <TypeDefinition> ()
            {
                type,
            };

            foreach (var bt in type.GetBaseTypes(cache))
            {
                ctorTypes.Add(bt);
                RegisterAttribute rattr = GetRegisterAttributes(bt).FirstOrDefault();
                if (rattr != null && rattr.DoNotGenerateAcw)
                {
                    break;
                }
            }
            ctorTypes.Reverse();

            var curCtors = new List <MethodDefinition> ();

            foreach (MethodDefinition minfo in type.Methods.Where(m => m.IsConstructor))
            {
                if (GetExportAttributes(minfo).Any())
                {
                    if (minfo.IsStatic)
                    {
                        // Diagnostic.Warning (log, "ExportAttribute does not work on static constructor");
                    }
                    else
                    {
                        AddConstructor(minfo, ctorTypes [0], outerType, null, curCtors, false, true);
                        HasExport = true;
                    }
                }
            }

            AddConstructors(ctorTypes [0], outerType, null, curCtors, true);

            for (int i = 1; i < ctorTypes.Count; ++i)
            {
                var baseCtors = curCtors;
                curCtors = new List <MethodDefinition> ();
                AddConstructors(ctorTypes [i], outerType, baseCtors, curCtors, false);
            }
        }
Example #14
0
        public RegisterService(DataTarget target)
        {
            _target = target;

            Type contextType;

            switch (target.Architecture)
            {
            case Architecture.Amd64:
                _contextSize  = AMD64Context.Size;
                _contextFlags = AMD64Context.ContextControl | AMD64Context.ContextInteger | AMD64Context.ContextSegments;
                contextType   = typeof(AMD64Context);
                break;

            case Architecture.X86:
                _contextSize  = X86Context.Size;
                _contextFlags = X86Context.ContextControl | X86Context.ContextInteger | X86Context.ContextSegments;
                contextType   = typeof(X86Context);
                break;

            case Architecture.Arm64:
                _contextSize  = Arm64Context.Size;
                _contextFlags = Arm64Context.ContextControl | Arm64Context.ContextInteger;
                contextType   = typeof(Arm64Context);
                break;

            case Architecture.Arm:
                _contextSize  = ArmContext.Size;
                _contextFlags = ArmContext.ContextControl | ArmContext.ContextInteger;
                contextType   = typeof(ArmContext);
                break;

            default:
                throw new PlatformNotSupportedException($"Unsupported architecture: {target.Architecture}");
            }

            var registers = new List <RegisterInfo>();
            int index     = 0;

            FieldInfo[] fields = contextType.GetFields(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic);
            foreach (FieldInfo field in fields)
            {
                RegisterAttribute registerAttribute = field.GetCustomAttributes <RegisterAttribute>(inherit: false).SingleOrDefault();
                if (registerAttribute == null)
                {
                    continue;
                }
                RegisterType registerType = registerAttribute.RegisterType & RegisterType.TypeMask;
                switch (registerType)
                {
                case RegisterType.Control:
                case RegisterType.General:
                case RegisterType.Segments:
                    break;

                default:
                    continue;
                }
                if ((registerAttribute.RegisterType & RegisterType.ProgramCounter) != 0)
                {
                    InstructionPointerIndex = index;
                }
                if ((registerAttribute.RegisterType & RegisterType.StackPointer) != 0)
                {
                    StackPointerIndex = index;
                }
                if ((registerAttribute.RegisterType & RegisterType.FramePointer) != 0)
                {
                    FramePointerIndex = index;
                }
                FieldOffsetAttribute offsetAttribute = field.GetCustomAttributes <FieldOffsetAttribute>(inherit: false).Single();
                var registerInfo = new RegisterInfo(index, offsetAttribute.Value, Marshal.SizeOf(field.FieldType), registerAttribute.Name ?? field.Name.ToLower());
                registers.Add(registerInfo);
                index++;
            }

            _lookupByName  = registers.ToDictionary((info) => info.RegisterName);
            _lookupByIndex = registers.ToDictionary((info) => info.RegisterIndex);

            Registers = registers;
        }
        protected override RegisterAttribute GetRegisterAttribute(TypeReference type)
        {
            CustomAttribute attrib;
            RegisterAttribute rv = null;

            if (!SharedStatic.TryGetAttributeImpl (type.Resolve (), Foundation, StringConstants.RegisterAttribute, out attrib))
                return null;

            if (!attrib.HasConstructorArguments) {
                rv = new RegisterAttribute ();
            } else {
                switch (attrib.ConstructorArguments.Count) {
                case 0:
                    rv = new RegisterAttribute ();
                    break;
                case 1:
                    rv = new RegisterAttribute ((string) attrib.ConstructorArguments [0].Value);
                    break;
                case 2:
                    rv = new RegisterAttribute ((string) attrib.ConstructorArguments [0].Value, (bool) attrib.ConstructorArguments [1].Value);
                    break;
                default:
                    throw ErrorHelper.CreateError (4124, "Invalid RegisterAttribute found on '{0}'. Please file a bug report at http://bugzilla.xamarin.com", type.FullName);
                }
            }

            if (attrib.HasProperties) {
                foreach (var prop in attrib.Properties) {
                    switch (prop.Name) {
                    case "IsWrapper":
                        rv.IsWrapper = (bool) prop.Argument.Value;
                        break;
                    case "Name":
                        rv.Name = (string) prop.Argument.Value;
                        break;
                    case "SkipRegistration":
                        rv.SkipRegistration = (bool) prop.Argument.Value;
                        break;
                    default:
                        throw ErrorHelper.CreateError (4124, "Invalid RegisterAttribute property {1} found on '{0}'. Please file a bug report at http://bugzilla.xamarin.com", type.FullName, prop.Name);
                    }
                }
            }

            return rv;
        }
 public override DocumentSection CreateSection(XElement sectionAnchor, string anchor, RegisterAttribute mregister)
 {
     return(new JavaDoc8DocumentSection(sectionAnchor)
     {
         Mdoc = Mdoc, Anchor = anchor, RegisterAttribute = mregister
     });
 }
Example #17
0
		protected string GetExportedTypeName (TType type, RegisterAttribute register_attribute)
		{
			var name = register_attribute != null && register_attribute.Name != null ? register_attribute.Name : GetTypeFullName (type);
			return SanitizeName (name);
		}