Example #1
0
        public static IList <ITypeDefinition> GetNestedTypes(AssemblyDefinition assemblyDefinition, string fullTypeName)
        {
            var loader = new CecilLoader();

            loader.IncludeInternalMembers = true;

            var bridgeAssemblyDefinition = MonoCecilAssemblyHelper.GetBridgeAssemlyDefinition();
            var bridgeAssembly           = loader.LoadAssembly(bridgeAssemblyDefinition);

            IProjectContent project = new CSharpProjectContent();

            project = project.AddAssemblyReferences(bridgeAssembly);

            var compilation = project.CreateCompilation();

            var ctx = new SimpleTypeResolveContext(compilation);

            var unresolvedAssembly = loader.LoadAssembly(assemblyDefinition);
            var assembly           = unresolvedAssembly.Resolve(ctx);

            var parentType = assembly.GetAllTypeDefinitions().FirstOrDefault(x => x.FullName == fullTypeName);

            if (parentType == null)
            {
                return(new List <ITypeDefinition>());
            }

            var nested = parentType.NestedTypes;

            return(nested);
        }
Example #2
0
        internal static List <IAssemblyReference> ToAssemblyReferences(IEnumerable <AssemblyDefinition> references, ILogger logger)
        {
            logger.Info("Assembly definition to references...");

            var list = new List <IAssemblyReference>();

            if (references == null)
            {
                return(list);
            }

            foreach (var reference in references)
            {
                logger.Trace("\tLoading AssemblyDefinition " + (reference != null && reference.Name != null && reference.Name.Name != null ? reference.Name.Name : "") + " ...");

                var loader = new CecilLoader();
                loader.IncludeInternalMembers = true;

                list.Add(loader.LoadAssembly(reference));

                logger.Trace("\tLoading AssemblyDefinition done");
            }

            logger.Info("Assembly definition to references done");

            return(list);
        }
        private static IList <Tuple <IUnresolvedAssembly, IList <string>, Assembly> > LoadReferences(IEnumerable <string> references, IErrorReporter er)
        {
            var loader = new CecilLoader {
                IncludeInternalMembers = true
            };
            var assemblies = references.Select(r => AssemblyDefinition.ReadAssembly(r)).ToList();             // Shouldn't result in errors because mcs would have caught it.

            var indirectReferences = (from a in assemblies
                                      from m in a.Modules
                                      from r in m.AssemblyReferences
                                      select r.Name)
                                     .Distinct();

            var directReferences = from a in assemblies select a.Name.Name;

            var missingReferences = indirectReferences.Except(directReferences).ToList();

            if (missingReferences.Count > 0)
            {
                er.Region = DomRegion.Empty;
                foreach (var r in missingReferences)
                {
                    er.Message(Messages._7996, r);
                }
                return(null);
            }

            return(assemblies.Select(asm => Tuple.Create(loader.LoadAssembly(asm), GetReferencedAssemblyNames(asm), LoadPlugin(asm))).ToList());
        }
Example #4
0
        public AssemblyLoader(AssemblyBrowserWidget widget, string fileName)
        {
            if (widget == null)
            {
                throw new ArgumentNullException(nameof(widget));
            }
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            this.widget = widget;
            FileName    = fileName;
            if (!File.Exists(fileName))
            {
                throw new ArgumentException("File doesn't exist.", nameof(fileName));
            }

            loader = new CecilLoader(true);
            loader.InterningProvider      = new FastNonInterningProvider();
            loader.IncludeInternalMembers = true;
            loader.LazyLoad = true;

            assemblyLoaderTask = Task.Run(() => {
                try {
                    var asm = AssemblyDefinition.ReadAssembly(FileName, new ReaderParameters {
                        AssemblyResolver = this
                    });
                    var loadedAssembley = loader.LoadAssembly(asm);
                    return(Tuple.Create(asm, loadedAssembley));
                } catch (Exception e) {
                    LoggingService.LogError("Error while reading assembly " + FileName, e);
                    return(null);
                }
            }, src.Token);
        }
