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 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 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);
}
}
///
/// A used to preprocess the closure type declarations for both lambda expressions and local methods
///
private static readonly Regex ClosureTypeDeclarationRegex = new Regex(@"(?<=private sealed class )<\w*>[\w_]+", RegexOptions.Compiled);
///
/// A used to preprocess the entry point declaration for both lambda expressions and local methods
///
private static readonly Regex LambdaMethodDeclarationRegex = new Regex(@"(?:private|internal) void <\w+>[\w_|]+(?=\()", RegexOptions.Compiled);
///
/// 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 MethodDeclarationSyntax rootNode, out SemanticModel semanticModel)
{
lock (Lock)
{
// Get the handle of the containing type method
string assemblyPath = methodInfo.DeclaringType?.Assembly.Location ?? throw new InvalidOperationException();
EntityHandle typeHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.DeclaringType.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);
}
// Decompile the method source and fix the method declaration for local methods converted to lambdas
string
sourceCode = decompiler.DecompileAsString(typeHandle),
typeFixedCode = ClosureTypeDeclarationRegex.Replace(sourceCode, "Shader"),
methodFixedCode = LambdaMethodDeclarationRegex.Replace(typeFixedCode, m => $"// {m.Value}{Environment.NewLine} internal void Main");
// Workaround for some local methods not being decompiled correctly
if (!methodFixedCode.Contains("internal void Main"))
{
EntityHandle methodHandle = MetadataTokenHelpers.TryAsEntityHandle(methodInfo.MetadataToken) ?? throw new InvalidOperationException();
string
methodOnlySourceCode = decompiler.DecompileAsString(methodHandle),
methodOnlyFixedSourceCode = LambdaMethodDeclarationRegex.Replace(methodOnlySourceCode, m => $"// {m.Value}{Environment.NewLine} internal void Main"),
methodOnlyIndentedSourceCode = $" {methodOnlyFixedSourceCode.Replace(Environment.NewLine, $"{Environment.NewLine} ")}";
int lastClosedBracketsIndex = methodFixedCode.LastIndexOf('}');
methodFixedCode = methodFixedCode.Insert(lastClosedBracketsIndex, methodOnlyIndentedSourceCode);
}
// Load the type syntax tree
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(methodFixedCode);
// Get the root node to return
rootNode = syntaxTree.GetRoot().DescendantNodes().OfType().First(node => node.GetLeadingTrivia().ToFullString().Contains(methodInfo.Name));
// Update the incremental compilation and retrieve the syntax tree for the method
_Compilation = _Compilation.AddSyntaxTrees(syntaxTree);
semanticModel = _Compilation.GetSemanticModel(syntaxTree);
}
}
///
/// 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);
}
}
}