예제 #1
0
        /// <summary>
        /// Gets the kernel code.
        /// </summary>
        /// <param name="kernalClass">The kernal class.</param>
        /// <returns></returns>
        private string GetKernelCode(Type kernalClass)
        {
            string           assemblyPath = kernalClass.Assembly.Location;
            CSharpDecompiler cSharpDecompiler
                = new CSharpDecompiler(assemblyPath, new Amplifier.Decompiler.DecompilerSettings()
            {
                ThrowOnAssemblyResolveErrors = false, ForEachStatement = false
            });
            StringBuilder   result   = new StringBuilder();
            ITypeDefinition typeInfo = cSharpDecompiler.TypeSystem.MainModule.Compilation.FindType(new FullTypeName(kernalClass.FullName)).GetDefinition();

            List <IMethod> kernelMethods    = new List <IMethod>();
            List <IMethod> nonKernelMethods = new List <IMethod>();

            foreach (var item in typeInfo.Methods)
            {
                if (item.IsConstructor)
                {
                    continue;
                }

                if (item.GetAttributes().FirstOrDefault(x => (x.AttributeType.Name == "OpenCLKernelAttribute")) == null)
                {
                    nonKernelMethods.Add(item);
                    continue;
                }

                kernelMethods.Add(item);

                var k = new KernelFunction()
                {
                    Name = item.Name
                };
                foreach (var p in item.Parameters)
                {
                    k.Parameters.Add(p.Name, p.Type.FullName);
                }

                KernelFunctions.Add(k);
            }

            var kernelHandles    = kernelMethods.ToList().Select(x => (x.MetadataToken)).ToList();
            var nonKernelHandles = nonKernelMethods.ToList().Select(x => (x.MetadataToken)).ToList();

            result.AppendLine(cSharpDecompiler.DecompileAsString(nonKernelHandles));
            result.AppendLine(cSharpDecompiler.DecompileAsString(kernelHandles));

            return(CodeTranslator.Translate(result.ToString()));
        }
예제 #2
0
        public IActionResult GetCode([FromQuery] string address)
        {
            this.logger.LogTrace("(){0}:{1}", nameof(address), address);

            uint160 addressNumeric = new Address(address).ToUint160(this.network);

            byte[] contractCode = this.stateRoot.GetCode(addressNumeric);

            if (contractCode == null || !contractCode.Any())
            {
                return(Json(new GetCodeResponse
                {
                    Message = string.Format("No contract execution code exists at {0}", address)
                }));
            }

            using (var memStream = new MemoryStream(contractCode))
            {
                var modDefinition = ModuleDefinition.ReadModule(memStream);
                var decompiler    = new CSharpDecompiler(modDefinition, new DecompilerSettings {
                });
                // TODO: Update decompiler to display all code, not just this rando FirstOrDefault (given we now allow multiple types)
                string cSharp = decompiler.DecompileAsString(modDefinition.Types.FirstOrDefault(x => x.FullName != "<Module>"));

                this.logger.LogTrace("(-)");

                return(Json(new GetCodeResponse
                {
                    Message = string.Format("Contract execution code retrieved at {0}", address),
                    Bytecode = contractCode.ToHexString(),
                    CSharp = cSharp
                }));
            }
        }
예제 #3
0
        private static string DecompileMethod(string assemblyFileName, MethodDefinition methodDefinition)
        {
            var decompiler = new CSharpDecompiler(assemblyFileName, new DecompilerSettings()
            {
                ThrowOnAssemblyResolveErrors = false
            });
            string result = decompiler.DecompileAsString(methodDefinition);

            return(result);
        }
예제 #4
0
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var decompiler = new CSharpDecompiler(_assemblyDefinition.MainModule, new DecompilerSettings());
            //var name = new FullTypeName(e.Node.Text);

            var str = decompiler.DecompileAsString(e.Node.Tag as IMemberDefinition);

            //var str = decompiler.DecompileTypeAsString(name);

            fastColoredTextBox1.Text = str;
        }
        private static string getMethod(string id, CSharpDecompiler decompiler)
        {
            string[] split  = id.Split("|");
            string   type   = split[0];
            string   method = split[1];

            string[] param = split[2].Split(",");

            try
            {
                return(decompiler.DecompileAsString(decompiler.TypeSystem.MainModule.Compilation.FindType(new FullTypeName(type)).GetDefinition().Methods.Where(x => x.Name.Equals(method) && (!x.Parameters.Any() || (x.Parameters.ToList().Select(y => y.Type.ReflectionName).SequenceEqual(param)))).First().MetadataToken));
            }
            catch (InvalidOperationException)
            {
                return("-1");
            }
        }
