public void Decompile(Stream assemblyStream, TextWriter codeWriter) { // ReSharper disable once AgentHeisenbug.CallToNonThreadSafeStaticMethodInThreadSafeType var module = ModuleDefinition.ReadModule(assemblyStream); ((BaseAssemblyResolver)module.AssemblyResolver).ResolveFailure += (_, name) => AssemblyCache.GetOrAdd(name.FullName, fullName => { var assembly = AppDomain.CurrentDomain.GetAssemblies().Single(a => a.FullName == fullName); return(AssemblyDefinition.ReadAssembly(assembly.GetAssemblyFile().FullName)); }); var context = new DecompilerContext(module) { Settings = { CanInlineVariables = false, OperatorOverloading = false, AnonymousMethods = false, YieldReturn = false, AsyncAwait = false, AutomaticProperties = false, ExpressionTrees = false, ArrayInitializers = false, ObjectOrCollectionInitializers = false } }; var ast = new AstBuilder(context); ast.AddAssembly(module.Assembly); WriteResult(codeWriter, ast); }
public override void DecompileAssembly(AssemblyDefinition assembly, string fileName, ITextOutput output, DecompilationOptions options) { /* * if (options.FullDecompilation) * { * //if (options.SaveAsProjectDirectory != null) * //{ * // HashSet<string> directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase); * // var files = WriteCodeFilesInProject(assembly, options, directories).ToList(); * // files.AddRange(WriteResourceFilesInProject(assembly, fileName, options, directories)); * // WriteProjectFile(new TextOutputWriter(output), files, assembly.MainModule); * //} * //else * { * foreach (TypeDefinition type in assembly.MainModule.Types) * { * if (AstBuilder.MemberIsHidden(type, options.DecompilerSettings)) * continue; * AstBuilder codeDomBuilder = CreateAstBuilder(options, type); * codeDomBuilder.AddType(type); * codeDomBuilder.GenerateCode(output, transformAbortCondition); * output.WriteLine(); * } * } * } * else */ { base.DecompileAssembly(assembly, fileName, output, options); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: null); codeDomBuilder.AddAssembly(assembly, onlyAssemblyLevel: true); codeDomBuilder.GenerateCode(output, transformAbortCondition); } }
public void Write(TextWriter writer) { var decompiler = new AstBuilder(new DecompilerContext(assemblyDefinition.MainModule)); decompiler.AddAssembly(assemblyDefinition); var formattingPolicy = FormattingOptionsFactory.CreateMono().Clone(); IAstVisitor [] visitors = { new PublicApiVisitor(), new SortTreeVisitor(), new CSharpOutputVisitor(TokenWriter.Create(writer,indentation: " "), formattingPolicy) }; foreach (var visitor in visitors) { decompiler.SyntaxTree.AcceptVisitor(visitor); } foreach (var tool in visitorTools) { decompiler.SyntaxTree.AcceptVisitor(tool.Visitor); } writer.Flush(); }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { //Checks if must create a solution if (options.CreateSolution) { //Solution directory var solutionDir = options.SaveAsProjectDirectory; //List of the project names and their guid List <Tuple <string, string> > projects = new List <Tuple <string, string> >(); //For each module foreach (var module in assembly.AssemblyDefinition.Modules) { //Creates the project and the various files var projectDir = Path.Combine(solutionDir, TextView.DecompilerTextView.CleanUpName(Path.GetFileNameWithoutExtension(module.Name))); Directory.CreateDirectory(projectDir); options.SaveAsProjectDirectory = projectDir; HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(module, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(module, options, directories)); using (var writer = new StreamWriter(Path.Combine(projectDir, Path.GetFileName(projectDir) + this.ProjectFileExtension), false, System.Text.Encoding.UTF8)) projects.Add(Tuple.Create( Path.GetFileName(projectDir), "{" + WriteProjectFile(writer, files, module, options).ToString().ToUpperInvariant() + "}" )); } //Writes the solution WriteSolutionFile(new TextOutputWriter(output), Enumerable.Reverse(projects)); } else { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = assembly.AssemblyDefinition.Modules.SelectMany(m => WriteCodeFilesInProject(m, options, directories)).ToList(); files.AddRange(assembly.AssemblyDefinition.Modules.SelectMany(m => WriteResourceFilesInProject(m, options, directories))); WriteProjectFile(new TextOutputWriter(output), files, assembly.AssemblyDefinition.MainModule, options); } } else { base.DecompileAssembly(assembly, output, options); output.WriteLine(); output.WriteLine("// Main module:"); ModuleDefinition mainModule = assembly.AssemblyDefinition.MainModule; WriteModuleAttributes(mainModule, output, options); output.WriteLine(); // don't automatically load additional assemblies when an assembly node is selected in the tree view using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.AssemblyDefinition.MainModule); codeDomBuilder.AddAssembly(assembly.AssemblyDefinition, onlyAssemblyLevel: !options.FullDecompilation); codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.GenerateCode(output); } } OnDecompilationFinished(null); }
private static void CompareAssemblyAgainstCSharp(string expectedCSharpCode, string asmFilePath) { var module = Utils.OpenModule(asmFilePath); try { try { module.LoadPdb(); } catch { } AstBuilder decompiler = AstBuilder.CreateAstBuilderTestContext(module); decompiler.AddAssembly(module, false, true, true); new Helpers.RemoveCompilerAttribute().Run(decompiler.SyntaxTree); StringWriter output = new StringWriter(); // the F# assembly contains a namespace `<StartupCode$tmp6D55>` where the part after tmp is randomly generated. // remove this from the ast to simplify the diff var startupCodeNode = decompiler.SyntaxTree.Children.OfType <NamespaceDeclaration>().SingleOrDefault(d => d.Name.StartsWith("<StartupCode$", StringComparison.Ordinal)); if (startupCodeNode != null) { startupCodeNode.Remove(); } decompiler.GenerateCode(new PlainTextOutput(output)); var fullCSharpCode = output.ToString(); CodeAssert.AreEqual(expectedCSharpCode, output.ToString()); } finally { File.Delete(asmFilePath); File.Delete(Path.ChangeExtension(asmFilePath, ".pdb")); } }
public void Decompile(Stream assemblyStream, TextWriter codeWriter) { // ReSharper disable once AgentHeisenbug.CallToNonThreadSafeStaticMethodInThreadSafeType var module = ModuleDefinition.ReadModule(assemblyStream, new ReaderParameters { AssemblyResolver = PreCachedAssemblyResolver.Instance }); var context = new DecompilerContext(module) { Settings = { CanInlineVariables = false, OperatorOverloading = false, AnonymousMethods = false, AnonymousTypes = false, YieldReturn = false, AsyncAwait = false, AutomaticProperties = false, ExpressionTrees = false, ArrayInitializers = false, ObjectOrCollectionInitializers = false, LiftedOperators = false, UsingStatement = false } }; var ast = new AstBuilder(context); ast.AddAssembly(module.Assembly); WriteResult(codeWriter, ast); }
public void Decompile(Stream assemblyStream, TextWriter resultWriter) { // ReSharper disable once AgentHeisenbug.CallToNonThreadSafeStaticMethodInThreadSafeType var module = ModuleDefinition.ReadModule(assemblyStream); ((BaseAssemblyResolver)module.AssemblyResolver).ResolveFailure += (_, name) => AssemblyCache.GetOrAdd(name.FullName, fullName => { var assembly = AppDomain.CurrentDomain.GetAssemblies().Single(a => a.FullName == fullName); return(AssemblyDefinition.ReadAssembly(assembly.GetAssemblyFile().FullName)); }); var context = new DecompilerContext(module) { Settings = { AnonymousMethods = false, YieldReturn = false, AsyncAwait = false, AutomaticProperties = false, ExpressionTrees = false } }; var ast = new AstBuilder(context); ast.AddAssembly(module.Assembly); RunTransforms(ast, context); // I cannot use GenerateCode as it re-runs all the transforms var userCode = GetUserCode(ast); WriteResult(resultWriter, userCode, context); }
public void Decompile(Stream assemblyStream, TextWriter resultWriter) { // ReSharper disable once AgentHeisenbug.CallToNonThreadSafeStaticMethodInThreadSafeType var module = ModuleDefinition.ReadModule(assemblyStream); ((BaseAssemblyResolver)module.AssemblyResolver).AddSearchDirectory( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ); var context = new DecompilerContext(module) { Settings = { AnonymousMethods = false, YieldReturn = false, AsyncAwait = false, AutomaticProperties = false, ExpressionTrees = false } }; var ast = new AstBuilder(context); ast.AddAssembly(module.Assembly); RunTransforms(ast, context); // I cannot use GenerateCode as it re-runs all the transforms var userCode = GetUserCode(ast); WriteResult(resultWriter, userCode, context); }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(assembly.ModuleDefinition, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(assembly, options, directories)); WriteProjectFile(new TextOutputWriter(output), files, assembly.ModuleDefinition); } else { base.DecompileAssembly(assembly, output, options); output.WriteLine(); ModuleDefinition mainModule = assembly.ModuleDefinition; if (mainModule.Types.Count > 0) { output.Write("// Global type: "); output.WriteReference(mainModule.Types[0].FullName, mainModule.Types[0]); output.WriteLine(); } if (mainModule.EntryPoint != null) { output.Write("' Entry point: "); output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint); output.WriteLine(); } WriteCommentLine(output, "Architecture: " + CSharpLanguage.GetPlatformDisplayName(mainModule)); if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) { WriteCommentLine(output, "This assembly contains unmanaged code."); } switch (mainModule.Runtime) { case TargetRuntime.Net_1_0: WriteCommentLine(output, "Runtime: .NET 1.0"); break; case TargetRuntime.Net_1_1: WriteCommentLine(output, "Runtime: .NET 1.1"); break; case TargetRuntime.Net_2_0: WriteCommentLine(output, "Runtime: .NET 2.0"); break; case TargetRuntime.Net_4_0: WriteCommentLine(output, "Runtime: .NET 4.0"); break; } output.WriteLine(); // don't automatically load additional assemblies when an assembly node is selected in the tree view using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition); codeDomBuilder.AddAssembly(assembly.ModuleDefinition, onlyAssemblyLevel: !options.FullDecompilation); RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.ModuleDefinition); } } }
static void RunOnCore() { Console.Write("Dry run..."); DateTime startDryRun = DateTime.UtcNow; { var _para = new ReaderParameters(ReadingMode.Immediate) { AssemblyResolver = new AssemblyResolver(), ReadSymbols = false }; var sys = AssemblyDefinition.ReadAssembly(typeof(TestingLogic).Assembly.Location, _para); var _dc = new DecompilerContext(sys.MainModule); var _astb = new AstBuilder(_dc); _astb.AddAssembly(sys); _astb.RunTransformations(); _astb.GenerateCode(new DummyOutput()); } TimeSpan dryRunTime = DateTime.UtcNow - startDryRun; Console.WriteLine(" O.K. " + dryRunTime.TotalSeconds.ToString("0.000") + " s."); Console.Write("Press Esc to skip large assembly reading"); if (Console.ReadKey().Key != ConsoleKey.Escape) { Console.Write("Reading assembly..."); DateTime startReading = DateTime.UtcNow; var msco = AssemblyDefinition.ReadAssembly(typeof(int).Assembly.Location); TimeSpan readAssemblyTime = DateTime.UtcNow - startReading; Console.WriteLine(" O.K. " + readAssemblyTime.TotalSeconds.ToString("0.000") + " s."); Console.Write("new DecompilerContext(), new AstBuilder()..."); DateTime startNewContext = DateTime.UtcNow; var dc = new DecompilerContext(msco.MainModule); var astb = new AstBuilder(dc); TimeSpan newContextTime = DateTime.UtcNow - startNewContext; Console.WriteLine(" O.K. " + newContextTime.TotalSeconds.ToString("0.000") + " s."); Console.Write("AstBuilder.AddAssembly()..."); DateTime startAddAssembly = DateTime.UtcNow; astb.AddAssembly(msco); TimeSpan decompilerInitTime = DateTime.UtcNow - startAddAssembly; Console.WriteLine(" O.K. " + decompilerInitTime.TotalSeconds.ToString("0.000") + " s."); Console.Write("AstBuilder.RunTransformations()..."); DateTime startTransform = DateTime.UtcNow; astb.RunTransformations(); TimeSpan transformTime = DateTime.UtcNow - startTransform; Console.WriteLine(" O.K. " + transformTime.TotalSeconds.ToString("0.000") + " s."); Console.Write("AstBuilder.GenerateCode()..."); DateTime startGeneration = DateTime.UtcNow; astb.GenerateCode(new DummyOutput()); TimeSpan generationTime = DateTime.UtcNow - startGeneration; Console.WriteLine(" O.K. " + generationTime.TotalSeconds.ToString("0.000") + " s."); Console.Write("Press any key to exit"); Console.ReadKey(); } }
private void DecompileModule(ClrModule module) { var assemblyDef = AssemblyDefinition.ReadAssembly(module.FileName); AstBuilder decompiler = new AstBuilder( new DecompilerContext(assemblyDef.MainModule)); decompiler.AddAssembly(assemblyDef); GenerateCode(decompiler); }
public static string ToCSharp(AssemblyDefinition assemblyDefinition) { var astBuilder = new AstBuilder(new DecompilerContext(assemblyDefinition.MainModule)); astBuilder.AddAssembly(assemblyDefinition); var output = new StringWriter(); astBuilder.GenerateCode(new PlainTextOutput(output)); return(output.ToString()); }
public override void Decompile(ModuleDef mod, ITextOutput output, DecompilationContext ctx) { WriteModule(mod, output, ctx); using (ctx.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(ctx, langSettings.Settings, currentModule: mod); codeDomBuilder.AddAssembly(mod, true, false, true); RunTransformsAndGenerateCode(codeDomBuilder, output, ctx); } }
/// <summary> /// Compiles and decompiles a source code. /// </summary> /// <param name="code">The source code to copile.</param> /// <returns>The decompilation result of compiled source code.</returns> static string RoundtripCode(string code) { AssemblyDefinition assembly = Compile(code); AstBuilder decompiler = new AstBuilder(new DecompilerContext()); decompiler.AddAssembly(assembly); decompiler.Transform(new Helpers.RemoveCompilerAttribute()); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); return(output.ToString()); }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options, DecompileAssemblyFlags flags = DecompileAssemblyFlags.AssemblyAndModule) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(assembly.ModuleDefinition, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(assembly, options, directories)); WriteProjectFile(new TextOutputWriter(output), files, assembly, options); } else { bool decompileAsm = (flags & DecompileAssemblyFlags.Assembly) != 0; bool decompileMod = (flags & DecompileAssemblyFlags.Module) != 0; base.DecompileAssembly(assembly, output, options, flags); output.WriteLine(); ModuleDef mainModule = assembly.ModuleDefinition; if (decompileMod && mainModule.Types.Count > 0) { output.Write("' Global type: ", TextTokenType.Comment); output.WriteReference(IdentifierEscaper.Escape(mainModule.GlobalType.FullName), mainModule.GlobalType, TextTokenType.Comment); output.WriteLine(); } if (decompileMod || decompileAsm) { PrintEntryPoint(assembly, output); } if (decompileMod) { WriteCommentLine(output, "Architecture: " + CSharpLanguage.GetPlatformDisplayName(mainModule)); if (!mainModule.IsILOnly) { WriteCommentLine(output, "This assembly contains unmanaged code."); } string runtimeName = ICSharpCode.ILSpy.CSharpLanguage.GetRuntimeDisplayName(mainModule); if (runtimeName != null) { WriteCommentLine(output, "Runtime: " + runtimeName); } } if (decompileMod || decompileAsm) { output.WriteLine(); } // don't automatically load additional assemblies when an assembly node is selected in the tree view using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition); codeDomBuilder.AddAssembly(assembly.ModuleDefinition, !options.FullDecompilation, decompileAsm, decompileMod); RunTransformsAndGenerateCode(codeDomBuilder, output, options, assembly.ModuleDefinition); } } }
void Run(string compiledFile, string expectedOutputFile) { string expectedOutput = File.ReadAllText(Path.Combine(path, expectedOutputFile)); var assembly = AssemblyDefinition.ReadAssembly(Path.Combine(path, compiledFile)); AstBuilder decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule)); decompiler.AddAssembly(assembly); new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); CodeAssert.AreEqual(expectedOutput, output.ToString()); }
static void TestFile(string fileName, bool optimize, bool useDebug = false) { string code = File.ReadAllText(fileName); AssemblyDefinition assembly = Compile(code, optimize, useDebug); AstBuilder decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule)); decompiler.AddAssembly(assembly); new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); CodeAssert.AreEqual(code, output.ToString()); }
void Run(string compiledFile, string expectedOutputFile) { string expectedOutput = File.ReadAllText(Path.Combine(path, expectedOutputFile)); var assembly = Utils.OpenModule(Path.Combine(path, compiledFile)).Assembly; AstBuilder decompiler = new AstBuilder(DecompilerContext.CreateTestContext(assembly.ManifestModule)); decompiler.AddAssembly(assembly); new Helpers.RemoveCompilerAttribute().Run(decompiler.SyntaxTree); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); CodeAssert.AreEqual(expectedOutput, output.ToString()); }
private static string GenerateAssemblyDescription(ModuleDefinition module) { var context = new DecompilerContext(module); var astBuilder = new AstBuilder(context) { DecompileMethodBodies = false }; astBuilder.AddAssembly(module, true); var output = new PlainTextOutput(); astBuilder.GenerateCode(output); return(output.ToString()); }
public static void Main() { AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(@"C:\Code\Sandbox Form\SandboxForm\bin\Debug\SandboxForm.exe"); var context = new DecompilerContext(assembly.MainModule); context.Settings.AsyncAwait = false; //If you don't do this it will show the original code with the "await" keyword and hide the state machine. AstBuilder decompiler = new AstBuilder(context); decompiler.AddAssembly(assembly); using (var output = new StreamWriter("Output.cs")) { decompiler.GenerateCode(new PlainTextOutput(output)); } }
protected static void AssertRoundtripCode(string fileName, bool optimize = false, bool useDebug = false) { var code = RemoveIgnorableLines(File.ReadLines(fileName)); AssemblyDefinition assembly = CompileLegacy(code, optimize, useDebug); AstBuilder decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule)); decompiler.AddAssembly(assembly); new Helpers.RemoveCompilerAttribute().Run(decompiler.SyntaxTree); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); CodeAssert.AreEqual(code, output.ToString()); }
public override void DecompileAssembly(AssemblyDefinition assembly, string fileName, ITextOutput output, DecompilationOptions options) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(assembly, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(assembly, fileName, options, directories)); WriteProjectFile(new TextOutputWriter(output), files, assembly.MainModule); } else { base.DecompileAssembly(assembly, fileName, output, options); AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: null); codeDomBuilder.AddAssembly(assembly, onlyAssemblyLevel: !options.FullDecompilation); codeDomBuilder.GenerateCode(output, transformAbortCondition); } }
public static void Decompile(string path) { var asm = AssemblyDefinition.ReadAssembly(path); var settings = new DecompilerSettings(); settings.FullyQualifyAmbiguousTypeNames = false; var ctx = new DecompilerContext(asm.MainModule) { Settings = settings }; var decompiler = new AstBuilder(ctx); decompiler.AddAssembly(asm); new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit); var output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); }
private static void WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options) { var path = Path.Combine(options.SaveAsProjectDirectory, Path.Combine("Properties", "AssemblyInfo" + lang.FileExtension)); CreateParentDirectory(path); using (var w = new StreamWriter(path)) { var builder = new AstBuilder( new DecompilerContext(module) { CancellationToken = options.CancellationToken, Settings = options.DecompilerSettings }); builder.AddAssembly(module, true); builder.GenerateCode(new PlainTextOutput(w)); } }
static void TestFile(string fileName) { string code = File.ReadAllText(fileName); AssemblyDefinition assembly = Compile(code); AstBuilder decompiler = new AstBuilder(new DecompilerContext()); decompiler.AddAssembly(assembly); decompiler.Transform(new Helpers.RemoveCompilerAttribute()); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); StringWriter diff = new StringWriter(); if (!Compare(code, output.ToString(), diff)) { throw new Exception("Test failure." + Environment.NewLine + diff.ToString()); } }
IEnumerable<Tuple<string, string>> WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options, HashSet<string> directories) { // don't automatically load additional assemblies when an assembly node is selected in the tree view using (LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module); codeDomBuilder.AddAssembly(module, onlyAssemblyLevel: true); codeDomBuilder.RunTransformations(transformAbortCondition); string prop = "Properties"; if (directories.Add("Properties")) Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, prop)); string assemblyInfo = Path.Combine(prop, "AssemblyInfo" + this.FileExtension); using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, assemblyInfo))) codeDomBuilder.GenerateCode(new PlainTextOutput(w)); return new Tuple<string, string>[] { Tuple.Create("Compile", assemblyInfo) }; } }
/// <summary> /// Compiles and decompiles a source code. /// </summary> /// <param name="code">The source code to copile.</param> /// <returns>The decompilation result of compiled source code.</returns> static string RoundtripCode(string code) { DecompilerSettings settings = new DecompilerSettings(); settings.FullyQualifyAmbiguousTypeNames = false; AssemblyDefinition assembly = Compile(code); AstBuilder decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule) { Settings = settings }); decompiler.AddAssembly(assembly); new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); return(output.ToString()); }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(assembly.ModuleDefinition, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(assembly, options, directories)); WriteProjectFile(new TextOutputWriter(output), files, assembly.ModuleDefinition); } else { base.DecompileAssembly(assembly, output, options); output.WriteLine(); ModuleDefinition mainModule = assembly.ModuleDefinition; if (mainModule.EntryPoint != null) { output.Write("// Entry point: "); output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint); output.WriteLine(); } output.WriteLine("// Architecture: " + GetPlatformDisplayName(mainModule)); if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) { output.WriteLine("// This assembly contains unmanaged code."); } string runtimeName = GetRuntimeDisplayName(mainModule); if (runtimeName != null) { output.WriteLine("// Runtime: " + runtimeName); } output.WriteLine(); // don't automatically load additional assemblies when an assembly node is selected in the tree view using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition); codeDomBuilder.AddAssembly(assembly.ModuleDefinition, onlyAssemblyLevel: !options.FullDecompilation); codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.GenerateCode(output); } } }
public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options) { if (options.FullDecompilation && options.SaveAsProjectDirectory != null) { HashSet <string> directories = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var files = WriteCodeFilesInProject(assembly.AssemblyDefinition, options, directories).ToList(); files.AddRange(WriteResourceFilesInProject(assembly, options, directories)); WriteProjectFile(new TextOutputWriter(output), files, assembly.AssemblyDefinition.MainModule); } else { base.DecompileAssembly(assembly, output, options); // don't automatically load additional assemblies when an assembly node is selected in the tree view using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) { AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.AssemblyDefinition.MainModule); codeDomBuilder.AddAssembly(assembly.AssemblyDefinition, onlyAssemblyLevel: !options.FullDecompilation); codeDomBuilder.RunTransformations(transformAbortCondition); codeDomBuilder.GenerateCode(output); } } }
public void Decompile(Stream assemblyStream, TextWriter codeWriter) { // ReSharper disable once AgentHeisenbug.CallToNonThreadSafeStaticMethodInThreadSafeType var module = ModuleDefinition.ReadModule(assemblyStream, new ReaderParameters { AssemblyResolver = PreCachedAssemblyResolver.Instance }); var context = new DecompilerContext(module) { Settings = { CanInlineVariables = false, OperatorOverloading = false, AnonymousMethods = false, AnonymousTypes = false, YieldReturn = false, AsyncAwait = false, AutomaticProperties = false, ExpressionTrees = false, ArrayInitializers = false, ObjectOrCollectionInitializers = false, LiftedOperators = false, UsingStatement = false } }; var ast = new AstBuilder(context); ast.AddAssembly(module.Assembly); // Remove a large helper class generated by Peachpie ast.SyntaxTree.Children .OfType <TypeDeclaration>() .Where(decl => decl.Name == Pchp.Core.Context.ScriptInfo.ScriptTypeName) .FirstOrDefault() ?.Remove(); WriteResult(codeWriter, ast); }