Removed code decompiler 🎉

このコミットが含まれているのは:
Sergio Pedri committed 2020-11-25 01:17:39 +01:00
1 親 3a3f301af2
コミット 9a26c5c4bd
6ファイル変更
+31 -391

検索条件に一致するファイルはありません

-1
ファイルの表示
@@ -7,7 +7,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ICSharpCode.Decompiler" Version="5.0.2.5153" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.7.0" />
<PackageReference Include="Stubble.Core" Version="1.9.3" />
</ItemGroup>
+20 -20
ファイルの表示
@@ -3,58 +3,58 @@ using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using ComputeSharp.Shaders.Renderer.Models.Functions;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
#pragma warning disable CS8618
namespace ComputeSharp.Shaders.Renderer.Models
{
/// <summary>
/// A <see langword="class"/> that contains info to render a shader source to compile
/// A <see langword="class"/> that contains info to render a shader source to compile.
/// </summary>
internal sealed class ShaderInfo
{
/// <summary>
/// Gets or sets the list of captured buffers being present in the current shader
/// Gets or sets the list of captured buffers being present in the current shader.
/// </summary>
public IReadOnlyList<HlslBufferInfo> BuffersList { get; set; }
public IReadOnlyList<HlslBufferInfo> BuffersList { get; init; }
/// <summary>
/// Gets or sets the list of captured variables being present in the current shader
/// Gets or sets the list of captured variables being present in the current shader.
/// </summary>
public IReadOnlyList<CapturedFieldInfo> FieldsList { get; set; }
public IReadOnlyList<CapturedFieldInfo> FieldsList { get; init; }
/// <summary>
/// Gets or sets the number of threads in the X group
/// Gets or sets the number of threads in the X group.
/// </summary>
public int NumThreadsX { get; set; }
public int NumThreadsX { get; init; }
/// <summary>
/// Gets or sets the number of threads in the Y group
/// Gets or sets the number of threads in the Y group.
/// </summary>
public int NumThreadsY { get; set; }
public int NumThreadsY { get; init; }
/// <summary>
/// Gets or sets the number of threads in the Z group
/// Gets or sets the number of threads in the Z group.
/// </summary>
public int NumThreadsZ { get; set; }
public int NumThreadsZ { get; init; }
/// <summary>
/// Gets or sets the name for the threads id variable used in the shader
/// Gets or sets the name for the threads id variable used in the shader.
/// </summary>
public string ThreadsIdsVariableName { get; set; }
public string ThreadsIdsVariableName { get; init; }
/// <summary>
/// Gets or sets the shader body to compile
/// Gets or sets the entry point of the shader.
/// </summary>
public string ShaderBody { get; set; }
public string EntryPoint { get; init; }
/// <summary>
/// Gets or sets the list of static functions used by the shader
/// Gets or sets the list of static functions used by the shader.
/// </summary>
public IReadOnlyList<FunctionInfo> FunctionsList { get; set; }
public IReadOnlyList<FunctionInfo> FunctionsList { get; init; }
/// <summary>
/// Gets or sets the list of local (implicit) functions used by the shader
/// Gets or sets the list of local (implicit) functions used by the shader.
/// </summary>
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList { get; set; }
public IReadOnlyList<LocalFunctionInfo> LocalFunctionsList { get; init; }
}
}
+1 -7
ファイルの表示
@@ -50,10 +50,4 @@ cbuffer _{{FieldName}} : register(b{{BufferIndex}})
{{!Shader entry point}}
[NumThreads({{NumThreadsX}}, {{NumThreadsY}}, {{NumThreadsZ}})]
void CSMain(uint3 {{ThreadsIdsVariableName}} : SV_DispatchThreadId)
{
if ({{ThreadsIdsVariableName}}.x < __x &&
{{ThreadsIdsVariableName}}.y < __y &&
{{ThreadsIdsVariableName}}.z < __z)
{{&ShaderBody}}
}
{{&EntryPoint}}
+1 -1
ファイルの表示
@@ -176,7 +176,7 @@ namespace ComputeSharp.Shaders
NumThreadsY = threadsY,
NumThreadsZ = threadsZ,
ThreadsIdsVariableName = shaderLoader.ThreadsIdsVariableName,
ShaderBody = shaderLoader.MethodBody,
EntryPoint = shaderLoader.EntryPoint,
FunctionsList = shaderLoader.FunctionsInfo,
LocalFunctionsList = shaderLoader.LocalFunctionsInfo
});
-258
ファイルの表示
@@ -1,258 +0,0 @@
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;
using Microsoft.Toolkit.Diagnostics;
namespace ComputeSharp.Shaders.Translation
{
/// <summary>
/// A <see langword="class"/> that is able to decompile arbitrary methods
/// </summary>
internal sealed class MethodDecompiler
{
/// <summary>
/// Gets the singleton <see cref="MethodDecompiler"/> instance to use
/// </summary>
public static MethodDecompiler Instance { get; } = new MethodDecompiler();
/// <summary>
/// The mapping of available <see cref="CSharpDecompiler"/> instances targeting different assemblies
/// </summary>
private readonly Dictionary<string, CSharpDecompiler> Decompilers = new Dictionary<string, CSharpDecompiler>();
/// <summary>
/// The incremental <see cref="Compilation"/> instance for the shader assembly
/// </summary>
private Compilation _Compilation;
/// <summary>
/// Creates a new <see cref="MethodDecompiler"/> instance
/// </summary>
private MethodDecompiler()
{
// Load the assembly paths for all the available dlls
IReadOnlyList<string> 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<PortableExecutableReference> 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);
}
}
/// <summary>
/// Creates a new <see cref="CSharpDecompiler"/> instance targeting a given assembly
/// </summary>
/// <param name="assemblyPath">The path of the assembly to decompile</param>
/// <returns>A <see cref="CSharpDecompiler"/> instance that can be used on the targeted assembly</returns>
[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);
}
/// <summary>
/// Decompiles a method or the whole declaring type
/// </summary>
/// <param name="methodInfo">The target <see cref="MethodInfo"/> to decompile</param>
/// <param name="methodOnly">Specifies whether or not to force the decompilation of just the given method, even if not static</param>
/// <returns>The decompiled source code</returns>
[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);
}
/// <summary>
/// Decompiles a target method and returns its <see cref="SyntaxTree"/> and <see cref="SemanticModel"/> info
/// </summary>
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
/// <param name="methodType">The type of method to decompile</param>
/// <param name="rootNode">The root node for the syntax tree of the input method</param>
/// <param name="semanticModel">The semantic model for the input method</param>
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),
_ => ThrowHelper.ThrowArgumentException<string>("Invalid method type")
};
// Load the type syntax tree
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(sourceCode);
// Get the root node to return
rootNode = syntaxTree
.GetRoot()
.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.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);
}
/// <summary>
/// Decompiles a target closure method
/// </summary>
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
[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, @"(?<!\w)in ", string.Empty);
// Tweak the out declarations
string outFixedSourceCode = RefactorInlineOutDeclarations(inFixedSourceCode, methodInfo.Name);
return outFixedSourceCode;
}
/// <summary>
/// Decompiles a target method and returns its <see cref="SyntaxTree"/> and <see cref="SemanticModel"/> info
/// </summary>
/// <param name="methodInfo">The input <see cref="MethodInfo"/> to inspect</param>
[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<MethodDeclarationSyntax>()
.First()
.WithAttributeLists(default)
.ToString(),
prototype = methodWithoutAttributes.Split(Environment.NewLine)[0],
commentedSourceCode = $"// {methodInfo.Name}{Environment.NewLine}{methodWithoutAttributes}",
inFixedSourceCode = Regex.Replace(commentedSourceCode, @"(?<!\w)in ", string.Empty),
outFixedSourceCode = RefactorInlineOutDeclarations(inFixedSourceCode, methodInfo.Name);
// Restore the original prototype, as some out parameters might have been removed
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(outFixedSourceCode);
BlockSyntax block = syntaxTree.GetRoot().DescendantNodes().OfType<BlockSyntax>().First();
return $"// {methodInfo.Name}{Environment.NewLine}{prototype}{Environment.NewLine}{block.ToFullString()}";
}
/// <summary>
/// Refactors all the inline out expressions with a variable declaration
/// </summary>
/// <param name="source">The input source code to process</param>
/// <param name="entryPoint">The name of the shader method being processed</param>
[Pure]
private string RefactorInlineOutDeclarations(string source, string entryPoint)
{
// Replace the discards
source = Regex.Replace(source, @"(?<!\w)out ([\w.]+) _(?!_)", m => $"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<MethodDeclarationSyntax>()
.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<ArgumentSyntax>()
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, @"(?<!\w)out [\w.]+ (?=[\w_]+)", string.Empty); // Inline out declarations
source = Regex.Replace(source, @"(?<!\w)out ", string.Empty); // Leftovers out keywords
return source;
}
}
}
+9 -104
ファイルの表示
@@ -4,22 +4,17 @@ using System.Diagnostics.Contracts;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using ComputeSharp.Graphics.Extensions;
using ComputeSharp.Core.Helpers;
using ComputeSharp.Shaders.Mappings;
using ComputeSharp.Shaders.Renderer.Models.Fields;
using ComputeSharp.Shaders.Renderer.Models.Fields.Abstract;
using ComputeSharp.Shaders.Renderer.Models.Functions;
using ComputeSharp.Shaders.Translation.Enums;
using ComputeSharp.Shaders.Translation.Models;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.Toolkit.Diagnostics;
using TerraFX.Interop;
using static TerraFX.Interop.D3D12_DESCRIPTOR_RANGE_TYPE;
using ParameterInfo = ComputeSharp.Shaders.Renderer.Models.Functions.ParameterInfo;
#pragma warning disable CS8618 // Non-nullable field is uninitialized
#pragma warning disable CS0618, CS8618
namespace ComputeSharp.Shaders.Translation
{
@@ -93,7 +88,7 @@ namespace ComputeSharp.Shaders.Translation
/// <summary>
/// Gets the generated source code for the method in the current shader.
/// </summary>
public string MethodBody { get; private set; }
public string EntryPoint { get; private set; }
/// <summary>
/// Gets the collection of <see cref="HlslBufferInfo"/> items for the shader fields.
@@ -232,7 +227,7 @@ namespace ComputeSharp.Shaders.Translation
HlslKnownTypes.IsKnownVectorType(type)))
{
// Captured static delegates with a return type
LoadStaticMethodSource(shader, fieldName, func.Method);
throw new NotImplementedException();
}
else ThrowHelper.ThrowArgumentException("Invalid captured variable");
}
@@ -243,101 +238,11 @@ namespace ComputeSharp.Shaders.Translation
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
private void LoadMethodSource(object shader)
{
// Decompile the shader method
MethodInfo methodInfo = typeof(T).GetMethod(nameof(IComputeShader.Execute))!;
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Execute, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the shader method (eg. to fix the type declarations)
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, typeof(T));
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Extract the implicit local functions
var locals = root.DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray();
root = root.RemoveNodes(locals, SyntaxRemoveOptions.KeepNoTrivia)!;
foreach (var local in locals)
{
string alignedLocal = local.ToFullString().RemoveLeftPadding().Trim(' ', '\r', '\n');
alignedLocal = Regex.Replace(alignedLocal, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
alignedLocal = HlslKnownKeywords.GetMappedText(alignedLocal);
this.localFunctionsInfo.Add(new LocalFunctionInfo(alignedLocal));
}
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the thread ids identifier name and shader method body
ThreadsIdsVariableName = root.ParameterList.Parameters.First().Identifier.Text;
MethodBody = root.Body!.ToFullString();
// Additional preprocessing
MethodBody = Regex.Replace(MethodBody, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
MethodBody = MethodBody.TrimEnd('\n', '\r', ' ');
MethodBody = HlslKnownKeywords.GetMappedText(MethodBody);
}
/// <summary>
/// Loads additional static methods used by the shader
/// </summary>
/// <param name="shader">The boxed <typeparamref name="T"/> instance to use to build the shader</param>
/// <param name="name">The HLSL name of the new method to load</param>
/// <param name="methodInfo">The <see cref="MethodInfo"/> instance for the method to load</param>
private void LoadStaticMethodSource(object shader, string name, MethodInfo methodInfo)
{
// Decompile the target method
MethodDecompiler.Instance.GetSyntaxTree(methodInfo, MethodType.Static, out MethodDeclarationSyntax root, out SemanticModel semanticModel);
// Rewrite the method
ShaderSyntaxRewriter syntaxRewriter = new ShaderSyntaxRewriter(semanticModel, methodInfo.DeclaringType!);
root = (MethodDeclarationSyntax)syntaxRewriter.Visit(root);
// Register the captured static members
foreach (var member in syntaxRewriter.StaticMembers)
{
LoadFieldInfo(shader, member.Value, member.Key);
}
// Register the captured static methods
foreach (var method in syntaxRewriter.StaticMethods)
{
LoadStaticMethodSource(shader, method.Key, method.Value);
}
// Get the function parameters
IReadOnlyList<ParameterInfo> parameters = (
from parameter in root.ParameterList.Parameters.Select((p, i) => (Node: p, Index: i))
let modifiers = parameter.Node.Modifiers
let type = parameter.Node.Type!.ToFullString()
let parameterName = parameter.Node.Identifier.ToFullString()
let last = parameter.Index == root.ParameterList.Parameters.Count - 1
select new ParameterInfo(modifiers, type, parameterName, last)).ToArray();
// Get the function body
string body = root.Body!.ToFullString();
body = Regex.Replace(body, @"(?<=\W)(\d+)[fFdD]", m => m.Groups[1].Value);
body = body.TrimEnd('\n', '\r', ' ');
body = HlslKnownKeywords.GetMappedText(body);
// Get the final function info instance
FunctionInfo functionInfo = new FunctionInfo(
methodInfo.ReturnType,
$"{methodInfo.DeclaringType!.FullName}{Type.Delimiter}{methodInfo.Name}",
string.Join(", ", methodInfo.GetParameters().Select(p => $"{p.ParameterType.ToFriendlyString()} {p.Name}")),
root.ReturnType.ToString(),
name,
parameters,
body);
this.functionsInfo.Add(functionInfo);
EntryPoint = (
from attribute in typeof(T).Assembly.GetCustomAttributes<IComputeShaderSourceAttribute>()
where attribute.ShaderTypeName == typeof(T).FullName &&
attribute.MethodName == nameof(IComputeShader.Execute)
select attribute.Source).First();
}
}
}