Example #5
0
        public void ResolveTypeWithUnknownAttributes()
        {
            const String source = "namespace ns\r\n" +
                                  "{\r\n" +
                                  "    public enum EE {v1 = 13, v2 = 666}\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property, AllowMultiple = true)]\r\n" +
                                  "    public class AttrA : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.Method)]\r\n" +
                                  "    public class AttrB : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "        public AttrB(int i, string s, EE e) {}\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "        [AttrA]\r\n" +
                                  "        [AttrB(666, \"iddqd\", EE.v1)]\r\n" +
                                  "        [AttrC]\r\n" +
                                  "        public void M()\r\n" +
                                  "        { }\r\n" +
                                  "    }\r\n" +
                                  "}";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(source);

            syntaxTree.FileName = "example.cs";
            CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem();
            IProjectContent      content = new CSharpProjectContent();

            content = content.AddOrUpdateFiles(unresolvedTypeSystem);
            CecilLoader         loader = new CecilLoader();
            AssemblyDefinition  mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location);
            IUnresolvedAssembly mscorlibAssembly           = loader.LoadAssembly(mscorlibAssemblyDefinition);

            content = content.AddAssemblyReferences(mscorlibAssembly);
            ICompilation        compilation  = content.CreateCompilation();
            CSharpAstResolver   resolver     = new CSharpAstResolver(compilation, syntaxTree);
            MethodDeclaration   method       = syntaxTree.Descendants.OfType <MethodDeclaration>().First(m => m.Name == "M");
            ResolveResult       result       = resolver.Resolve(method);
            MemberResolveResult memberResult = (MemberResolveResult)result;
            IMember             member       = memberResult.Member;

            foreach (IAttribute attribute in member.Attributes)
            {
                Console.WriteLine("attribute.AttributeType = {0}, attribute.AttributeType.Kind = {1}", attribute.AttributeType.FullName, attribute.AttributeType.Kind);
                Console.WriteLine("attribute.PositionalArguments.Count = {0}", attribute.PositionalArguments.Count);
                ProcessPositionalArgs(attribute.PositionalArguments);
                Console.WriteLine("attribute.NamedArguments.Count = {0}", attribute.NamedArguments.Count);
                Console.WriteLine();
            }
        }
Example #6
0
        public DecompilerTypeSystem(ModuleDefinition moduleDefinition)
        {
            if (moduleDefinition == null)
            {
                throw new ArgumentNullException(nameof(moduleDefinition));
            }
            this.moduleDefinition = moduleDefinition;
            CecilLoader cecilLoader = new CecilLoader {
                IncludeInternalMembers = true, LazyLoad = true, OnEntityLoaded = StoreMemberReference, ShortenInterfaceImplNames = false
            };

            typeReferenceCecilLoader.SetCurrentModule(moduleDefinition);
            IUnresolvedAssembly mainAssembly = cecilLoader.LoadModule(moduleDefinition);
            // Load referenced assemblies and type-forwarder references.
            // This is necessary to make .NET Core/PCL binaries work better.
            var referencedAssemblies        = new List <IUnresolvedAssembly>();
            var assemblyReferenceQueue      = new Queue <AssemblyNameReference>(moduleDefinition.AssemblyReferences);
            var processedAssemblyReferences = new HashSet <AssemblyNameReference>(KeyComparer.Create((AssemblyNameReference reference) => reference.FullName));

            while (assemblyReferenceQueue.Count > 0)
            {
                var asmRef = assemblyReferenceQueue.Dequeue();
                if (!processedAssemblyReferences.Add(asmRef))
                {
                    continue;
                }
                var asm = moduleDefinition.AssemblyResolver.Resolve(asmRef);
                if (asm != null)
                {
                    referencedAssemblies.Add(cecilLoader.LoadAssembly(asm));
                    foreach (var forwarder in asm.MainModule.ExportedTypes)
                    {
                        if (!forwarder.IsForwarder || !(forwarder.Scope is AssemblyNameReference forwarderRef))
                        {
                            continue;
                        }
                        assemblyReferenceQueue.Enqueue(forwarderRef);
                    }
                }
            }
            compilation = new SimpleCompilation(mainAssembly, referencedAssemblies);
            // Primitive types are necessary to avoid assertions in ILReader.
            // Fallback to MinimalCorlib to provide the primitive types.
            if (compilation.FindType(KnownTypeCode.Void).Kind == TypeKind.Unknown || compilation.FindType(KnownTypeCode.Int32).Kind == TypeKind.Unknown)
            {
                referencedAssemblies.Add(MinimalCorlib.Instance);
                compilation = new SimpleCompilation(mainAssembly, referencedAssemblies);
            }
            context = new SimpleTypeResolveContext(compilation.MainAssembly);
        }
