public void DecompileOnDemand(TypeDefinition type) { if (type == null) return; if (CheckMappings(type.MetadataToken.ToInt32())) return; try { DecompilerContext context = new DecompilerContext(type.Module); AstBuilder astBuilder = new AstBuilder(context); astBuilder.AddType(type); astBuilder.GenerateCode(new PlainTextOutput()); int token = type.MetadataToken.ToInt32(); var info = new DecompileInformation { CodeMappings = astBuilder.CodeMappings, LocalVariables = astBuilder.LocalVariables, DecompiledMemberReferences = astBuilder.DecompiledMemberReferences }; // save the data DebugInformation.AddOrUpdate(token, info, (k, v) => info); } catch { return; } }
public static async Task<string> GetSourceCode(MethodDefinition methodDefinition, ILWeaver weaver = null) { return await Task.Run(() => { try { if (weaver != null) weaver.Apply(methodDefinition.Body); var settings = new DecompilerSettings { UsingDeclarations = false }; var context = new DecompilerContext(methodDefinition.Module) { CurrentType = methodDefinition.DeclaringType, Settings = settings }; var astBuilder = new AstBuilder(context); astBuilder.AddMethod(methodDefinition); var textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); } catch (Exception ex) { return "Error in creating source code from IL: " + ex.Message + Environment.NewLine + ex.StackTrace; } finally { if (weaver != null) methodDefinition.Body = null; } }); }
private static void CompareAssemblyAgainstCSharp(string expectedCSharpCode, string asmFilePath) { var module = Utils.OpenModule(asmFilePath); try { try { module.LoadPdb(); } catch { } AstBuilder decompiler = new AstBuilder(DecompilerContext.CreateTestContext(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")); } }
/// <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(); }
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.SyntaxTree); StringWriter output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); CodeAssert.AreEqual(expectedOutput, output.ToString()); }
public void DecompileFile(string input, TextWriter writer) { var assembly = AssemblyDefinition.ReadAssembly(input, new ReaderParameters() { AssemblyResolver = new IgnoringExceptionsAssemblyResolver() }); var decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule)); decompiler.AddAssembly(assembly); decompiler.GenerateCode(new PlainTextOutput(writer)); writer.Close(); }
public void Decompile() { AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly("Salient.JsonSchemaUtilities.dll"); DecompilerSettings settings = new DecompilerSettings(); settings.FullyQualifyAmbiguousTypeNames = false; 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)); var code = output.ToString(); }
/// <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(); }
protected static void AssertRoundtripCode(string fileName, bool optimize = false, bool useDebug = false, int compilerVersion = 4) { var code = RemoveIgnorableLines(File.ReadLines(fileName)); AssemblyDef assembly = CompileLegacy(code, optimize, useDebug, compilerVersion); 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(code, output.ToString()); }
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()); } }
public static string ToSource(MethodDefinition methodDefinition) { var settings = new DecompilerSettings { UsingDeclarations = false }; var context = new DecompilerContext(methodDefinition.Module) { CurrentType = methodDefinition.DeclaringType, Settings = settings, }; var astBuilder = new AstBuilder(context); astBuilder.AddMethod(methodDefinition); var textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); }
public static async Task<string> GetSourceCode(TypeDefinition typeDefinition) { return await Task.Run(() => { try { var settings = new DecompilerSettings { UsingDeclarations = true }; var context = new DecompilerContext(typeDefinition.Module) { CurrentType = typeDefinition, Settings = settings }; var astBuilder = new AstBuilder(context); var textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); } catch (Exception ex) { return "Error in creating source code from Type: " + ex.Message + ex.Message + Environment.NewLine + ex.StackTrace; } }); }
private static string Decompile(string name, MethodDefinition mtd) { var decompilerSettings = new ICSharpCode.Decompiler.DecompilerSettings { ShowXmlDocumentation = false, UsingDeclarations = false, }; var output = new ICSharpCode.Decompiler.PlainTextOutput(); var method = mtd; var astBuilder = new AstBuilder(new DecompilerContext(method.DeclaringType.Module) { CancellationToken = new CancellationToken(), CurrentType = method.DeclaringType, Settings = decompilerSettings, }); astBuilder.AddMethod(method); astBuilder.GenerateCode(output); var methodCode = output.ToString(); // remove top comment line //if (methodCode.StartsWith("//")) { // methodCode = methodCode.Substring(methodCode.IndexOf('\n') + 1); //} var attrRE = new Regex(@"^(?:\[[^]]+]\s*){1,}"); methodCode = attrRE.Replace(methodCode, "", 1); // change the method name to the mod's name for the method, and replace parameter names with game names var methodName = mtd.Name; var nameLocation = methodCode.IndexOf(" " + methodName) + 1; var nameEnd = nameLocation + methodName.Length; // Prepend "void " if this was a constructor (since methodCode won't have a return type) var correctName = mtd.IsConstructor ? ("void " + name) : name; methodCode = methodCode.Substring(0, nameLocation) + correctName + methodCode.Substring(nameEnd); return methodCode; }
public static List<ReferenceSegment> Decompile (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData) { try { var types = DesktopService.GetMimeTypeInheritanceChain (data.Document.MimeType); var codePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types); var context = new DecompilerContext (module); var source = new CancellationTokenSource (); context.CancellationToken = source.Token; context.CurrentType = currentType; context.Settings = new DecompilerSettings () { AnonymousMethods = true, AutomaticEvents = true, AutomaticProperties = true, ForEachStatement = true, LockStatement = true }; AstBuilder astBuilder = new AstBuilder (context); setData (astBuilder); astBuilder.RunTransformations (o => false); var output = new ColoredCSharpFormatter (data.Document); astBuilder.GenerateCode (output, codePolicy.CreateOptions ()); output.SetDocumentData (); return output.ReferencedSegments; } catch (Exception e) { data.Text = "Decompilation failed: \n" + e; } return null; }
void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, IAstTransform additionalTransform = null) { astBuilder.RunTransformations(transformAbortCondition); if (additionalTransform != null) { additionalTransform.Run(astBuilder.SyntaxTree); } if (options.DecompilerSettings.ShowXmlDocumentation) { try { AddXmlDocTransform.Run(astBuilder.SyntaxTree); } catch (XmlException ex) { string[] msg = (" Exception while reading XmlDoc: " + ex.ToString()).Split(new[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries); var insertionPoint = astBuilder.SyntaxTree.FirstChild; for (int i = 0; i < msg.Length; i++) astBuilder.SyntaxTree.InsertChildBefore(insertionPoint, new Comment(msg[i], CommentType.Documentation), Roles.Comment); } } astBuilder.GenerateCode(output); }
public static List<ReferenceSegment> Decompile (TextEditor data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData, DecompilerSettings settings) { var context = new DecompilerContext (module); var source = new CancellationTokenSource (); context.CancellationToken = source.Token; context.CurrentType = currentType; context.Settings = settings; try { var astBuilder = new AstBuilder (context); setData (astBuilder); astBuilder.RunTransformations (o => false); GeneratedCodeSettings.Default.Apply (astBuilder.SyntaxTree); var output = new ColoredCSharpFormatter (data); astBuilder.GenerateCode (output); output.SetDocumentData (); return output.ReferencedSegments; } catch (Exception e) { // exception -> try to decompile without method bodies try { var astBuilder = new AstBuilder (context); astBuilder.DecompileMethodBodies = false; setData (astBuilder); astBuilder.RunTransformations (o => false); GeneratedCodeSettings.Default.Apply (astBuilder.SyntaxTree); var output = new ColoredCSharpFormatter (data); astBuilder.GenerateCode (output); output.SetDocumentData (); data.InsertText (data.Length, "/* body decompilation failed: \n" + e + " */"); } catch (Exception e2) { data.Text = "/* fallback decompilation failed: \n" + e2 +"*/"; } } return null; }
protected virtual void InnerGenerateCode(AstBuilder astBuilder, ITextOutput output) { astBuilder.GenerateCode(output); }
public ICSharpCode.AvalonEdit.Document.TextDocument Decompile(object obj) { AvalonEditTextOutput aeto = new AvalonEditTextOutput(); AstBuilder ast = new AstBuilder(new DecompilerContext(ModuleDefinition.CreateModule("ash", ModuleKind.NetModule))); switch (obj.GetType().Name) { case "AssemblyDefinition": ast = new AstBuilder(new DecompilerContext((obj as AssemblyDefinition).MainModule) { Settings = new DecompilerSettings() }); try { ast.AddAssembly(obj as AssemblyDefinition); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.FullName); } break; case "TypeDefinition": ast = CreateAstBuilder((obj as TypeDefinition), true); try { ast.AddType(obj as TypeDefinition); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.FullName); } break; case "MethodDefinition": MethodDefinition method = (obj as MethodDefinition); ast = CreateAstBuilder(method.DeclaringType, true); if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType) { foreach (var field in method.DeclaringType.Fields) if (field.IsStatic == method.IsStatic) { try { ast.AddField(field); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.Name); } } foreach (var ctor in method.DeclaringType.Methods) if (ctor.IsConstructor && ctor.IsStatic == method.IsStatic) { try { ast.AddMethod(ctor); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.Name); } } } else { try { ast.AddMethod(obj as MethodDefinition); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.Name); } } break; case "PropertyDefinition": ast = CreateAstBuilder((obj as PropertyDefinition).DeclaringType, true); try { ast.AddProperty(obj as PropertyDefinition); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.Name); } break; case "FieldDefinition": ast = CreateAstBuilder((obj as FieldDefinition).DeclaringType, true); try { ast.AddField(obj as FieldDefinition); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.Name); } break; case "EventDefinition": ast = CreateAstBuilder((obj as EventDefinition).DeclaringType, true); try { ast.AddEvent(obj as EventDefinition); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly " + e.AssemblyReference.Name); } break; default: return new ICSharpCode.AvalonEdit.Document.TextDocument(); } try { ast.GenerateCode(aeto); } catch (AssemblyResolutionException e) { MessageBox.Show("Could not load assembly upon code generation:\r" + e.AssemblyReference.FullName); } return aeto.GetDocument(); }
void RunDecompiler(string assemblyFile, string fullTypeName, DebuggerTextOutput textOutput, CancellationToken cancellationToken) { ReaderParameters readerParameters = new ReaderParameters(); // Use new assembly resolver instance so that the AssemblyDefinitions can be garbage-collected // once the code is decompiled. readerParameters.AssemblyResolver = new ILSpyAssemblyResolver(Path.GetDirectoryName(assemblyFile)); ModuleDefinition module = ModuleDefinition.ReadModule(assemblyFile, readerParameters); TypeDefinition typeDefinition = module.GetType(fullTypeName); if (typeDefinition == null) throw new InvalidOperationException("Could not find type"); DecompilerContext context = new DecompilerContext(module); context.CancellationToken = cancellationToken; AstBuilder astBuilder = new AstBuilder(context); astBuilder.AddType(typeDefinition); astBuilder.GenerateCode(textOutput); // save decompilation data decompiledType = typeDefinition; memberLocations = textOutput.MemberLocations; }
void RunDecompiler(string assemblyFile, string fullTypeName, ITextOutput textOutput, CancellationToken cancellationToken) { ReaderParameters readerParameters = new ReaderParameters(); // Use new assembly resolver instance so that the AssemblyDefinitions can be garbage-collected // once the code is decompiled. readerParameters.AssemblyResolver = new ILSpyAssemblyResolver(Path.GetDirectoryName(assemblyFile)); ModuleDefinition module = ModuleDefinition.ReadModule(assemblyFile, readerParameters); TypeDefinition typeDefinition = module.GetType(fullTypeName); if (typeDefinition == null) throw new InvalidOperationException("Could not find type"); DecompilerContext context = new DecompilerContext(module); context.CancellationToken = cancellationToken; AstBuilder astBuilder = new AstBuilder(context); astBuilder.AddType(typeDefinition); astBuilder.GenerateCode(textOutput); // save decompilation data decompiledType = typeDefinition; /* int token = decompiledType.MetadataToken.ToInt32(); var info = new DecompileInformation { CodeMappings = astBuilder.CodeMappings, LocalVariables = astBuilder.LocalVariables, DecompiledMemberReferences = astBuilder.DecompiledMemberReferences }; // save the data DebuggerDecompilerService.DebugInformation.AddOrUpdate(token, info, (k, v) => info); */ }
public bool Compile() { LogLine(1, "Compiling Xaml"); LogLine(1, "\nAssembly: {0}", Assembly); if (!string.IsNullOrEmpty(DependencyPaths)) LogLine(1, "DependencyPaths: \t{0}", DependencyPaths); if (!string.IsNullOrEmpty(ReferencePath)) LogLine(1, "ReferencePath: \t{0}", ReferencePath.Replace("//", "/")); LogLine(3, "DebugSymbols:\"{0}\"", DebugSymbols); var skipassembly = true; //change this to false to enable XamlC by default bool success = true; if (!File.Exists(Assembly)) { LogLine(1, "Assembly file not found. Skipping XamlC."); return true; } var resolver = new XamlCAssemblyResolver(); if (!string.IsNullOrEmpty(DependencyPaths)) { foreach (var dep in DependencyPaths.Split(';')) { LogLine(3, "Adding searchpath {0}", dep); resolver.AddSearchDirectory(dep); } } if (!string.IsNullOrEmpty(ReferencePath)) { var paths = ReferencePath.Replace("//", "/").Split(';'); foreach (var p in paths) { var searchpath = Path.GetDirectoryName(p); LogLine(3, "Adding searchpath {0}", searchpath); resolver.AddSearchDirectory(searchpath); // LogLine (3, "Referencing {0}", p); // resolver.AddAssembly (p); } } var assemblyDefinition = AssemblyDefinition.ReadAssembly(Path.GetFullPath(Assembly), new ReaderParameters { AssemblyResolver = resolver, ReadSymbols = DebugSymbols }); CustomAttribute xamlcAttr; if (assemblyDefinition.HasCustomAttributes && (xamlcAttr = assemblyDefinition.CustomAttributes.FirstOrDefault( ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null) { var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value; if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip) skipassembly = true; if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile) skipassembly = false; } foreach (var module in assemblyDefinition.Modules) { var skipmodule = skipassembly; if (module.HasCustomAttributes && (xamlcAttr = module.CustomAttributes.FirstOrDefault( ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null) { var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value; if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip) skipmodule = true; if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile) skipmodule = false; } LogLine(2, " Module: {0}", module.Name); var resourcesToPrune = new List<EmbeddedResource>(); foreach (var resource in module.Resources.OfType<EmbeddedResource>()) { Log(2, " Resource: {0}... ", resource.Name); string classname; if (!resource.IsXaml(out classname)) { LogLine(2, "skipped."); continue; } TypeDefinition typeDef = module.GetType(classname); if (typeDef == null) { LogLine(2, "no type found... skipped."); continue; } var skiptype = skipmodule; if (typeDef.HasCustomAttributes && (xamlcAttr = typeDef.CustomAttributes.FirstOrDefault( ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null) { var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value; if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip) skiptype = true; if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile) skiptype = false; } if (skiptype) { LogLine(2, "Has XamlCompilationAttribute set to Skip and not Compile... skipped"); continue; } var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent"); if (initComp == null) { LogLine(2, "no InitializeComponent found... skipped."); continue; } LogLine(2, ""); Log(2, " Parsing Xaml... "); var rootnode = ParseXaml(resource.GetResourceStream(), typeDef); if (rootnode == null) { LogLine(2, "failed."); continue; } LogLine(2, "done."); hasCompiledXamlResources = true; try { Log(2, " Replacing {0}.InitializeComponent ()... ", typeDef.Name); var body = new MethodBody(initComp); var il = body.GetILProcessor(); il.Emit(OpCodes.Nop); var visitorContext = new ILContext(il, body); rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null); rootnode.Accept(new ExpandMarkupsVisitor(visitorContext), null); rootnode.Accept(new CreateObjectVisitor(visitorContext), null); rootnode.Accept(new SetNamescopesAndRegisterNamesVisitor(visitorContext), null); rootnode.Accept(new SetFieldVisitor(visitorContext), null); rootnode.Accept(new SetResourcesVisitor(visitorContext), null); rootnode.Accept(new SetPropertiesVisitor(visitorContext, true), null); il.Emit(OpCodes.Ret); initComp.Body = body; } catch (XamlParseException xpe) { LogLine(2, "failed."); LogError(null, null, null, resource.Name, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message, xpe.HelpLink, xpe.Source); LogLine(4, xpe.StackTrace); success = false; continue; } catch (XmlException xe) { LogLine(2, "failed."); LogError(null, null, null, resource.Name, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source); LogLine(4, xe.StackTrace); success = false; continue; } catch (Exception e) { LogLine(2, "failed."); LogError(null, null, null, resource.Name, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source); LogLine(4, e.StackTrace); success = false; continue; } LogLine(2, "done."); if (OptimizeIL) { Log(2, " Optimizing IL... "); initComp.Body.OptimizeMacros(); LogLine(2, "done"); } if (OutputGeneratedILAsCode) { var filepath = Path.Combine(Path.GetDirectoryName(Assembly), typeDef.FullName + ".decompiled.cs"); Log(2, " Decompiling {0} into {1}...", typeDef.FullName, filepath); var decompilerContext = new DecompilerContext(module); using (var writer = new StreamWriter(filepath)) { var output = new PlainTextOutput(writer); var codeDomBuilder = new AstBuilder(decompilerContext); codeDomBuilder.AddType(typeDef); codeDomBuilder.GenerateCode(output); } LogLine(2, "done"); } resourcesToPrune.Add(resource); } if (!KeepXamlResources) { if (resourcesToPrune.Any()) LogLine(2, " Removing compiled xaml resources"); foreach (var resource in resourcesToPrune) { Log(2, " Removing {0}... ", resource.Name); module.Resources.Remove(resource); LogLine(2, "done"); } } LogLine(2, ""); } if (!hasCompiledXamlResources) { LogLine(1, "No compiled resources. Skipping writing assembly."); return success; } Log(1, "Writing the assembly... "); try { assemblyDefinition.Write(Assembly, new WriterParameters { WriteSymbols = DebugSymbols }); LogLine(1, "done."); } catch (Exception e) { LogLine(1, "failed."); LogError(null, null, null, null, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source); LogLine(4, e.StackTrace); success = false; } return success; }
void Run(Config config) { if (config.ShowHelp) { Console.WriteLine ("Netjs compiler, Copyright 2014 Frank A. Krueger"); Console.WriteLine ("netjs [options] assembly-file"); return; } if (string.IsNullOrEmpty (config.MainAssembly)) { throw new Exception ("No assembly specified."); } var asmPath = Path.GetFullPath (config.MainAssembly); asmDir = Path.GetDirectoryName (asmPath); var outPath = Path.ChangeExtension (asmPath, ".ts"); Step ("Reading IL"); var parameters = new ReaderParameters { AssemblyResolver = this, }; var asm = AssemblyDefinition.ReadAssembly (asmPath, parameters); mscorlib = AssemblyDefinition.ReadAssembly (typeof(String).Assembly.Location, parameters); system = AssemblyDefinition.ReadAssembly (typeof(INotifyPropertyChanged).Assembly.Location, parameters); systemCore = AssemblyDefinition.ReadAssembly (typeof(Enumerable).Assembly.Location, parameters); Step ("Decompiling IL to C#"); var context = new DecompilerContext (asm.MainModule); context.Settings.ForEachStatement = false; context.Settings.ObjectOrCollectionInitializers = false; context.Settings.UsingStatement = false; context.Settings.AsyncAwait = false; context.Settings.AutomaticProperties = true; context.Settings.AutomaticEvents = true; context.Settings.QueryExpressions = false; context.Settings.AlwaysGenerateExceptionVariableForCatchBlocks = true; context.Settings.UsingDeclarations = false; context.Settings.FullyQualifyAmbiguousTypeNames = true; context.Settings.YieldReturn = false; var builder = new AstBuilder (context); builder.AddAssembly (asm); foreach (var a in referencedAssemblies.Values) { if (a != null) builder.AddAssembly (a); } builder.RunTransformations (); Step ("Translating C# to TypeScript"); new CsToTs ().Run (builder.SyntaxTree); Step ("Writing"); using (var outputWriter = new StreamWriter (outPath)) { var output = new PlainTextOutput (outputWriter); builder.GenerateCode (output, (s, e) => new TsOutputVisitor (s, e)); } Step ("Done"); }
private void GenerateCode(AstBuilder decompiler) { decompiler.GenerateCode(_output); if (!String.IsNullOrEmpty(OutputFileName)) { File.WriteAllText(OutputFileName, _output.ToString()); } else { _context.Write(_output.ToString()); } }
public static List<ReferenceSegment> Decompile (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData, DecompilerSettings settings) { try { var context = new DecompilerContext (module); var source = new CancellationTokenSource (); context.CancellationToken = source.Token; context.CurrentType = currentType; context.Settings = settings; AstBuilder astBuilder = new AstBuilder (context); setData (astBuilder); astBuilder.RunTransformations (o => false); GeneratedCodeSettings.Default.Apply (astBuilder.CompilationUnit); var output = new ColoredCSharpFormatter (data.Document); astBuilder.GenerateCode (output); output.SetDocumentData (); return output.ReferencedSegments; } catch (Exception e) { data.Text = "Decompilation failed: \n" + e; } return null; }
void Run(Config config) { if (config.AssembliesToDecompile.Count == 0) { config.ShowHelp = true; } if (config.ShowHelp) { Console.WriteLine ("Netjs compiler, Copyright 2014-2016 Frank A. Krueger"); Console.WriteLine ("netjs [options] assembly-files"); Console.WriteLine (" --help, -h Show usage information"); Console.WriteLine (" --includerefs, -r Decompile referenced assemblies"); return; } string outPath = ""; var asmPaths = new List<string> (); foreach (var asmRelPath in config.AssembliesToDecompile) { var asmPath = Path.GetFullPath (asmRelPath); asmPaths.Add (asmPath); if (string.IsNullOrEmpty (outPath)) { outPath = Path.ChangeExtension (asmPath, ".ts"); } var asmDir = Path.GetDirectoryName (asmPath); if (!asmSearchPaths.Exists (x => x.Item1 == asmDir)) { asmSearchPaths.Add (Tuple.Create (asmDir, config.IncludeRefs)); } } Step ("Reading IL"); globalReaderParameters.AssemblyResolver = this; globalReaderParameters.ReadingMode = ReadingMode.Immediate; var libDir = Path.GetDirectoryName (typeof (String).Assembly.Location); asmSearchPaths.Add (Tuple.Create(libDir, false)); asmSearchPaths.Add (Tuple.Create(Path.Combine (libDir, "Facades"), false)); AssemblyDefinition firstAsm = null; foreach (var asmPath in asmPaths) { var asm = AssemblyDefinition.ReadAssembly (asmPath, globalReaderParameters); if (firstAsm == null) firstAsm = asm; referencedAssemblies[asm.Name.Name] = asm; decompileAssemblies.Add (asm); } Step ("Decompiling IL to C#"); var context = new DecompilerContext (firstAsm.MainModule); context.Settings.ForEachStatement = false; context.Settings.ObjectOrCollectionInitializers = false; context.Settings.UsingStatement = false; context.Settings.AsyncAwait = false; context.Settings.AutomaticProperties = true; context.Settings.AutomaticEvents = true; context.Settings.QueryExpressions = false; context.Settings.AlwaysGenerateExceptionVariableForCatchBlocks = true; context.Settings.UsingDeclarations = false; context.Settings.FullyQualifyAmbiguousTypeNames = true; context.Settings.YieldReturn = false; var builder = new AstBuilder (context); var decompiled = new HashSet<string> (); for (;;) { var a = decompileAssemblies.FirstOrDefault (x => !decompiled.Contains (x.FullName)); if (a != null) { Info (" Decompiling {0}", a.FullName); builder.AddAssembly (a); decompiled.Add (a.FullName); } else { break; } } builder.RunTransformations (); Step ("Translating C# to TypeScript"); new CsToTs ().Run (builder.SyntaxTree); Step ("Writing"); using (var outputWriter = new StreamWriter (outPath)) { var output = new PlainTextOutput (outputWriter); builder.GenerateCode (output, (s, e) => new TsOutputVisitor (s, e)); } Step ("Done"); }
void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationContext ctx, IAstTransform additionalTransform = null) { astBuilder.RunTransformations(transformAbortCondition); if (additionalTransform != null) { additionalTransform.Run(astBuilder.SyntaxTree); } AddXmlDocumentation(langSettings.Settings, astBuilder); astBuilder.GenerateCode(output); }
static void TestFile(string fileName, bool optimize) { string code = File.ReadAllText(fileName); AssemblyDefinition assembly = Compile(code, optimize); 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()); }
public override string GetTooltip(MemberReference member) { MethodDefinition md = member as MethodDefinition; PropertyDefinition pd = member as PropertyDefinition; EventDefinition ed = member as EventDefinition; FieldDefinition fd = member as FieldDefinition; if (md != null || pd != null || ed != null || fd != null) { AstBuilder b = new AstBuilder(new DecompilerContext(member.Module) { Settings = new DecompilerSettings { UsingDeclarations = false } }); b.DecompileMethodBodies = false; if (md != null) b.AddMethod(md); else if (pd != null) b.AddProperty(pd); else if (ed != null) b.AddEvent(ed); else b.AddField(fd); b.RunTransformations(); foreach (var attribute in b.CompilationUnit.Descendants.OfType<AttributeSection>()) attribute.Remove(); StringWriter w = new StringWriter(); b.GenerateCode(new PlainTextOutput(w)); return Regex.Replace(w.ToString(), @"\s+", " ").TrimEnd(); } return base.GetTooltip(member); }
void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, IAstTransform additionalTransform = null) { astBuilder.RunTransformations(transformAbortCondition); if (additionalTransform != null) { additionalTransform.Run(astBuilder.CompilationUnit); } if (options.DecompilerSettings.ShowXmlDocumentation) { AddXmlDocTransform.Run(astBuilder.CompilationUnit); } astBuilder.GenerateCode(output); }
public string GetClass(TypeIdentity identity) { // Before we attempt to fetch it just try a decompilation. GetAssembly(identity.AssemblyPath); ModuleDefinition moduleDef; if (!this.loadedModules.TryGetValue(identity.AssemblyPath, out moduleDef)) { // Can't find the assembly, just return nothing. return string.Empty; } TypeDefinition typeDef = moduleDef.GetType(identity.FullyQualifiedName); if (typeDef == null) { // If we can't find our type just return as well. return string.Empty; } DecompilerContext context = new DecompilerContext(moduleDef); AstBuilder astBuilder = new AstBuilder(context); astBuilder.AddType(typeDef); PlainTextOutput textOutput = new PlainTextOutput(); astBuilder.GenerateCode(textOutput); return textOutput.ToString(); }