using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Text.RegularExpressions; using ComputeSharp.Shaders.Mappings; using ComputeSharp.Shaders.Translation.Enums; using ICSharpCode.Decompiler; using ICSharpCode.Decompiler.CSharp; using ICSharpCode.Decompiler.Metadata; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace ComputeSharp.Shaders.Translation { /// /// A that is able to decompile arbitrary methods /// internal sealed class MethodDecompiler { /// /// Gets the singleton instance to use /// public static MethodDecompiler Instance { get; } = new MethodDecompiler(); /// /// The mapping of available instances targeting different assemblies /// private readonly Dictionary Decompilers = new Dictionary(); /// /// The incremental instance for the shader assembly /// private Compilation _Compilation; /// /// Creates a new instance /// private MethodDecompiler() { // Load the assembly paths for all the available dlls IReadOnlyList assemblyPaths; if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location)) { assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location).ToArray(); } else { assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p => { try { using PEFile _ = new PEFile(p); return true; } catch { return false; } }).ToArray(); } // Ceate an incremental shader assembly with the available references IEnumerable metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p)); _Compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences); // Monitor for new assemblies being loaded AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad!; } // Increment the shader assembly when a new assembly is loaded private void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e) { if (!e.LoadedAssembly.IsDynamic) { PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location); _Compilation = _Compilation.AddReferences(metadataReference); } } /// /// Creates a new instance targeting a given assembly /// /// The path of the assembly to decompile /// A instance that can be used on the targeted assembly [Pure] private static CSharpDecompiler CreateDecompiler(string assemblyPath) { DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) { ObjectOrCollectionInitializers = false, UsingDeclarations = false, CSharpFormattingOptions = { IndentationString = IndentedTextWriter.DefaultTabString } }; UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); } /// /// Decompiles a method or the whole declaring type /// /// The target to decompile /// Specifies whether or not to force the decompilation of just the given method, even if not static /// The decompiled source code [Pure] private string DecompileMethodOrDeclaringType(MethodInfo methodInfo, bool methodOnly = false) { // Get the handle of the containing type method string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException(); int metadataToken = methodInfo.IsStatic || methodOnly ? methodInfo.MetadataToken : methodInfo.DeclaringType.MetadataToken; EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(metadataToken) ?? throw new InvalidOperationException(); // Get or create a decompiler for the target assembly, and decompile the type if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler? decompiler)) { decompiler = CreateDecompiler(assemblyPath); Decompilers.Add(assemblyPath, decompiler); } return decompiler.DecompileAsString(typeHandle); } /// /// Decompiles a target method and returns its and info /// /// The input to inspect /// The type of method to decompile /// The root node for the syntax tree of the input method /// The semantic model for the input method public void GetSyntaxTree(MethodInfo methodInfo, MethodType methodType, out MethodDeclarationSyntax rootNode, out SemanticModel semanticModel) { string sourceCode = methodType switch { MethodType.Execute => GetSyntaxTreeForExecuteMethod(methodInfo), MethodType.Static => GetSyntaxTreeForStaticMethod(methodInfo), _ => throw new ArgumentOutOfRangeException(nameof(methodType), $"Invalid method type: {methodType}") }; // Load the type syntax tree SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); // Get the root node to return rootNode = syntaxTree .GetRoot() .DescendantNodes() .OfType() .First(node => node.Identifier.ToString().Equals(methodInfo.Name) || node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name)); // Update the incremental compilation and retrieve the syntax tree for the method Compilation compilation = _Compilation.AddSyntaxTrees(syntaxTree); semanticModel = compilation.GetSemanticModel(syntaxTree); } /// /// Decompiles a target closure method /// /// The input to inspect [Pure] private string GetSyntaxTreeForExecuteMethod(MethodInfo methodInfo) { // Decompile the method source string sourceCode = DecompileMethodOrDeclaringType(methodInfo); // Remove the in keyword from the source string inFixedSourceCode = Regex.Replace(sourceCode, @"(? /// Decompiles a target method and returns its and info /// /// The input to inspect [Pure] private string GetSyntaxTreeForStaticMethod(MethodInfo methodInfo) { string sourceCode = DecompileMethodOrDeclaringType(methodInfo, true), methodFixedCode = sourceCode.Replace(methodInfo.Name, Regex.Replace(methodInfo.Name, "[<>|]", "_")), methodWithoutAttributes = CSharpSyntaxTree .ParseText(methodFixedCode) .GetRoot() .DescendantNodes() .OfType() .First() .WithAttributeLists(default) .ToString(), prototype = methodWithoutAttributes.Split(Environment.NewLine)[0], commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodWithoutAttributes}", inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(?().First(); return $"// {methodInfo.Name}{Environment.NewLine}{prototype}{Environment.NewLine}{block.ToFullString()}"; } /// /// Refactors all the inline out expressions with a variable declaration /// /// The input source code to process /// The name of the shader method being processed [Pure] private string RefactorInlineOutDeclarations(string source, string entryPoint) { // Replace the discards source = Regex.Replace(source, @"(? $"out {m.Groups[1].Value} {new string(Guid.NewGuid().ToByteArray().Select(b => (char)('a' + b % 26)).ToArray())}"); // Fix invalid C# names with @ prefix source = Regex.Replace(source, @"@(\w+)", m => $"__at__{m.Groups[1].Value}"); // Load the syntax tree and the entry node SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); MethodDeclarationSyntax rootNode = syntaxTree .GetRoot() .DescendantNodes() .OfType() .First(node => node.Identifier.ToString().Equals(entryPoint) || node.GetLeadingTrivia().ToFullString().Contains(entryPoint)); // Get the out declarations to replace var outs = ( from argument in rootNode.DescendantNodes().OfType() where argument.RefKindKeyword.IsKind(SyntaxKind.OutKeyword) && argument.Expression.IsKind(SyntaxKind.DeclarationExpression) let match = Regex.Match(argument.Expression.ToFullString(), @"([\w.]+) ([\w_]+)") let mappedType = HlslKnownTypes.GetMappedName(match.Groups[1].Value) let declaration = $"{mappedType} {match.Groups[2].Value} = ({mappedType})0;" select declaration).ToArray(); // Insert the explicit declarations at the start of the method int start = rootNode.Body!.ChildNodes().First().SpanStart; foreach (var declaration in outs.Reverse()) { source = source.Insert(start, $"{declaration}{Environment.NewLine} "); } // Remove the out keyword from the source source = Regex.Replace(source, @"(?