Example #7
0
        internal static List <IAssemblyReference> ToAssemblyReferences(IEnumerable <AssemblyDefinition> references)
        {
            var list = new List <IAssemblyReference>();

            if (references == null)
            {
                return(list);
            }

            foreach (var reference in references)
            {
                var loader = new CecilLoader();
                loader.IncludeInternalMembers = true;
                list.Add(loader.LoadAssembly(reference));
            }

            return(list);
        }
Example #8
0
        private void TestCommonBody(String source)
        {
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(source);

            syntaxTree.FileName = "example.cs";
            BaseReferenceExpression baseRef = syntaxTree.Descendants.OfType <BaseReferenceExpression>().First();
            ExpressionStatement     expr    = MoveToParent <ExpressionStatement>(baseRef);
            CSharpUnresolvedFile    unresolvedTypeSystem = syntaxTree.ToTypeSystem();
            IProjectContent         content = new CSharpProjectContent();

            content = content.AddOrUpdateFiles(unresolvedTypeSystem);
            CecilLoader         loader = new CecilLoader();
            AssemblyDefinition  mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location);
            IUnresolvedAssembly mscorlibAssembly           = loader.LoadAssembly(mscorlibAssemblyDefinition);

            content = content.AddAssemblyReferences(mscorlibAssembly);
            ICompilation      compilation = content.CreateCompilation();
            CSharpAstResolver resolver    = new CSharpAstResolver(compilation, syntaxTree);

            ShowSubtree(expr, 0, resolver);
        }
Example #9
0
        public void MethodParamsReturnAttributes()
        {
            const String source = "namespace ns\r\n" +
                                  "{\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.Parameter)]\r\n" +
                                  "    public class AttrA : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    [System.AttributeUsage(System.AttributeTargets.ReturnValue)]\r\n" +
                                  "    public class AttrB : System.Attribute\r\n" +
                                  "    {\r\n" +
                                  "    }\r\n" +
                                  "    public class SomeClass\r\n" +
                                  "    {\r\n" +
                                  "        [return: AttrB]\r\n" +
                                  "        public string SomeMethod(int p1, [AttrA]string p2) { return \"iddqd\"; }\r\n" +
                                  "    }\r\n" +
                                  "}";
            CSharpParser parser     = new CSharpParser();
            SyntaxTree   syntaxTree = parser.Parse(source);

            syntaxTree.FileName = "example.cs";
            CSharpUnresolvedFile unresolvedTypeSystem = syntaxTree.ToTypeSystem();
            IProjectContent      content = new CSharpProjectContent();

            content = content.AddOrUpdateFiles(unresolvedTypeSystem);
            CecilLoader         loader = new CecilLoader();
            AssemblyDefinition  mscorlibAssemblyDefinition = AssemblyDefinition.ReadAssembly(typeof(Object).Assembly.Location);
            IUnresolvedAssembly mscorlibAssembly           = loader.LoadAssembly(mscorlibAssemblyDefinition);

            content = content.AddAssemblyReferences(mscorlibAssembly);
            ICompilation        compilation  = content.CreateCompilation();
            CSharpAstResolver   resolver     = new CSharpAstResolver(compilation, syntaxTree);
            MethodDeclaration   method       = syntaxTree.Descendants.OfType <MethodDeclaration>().First(m => m.Name == "SomeMethod");
            ResolveResult       result       = resolver.Resolve(method);
            MemberResolveResult memberResult = (MemberResolveResult)result;
            IMember             member       = memberResult.Member;
        }