예제 #6
0
        /// <summary>
        /// Gets the kernel code.
        /// </summary>
        /// <param name="kernalClass">The kernal class.</param>
        /// <returns></returns>
        private static string GetKernelCode(Type kernalClass)
        {
            string           assemblyPath = kernalClass.Assembly.Location;
            CSharpDecompiler cSharpDecompiler
                = new CSharpDecompiler(assemblyPath, new ICSharpCode.Decompiler.DecompilerSettings()
            {
                ThrowOnAssemblyResolveErrors = false
            });
            StringBuilder   result   = new StringBuilder();
            ITypeDefinition typeInfo = cSharpDecompiler.TypeSystem.MainModule.Compilation.FindType(new FullTypeName(kernalClass.FullName)).GetDefinition();

            List <IMethod> kernelMethods    = new List <IMethod>();
            List <IMethod> nonKernelMethods = new List <IMethod>();

            foreach (var item in typeInfo.Methods)
            {
                if (item.IsConstructor)
                {
                    continue;
                }

                if (item.GetAttributes().FirstOrDefault(x => (x.AttributeType.Name == "OpenCLKernelAttribute")) == null)
                {
                    nonKernelMethods.Add(item);
                    continue;
                }

                kernelMethods.Add(item);
            }

            var kernelHandles    = kernelMethods.ToList().Select(x => (x.MetadataToken)).ToList();
            var nonKernelHandles = nonKernelMethods.ToList().Select(x => (x.MetadataToken)).ToList();

            result.AppendLine("#ifdef cl_khr_fp64");
            result.AppendLine("#pragma OPENCL EXTENSION cl_khr_fp64 : enable");
            result.AppendLine("#endif");
            result.AppendLine(cSharpDecompiler.DecompileAsString(kernelHandles));

            result.AppendLine(cSharpDecompiler.DecompileAsString(nonKernelHandles));

            string resultCode = result.ToString();

            resultCode = resultCode.Replace("using Amplifier.OpenCL;", "")
                         .Replace("using System;", "")
                         .Replace("[OpenCLKernel]", "__kernel")
                         .Replace("public", "")
                         .Replace("[Global]", "global")
                         .Replace("[]", "*")
                         .Replace("@", "v_");

            Regex floatRegEx = new Regex(@"(\d+)(\.\d+)*f]?");
            var   matches    = floatRegEx.Matches(resultCode);

            foreach (Match match in matches)
            {
                resultCode = resultCode.Replace(match.Value, match.Value.Replace("f", ""));
            }

            floatRegEx = new Regex(@"(\d+)(\.\d+)*u]?");
            matches    = floatRegEx.Matches(resultCode);
            foreach (Match match in matches)
            {
                resultCode = resultCode.Replace(match.Value, match.Value.Replace("u", ""));
            }

            return(resultCode);
        }
예제 #7
0
 /// Uses the CSharpDecompiler with the EntityHandle to return a string with a "Method", "Field" or "Type" (which is the whole class).
 public string Decompile(EntityHandle entityHandle)
 {
     return(_decompiler.DecompileAsString(entityHandle));
 }
        private string UnwrapSyntaxTree(string source)
        {
            List <FieldDeclarationSyntax> parsedFields = new List <FieldDeclarationSyntax>();

            // Local function to recursively extract all the nested fields
            void ParseNestedFields(string typeSource)
            {
                // Find the field declarations
                Match match = NestedClosureFieldRegex.Match(typeSource);

                if (!match.Success)
                {
                    return;
                }

                // Load the nested closure type
                string fullname = match.Groups[1].Value.Replace(".<>", "+<>"); // Fullname of a nested type
                Type   type     = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(fullname)).First(t => t != null);

                // Decompile the type and get a readable source code
                EntityHandle     typeHandle = MetadataTokenHelpers.TryAsEntityHandle(type.MetadataToken) ?? throw new InvalidOperationException();
                CSharpDecompiler decompiler = Decompilers[type.Assembly.Location];
                string
                    sourceCode    = decompiler.DecompileAsString(typeHandle),
                    typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Scope");

                // Load the syntax tree and retrieve the list of fields
                SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(typeFixedCode);

                FieldDeclarationSyntax[] fields = syntaxTree.GetRoot().DescendantNodes().OfType <ClassDeclarationSyntax>().First().ChildNodes().OfType <FieldDeclarationSyntax>().ToArray();

                // Add the captured fields
                foreach (FieldDeclarationSyntax field in fields)
                {
                    if (!field.Declaration.Variables.ToFullString().StartsWith("CS$<>"))
                    {
                        parsedFields.Add(field);
                    }
                }

                // Explore the new decompiled type
                ParseNestedFields(typeFixedCode);
            }

            ParseNestedFields(source);

            if (parsedFields.Count > 0)
            {
                // Build the aggregated string with all the captured fields
                StringBuilder builder = new StringBuilder();
                foreach (FieldDeclarationSyntax field in parsedFields)
                {
                    builder.AppendLine(field.ToFullString());
                }
                string fields = builder.ToString().TrimEnd(' ', '\r', '\n');

                // Replace the field declarations
                Match match = NestedClosureFieldRegex.Match(source);
                source = source.Remove(match.Index - 11, match.Length + 12); // leading "    public " and trailing ";"
                source = source.Insert(match.Index - 11, fields);

                // Adjust the method body to remove references to compiler generated fields
                source = CompilerGeneratedFieldRegex.Replace(source, string.Empty);
            }

            return(source);
        }
        private static string GetDecompiledText(ModuleDefinition module, IMemberDefinition member)
        {
            CSharpDecompiler decompiler = GetDecompiler(module);

            return(DecompiledText + decompiler.DecompileAsString(member).Replace("\t", "  "));
        }