From 0a71c0a30bfd299f1fa1a066bec5e517fa4ca24a Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Sun, 11 Aug 2019 22:52:06 +0200 Subject: [PATCH] Method decompilation code refactored and moved --- .../MethodDecompiler.cs | 200 ++++++++++++++++++ .../ShaderGenerator.cs | 133 +----------- 2 files changed, 202 insertions(+), 131 deletions(-) create mode 100644 src/DirectX12GameEngine.Shaders/MethodDecompiler.cs diff --git a/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs b/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs new file mode 100644 index 00000000..031f2e21 --- /dev/null +++ b/src/DirectX12GameEngine.Shaders/MethodDecompiler.cs @@ -0,0 +1,200 @@ +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 ICSharpCode.Decompiler; +using ICSharpCode.Decompiler.CSharp; +using ICSharpCode.Decompiler.Metadata; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; + +namespace DirectX12GameEngine.Shaders +{ + /// + /// A that is able to decompile arbitrary methods + /// + public sealed class MethodDecompiler + { + /// + /// Gets the singleton instance to use + /// + public static MethodDecompiler Instance { get; } = new MethodDecompiler(); + + /// + /// The dummy object used to handle concurrent decompilation requests + /// + private readonly object Lock = new object(); + + /// + /// The mapping of available instances targeting different assemblies + /// + private readonly Dictionary Decompilers = new Dictionary(); + + /// + /// The available instances for the loaded assemblies + /// + private readonly IReadOnlyList PEFiles; + + /// + /// The mapping of and values for the discovered instances + /// + private readonly Dictionary TypeDefinitions = 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(); + } + + // Load and store all the available PEFile instances + PEFiles = assemblyPaths.Select(p => new PEFile(p)).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); + } + } + + /// + /// Decompiles a target method and returns its and info + /// + /// The input to inspect + /// The root node for the syntax tree of the input method + /// The semantic model for the input method + public void GetSyntaxTree(MethodInfo methodInfo, out SyntaxNode rootNode, out SemanticModel semanticModel) + { + lock (Lock) + { + // Get the handle of the input method + GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle); + + // Get or create a decompiler for the target assembly, and decompile the method + if (!Decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler)) + { + decompiler = CreateDecompiler(assemblyPath); + Decompilers.Add(assemblyPath, decompiler); + } + + string sourceCode = decompiler.DecompileAsString(methodHandle); + + // Load the method syntax tree + SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); + rootNode = syntaxTree.GetRoot(); + + // Update the incremental compilation and retrieve the syntax tree for the method + _Compilation = _Compilation.AddSyntaxTrees(syntaxTree); + semanticModel = _Compilation.GetSemanticModel(syntaxTree); + } + } + + /// + /// Loads the assembly path and method handle for the input instance + /// + /// The input to inspect + /// The path of the assembly containing the input method + /// The handle for the input method + private void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle) + { + // Try to get the method handle from the assembly of the declaring type + Type declaringType = methodInfo.DeclaringType ?? throw new InvalidOperationException("Invalid declaring type"); + string path = declaringType.Assembly.Location; + if (!string.IsNullOrEmpty(path)) + { + assemblyPath = path; + methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException(); + } + else + { + // Try to get the PEFile and type definition for the method declaring type + if (!TypeDefinitions.TryGetValue(methodInfo.DeclaringType, out (PEFile PEFile, TypeDefinition TypeDefinition) tuple)) + { + foreach (PEFile peFile in PEFiles) + { + // If not available, browse through the loaded PEFiles to find the type definition + TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName); + + if (!typeDefinitionHandle.IsNil) + { + tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle)); + TypeDefinitions.Add(methodInfo.DeclaringType, tuple); + + break; + } + } + + if (tuple.PEFile is null) throw new InvalidOperationException($"Missing PEFile for declaring type {methodInfo.DeclaringType.FullName}"); + } + + PEFile peFileForMethod = tuple.PEFile; + TypeDefinition typeDefinition = tuple.TypeDefinition; + + // Retrieve the assembly path and method handle from the loaded PEFile and metadata + assemblyPath = peFileForMethod.FileName; + methodHandle = typeDefinition.GetMethods() + .Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name)) + .First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length); + } + } + + /// + /// 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); + } + } +} diff --git a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs index dfd51e1f..08e2dde6 100644 --- a/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs +++ b/src/DirectX12GameEngine.Shaders/ShaderGenerator.cs @@ -4,29 +4,17 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; -using System.Reflection.Metadata; using System.Text.RegularExpressions; using DirectX12GameEngine.Graphics.Buffers.Abstract; using DirectX12GameEngine.Shaders.Mappings; using DirectX12GameEngine.Shaders.Primitives; -using ICSharpCode.Decompiler; -using ICSharpCode.Decompiler.CSharp; -using ICSharpCode.Decompiler.Metadata; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; using SharpDX.Direct3D12; namespace DirectX12GameEngine.Shaders { public class ShaderGenerator { - private static readonly object compilationLock = new object(); - private static readonly Dictionary decompilers = new Dictionary(); - private static readonly IEnumerable peFiles; - private static readonly Dictionary typeDefinitions = new Dictionary(); - - private static Compilation compilation; - private readonly List collectedTypes = new List(); private readonly BindingFlags bindingAttr; private readonly HlslBindingTracker bindingTracker = new HlslBindingTracker(); @@ -36,47 +24,6 @@ namespace DirectX12GameEngine.Shaders private ShaderGenerationResult? result; - static ShaderGenerator() - { - IEnumerable assemblyPaths; - - if (!string.IsNullOrEmpty(Assembly.GetEntryAssembly().Location)) - { - assemblyPaths = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location); - } - else - { - assemblyPaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.dll").Where(p => - { - try - { - PEFile peFile = new PEFile(p); - return true; - } - catch - { - return false; - } - }); - } - - var metadataReferences = assemblyPaths.Select(p => MetadataReference.CreateFromFile(p)); - peFiles = assemblyPaths.Select(p => new PEFile(p)); - - compilation = CSharpCompilation.Create("ShaderAssembly").WithReferences(metadataReferences); - - AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad; - } - - private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs e) - { - if (!e.LoadedAssembly.IsDynamic) - { - PortableExecutableReference metadataReference = MetadataReference.CreateFromFile(e.LoadedAssembly.Location); - compilation = compilation.AddReferences(metadataReference); - } - } - public ShaderGenerator(object shader, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) { this.shader = shader; @@ -358,7 +305,7 @@ namespace DirectX12GameEngine.Shaders private void CollectMethod(MethodInfo methodInfo) { - GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel); ShaderSyntaxCollector syntaxCollector = new ShaderSyntaxCollector(this, semanticModel); syntaxCollector.Visit(root); @@ -377,7 +324,7 @@ namespace DirectX12GameEngine.Shaders private void WriteMethod(MethodInfo methodInfo, int depth = 0) { - GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel); + MethodDecompiler.Instance.GetSyntaxTree(methodInfo, out SyntaxNode root, out SemanticModel semanticModel); ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, true, depth); root = syntaxRewriter.Visit(root); @@ -407,82 +354,6 @@ namespace DirectX12GameEngine.Shaders writer.WriteLine(shaderSource); } - private static void GetSyntaxTree(MethodInfo methodInfo, out SyntaxNode root, out SemanticModel semanticModel) - { - lock (compilationLock) - { - GetMethodHandle(methodInfo, out string assemblyPath, out EntityHandle methodHandle); - - if (!decompilers.TryGetValue(assemblyPath, out CSharpDecompiler decompiler)) - { - decompiler = CreateDecompiler(assemblyPath); - decompilers.Add(assemblyPath, decompiler); - } - - string sourceCode = decompiler.DecompileAsString(methodHandle); - - SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode); - root = syntaxTree.GetRoot(); - - compilation = compilation.AddSyntaxTrees(syntaxTree); - semanticModel = compilation.GetSemanticModel(syntaxTree); - } - } - - private static void GetMethodHandle(MethodInfo methodInfo, out string assemblyPath, out EntityHandle methodHandle) - { - assemblyPath = methodInfo.DeclaringType.Assembly.Location; - - if (!string.IsNullOrEmpty(assemblyPath)) - { - methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException(); - } - else - { - if (!typeDefinitions.TryGetValue(methodInfo.DeclaringType, out var tuple)) - { - foreach (PEFile peFile in peFiles) - { - TypeDefinitionHandle typeDefinitionHandle = peFile.Metadata.TypeDefinitions.FirstOrDefault(t => t.GetFullTypeName(peFile.Metadata).ToString() == methodInfo.DeclaringType.FullName); - - if (!typeDefinitionHandle.IsNil) - { - tuple = (peFile, peFile.Metadata.GetTypeDefinition(typeDefinitionHandle)); - typeDefinitions.Add(methodInfo.DeclaringType, tuple); - - break; - } - } - - if (tuple.PEFile is null) throw new InvalidOperationException(); - } - - PEFile peFileForMethod = tuple.PEFile; - TypeDefinition typeDefinition = tuple.TypeDefinition; - - assemblyPath = peFileForMethod.FileName; - - methodHandle = typeDefinition.GetMethods() - .Where(m => peFileForMethod.Metadata.StringComparer.Equals(peFileForMethod.Metadata.GetMethodDefinition(m).Name, methodInfo.Name)) - .First(m => peFileForMethod.Metadata.GetMethodDefinition(m).GetParameters().Count == methodInfo.GetParameters().Length); - } - } - - private static CSharpDecompiler CreateDecompiler(string assemblyPath) - { - UniversalAssemblyResolver resolver = new UniversalAssemblyResolver(assemblyPath, false, "netstandard"); - - DecompilerSettings decompilerSettings = new DecompilerSettings(ICSharpCode.Decompiler.CSharp.LanguageVersion.Latest) - { - ObjectOrCollectionInitializers = false, - UsingDeclarations = false - }; - - decompilerSettings.CSharpFormattingOptions.IndentationString = IndentedTextWriter.DefaultTabString; - - return new CSharpDecompiler(assemblyPath, resolver, decompilerSettings); - } - private class HlslBindingTracker { public int ConstantBuffer { get; set; }