Example #10
0
        internal static List <IAssemblyReference> ToAssemblyReferences(IReadOnlyList <AssemblyDefinition> references)
        {
            var stack = new ConcurrentStack <IAssemblyReference>();

            if (references is object)
            {
                using (new Measure(Logger, "Loading assembly definitions", references.Count))
                {
                    Task.WaitAll(references.Select(reference => Task.Run(() =>
                    {
                        Logger.ZLogTrace("\tLoading AssemblyDefinition {0} ...", (reference != null && reference.Name != null && reference.Name.Name != null ? reference.Name.Name : ""));
                        var loader = new CecilLoader()
                        {
                            IncludeInternalMembers = true
                        };
                        stack.Push(loader.LoadAssembly(reference));
                        Logger.ZLogTrace("\tLoading AssemblyDefinition done");
                    })).ToArray());
                }
            }

            return(stack.ToList());
        }
        IList <IUnresolvedAssembly> LoadAssemblies()
        {
            var resolver = new AssemblyResolver();

            foreach (var path in fileNames.Select(f => Path.GetDirectoryName(f)).Distinct(StringComparer.OrdinalIgnoreCase))
            {
                resolver.AddSearchDirectory(path);
            }
            List <AssemblyDefinition> assemblies = new List <AssemblyDefinition>();

            foreach (var file in fileNames.Distinct(StringComparer.OrdinalIgnoreCase))
            {
                assemblies.Add(resolver.LoadAssemblyFile(file));
            }
            foreach (var asm in assemblies.ToArray())
            {
                assemblies.AddRange(asm.Modules.SelectMany(m => m.AssemblyReferences).Select(r => resolver.TryResolve(r)).Where(r => r != null));
            }
            CecilLoader loader = new CecilLoader {
                IncludeInternalMembers = true
            };

            // Emulate the old CecilLoader.GetCecilObject() API:
            loader.OnEntityLoaded = delegate(IUnresolvedEntity entity, MemberReference cecilObj) {
                unresolvedTypeSystemToCecilDict[entity] = cecilObj;
            };
            var loadedAssemblies = new List <IUnresolvedAssembly>();

            foreach (var asm in assemblies.Distinct())
            {
                var loadedAssembly = loader.LoadAssembly(asm);
                loadedAssemblies.Add(loadedAssembly);
                unresolvedTypeSystemToCecilDict[loadedAssembly] = asm;
            }
            return(loadedAssemblies);
        }
Example #12
0
        /// <summary>
        /// Public translation interface.
        /// Translates the given method to HLSL
        /// </summary>
        /// <param name="s">Shader type definition.</param>
        /// <param name="m">A method representing a shader to translate.</param>
        /// <param name="attr">The shader type as attribute (either FragmentShaderAttribute or VertexShaderAttribute</param>
        /// <param name="type">The shader type as ShaderType</param>
        /// <returns>The translated GLSL shader source</returns>
        public FunctionDescription Transform(TypeDefinition s, MethodDefinition m, CustomAttribute attr,
                                             ShaderType type)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s");
            }

            if (m == null)
            {
                throw new ArgumentNullException("m");
            }

            if (attr == null)
            {
                throw new ArgumentNullException("attr");
            }

            var sbase = s.BaseType.Resolve();

            while (sbase.MetadataToken.ToInt32() != typeof(Shader).MetadataToken)
            {
                sbase = sbase.BaseType.Resolve();
            }

            var dctx = new DecompilerContext(s.Module)
            {
                CurrentType       = s,
                CurrentMethod     = m,
                CancellationToken = CancellationToken.None
            };
            var d = AstMethodBodyBuilder.CreateMethodBody(m, dctx);

            //var ctx = new CecilTypeResolveContext(sbase.Module);

            var loader   = new CecilLoader();
            var mscorlib = loader.LoadAssemblyFile(typeof(object).Assembly.Location);
            var slsharp  = loader.LoadAssembly(sbase.Module.Assembly);
            var project  = loader.LoadAssembly(s.Module.Assembly);

            var ctx      = new CompositeTypeResolveContext(new[] { project, slsharp, mscorlib });
            var resolver = new CSharpResolver(ctx, CancellationToken.None)
            {
                UsingScope = new UsingScope(project)
            };

            /*
             * foreach (var v in m.Body.Variables)
             * {
             *  resolver.AddVariable(v.VariableType, null, v.Name)
             * }*/

            //resolver.AddVariable()

            //resolver.LocalVariables = m.Body.Variables;


            // TODO: need a more sane way to get the correct class + member
            var ss = ctx.GetAllTypes().First(c => c.FullName == s.FullName);

            resolver.CurrentTypeDefinition = ss;
            resolver.CurrentMember         = ss.Methods.First(n => SameMethod(m, n, ctx));

            var rv = new ResolveVisitor(resolver, new ParsedFile("memory", resolver.UsingScope), null);

            var glsl = new HlslVisitor(d, attr, rv, dctx);

            _functions.UnionWith(glsl.Functions);

            var entry = (bool)attr.ConstructorArguments.FirstOrDefault().Value;
            var sig   = HlslVisitor.GetSignature(m);

            var code = glsl.Result;
            var desc = new FunctionDescription(Shader.GetMethodName(m), sig + code, entry, type);

            _dependencies.UnionWith(glsl.Dependencies);

            return(desc);
        }