public override bool View(DecompilerTextView textView) { AvalonEditTextOutput output = new AvalonEditTextOutput(); IHighlightingDefinition highlighting = null; textView.RunWithCancellation( token => Task.Factory.StartNew( () => { try { // cache read XAML because stream will be closed after first read if (xml == null) { using (var reader = new StreamReader(Data)) { xml = reader.ReadToEnd(); } } output.Write(xml); highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } catch (Exception ex) { output.Write(ex.ToString()); } return(output); }, token), t => textView.ShowNode(t.Result, this, highlighting) ); return(true); }
public override bool View(TabPageModel tabPage) { AvalonEditTextOutput output = new AvalonEditTextOutput(); IHighlightingDefinition highlighting = null; tabPage.ShowTextView(textView => textView.RunWithCancellation( token => Task.Factory.StartNew( () => { try { // cache read text because stream will be closed after first read if (text == null) { using (var reader = new StreamReader(Data)) { text = reader.ReadToEnd(); } } output.Write(text); highlighting = null; } catch (Exception ex) { output.Write(ex.ToString()); } return(output); }, token) ).Then(t => textView.ShowNode(t, this, highlighting)) .HandleExceptions()); tabPage.SupportsLanguageSwitching = false; return(true); }
public override void Execute(object parameter) { MainWindow.Instance.TextView.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => { AvalonEditTextOutput output = new AvalonEditTextOutput(); Parallel.ForEach(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct }, delegate(LoadedAssembly asm) { if (!asm.HasLoadError) { Stopwatch w = Stopwatch.StartNew(); Exception exception = null; using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) { try { new CSharpLanguage().DecompileAssembly(asm, new Decompiler.PlainTextOutput(writer), new DecompilationOptions() { FullDecompilation = true, CancellationToken = ct }); } catch (Exception ex) { writer.WriteLine(ex.ToString()); exception = ex; } } lock (output) { output.Write(asm.ShortName + " - " + w.Elapsed); if (exception != null) { output.Write(" - "); output.Write(exception.GetType().Name); } output.WriteLine(); } } }); return output; }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions(); }
public void EndAsyncShow(IShowContext ctx, IAsyncShowResult result) { var decompileContext = (DecompileContext)ctx.UserData; var uiCtx = (ITextEditorUIContext)ctx.UIContext; IHighlightingDefinition highlighting; if (decompileContext.DecompileNodeContext.HighlightingDefinition != null) { highlighting = decompileContext.DecompileNodeContext.HighlightingDefinition; } else if (decompileContext.DecompileNodeContext.HighlightingExtension != null) { highlighting = HighlightingManager.Instance.GetDefinitionByExtension(decompileContext.DecompileNodeContext.HighlightingExtension); } else { highlighting = decompileContext.DecompileNodeContext.Language.GetHighlightingDefinition(); } AvalonEditTextOutput output; if (result.IsCanceled) { output = new AvalonEditTextOutput(); output.Write(dnSpy_Resources.DecompilationCanceled, TextTokenKind.Error); } else if (result.Exception != null) { output = new AvalonEditTextOutput(); output.Write(dnSpy_Resources.DecompilationException, TextTokenKind.Error); output.WriteLine(); output.Write(result.Exception.ToString(), TextTokenKind.Text); } else { output = decompileContext.CachedOutput; if (output == null) { output = (AvalonEditTextOutput)decompileContext.DecompileNodeContext.Output; decompileFileTabContentFactory.DecompilationCache.Cache(decompileContext.DecompileNodeContext.Language, nodes, output, highlighting); } } if (result.CanShowOutput) { uiCtx.SetOutput(output, highlighting); } }
public override bool View(DecompilerTextView textView) { EmbeddedResource er = r as EmbeddedResource; if (er != null) { Stream s = er.GetResourceStream(); if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit) { s.Position = 0; FileType type = GuessFileType.DetectFileType(s); if (type != FileType.Binary) { s.Position = 0; AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write(FileReader.OpenStream(s, Encoding.UTF8).ReadToEnd()); string ext; if (type == FileType.Xml) { ext = ".xml"; } else { ext = Path.GetExtension(DecompilerTextView.CleanUpName(er.Name)); } textView.ShowNode(output, this, HighlightingManager.Instance.GetDefinitionByExtension(ext)); return(true); } } } return(false); }
public override bool View(DecompilerTextView textView) { AvalonEditTextOutput output = new AvalonEditTextOutput(); IHighlightingDefinition highlighting = null; var lang = MainWindow.Instance.CurrentLanguage; textView.RunWithCancellation( token => Task.Factory.StartNew( () => { try { bamlData.Position = 0; var document = BamlReader.ReadDocument(bamlData, token); if (BamlSettings.Instance.DisassembleBaml) { Disassemble(module, document, lang, output, out highlighting, token); } else { Decompile(module, document, lang, output, out highlighting, token); } } catch (Exception ex) { output.Write(ex.ToString(), TextTokenType.Text); } return(output); }, token) ).Then(t => textView.ShowNode(t, this, highlighting)).HandleExceptions(); return(true); }
public override bool View(TabPageModel tabPage) { Stream s = Resource.TryOpenStream(); if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit) { s.Position = 0; FileType type = GuessFileType.DetectFileType(s); if (type != FileType.Binary) { s.Position = 0; AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Title = Resource.Name; output.Write(FileReader.OpenStream(s, Encoding.UTF8).ReadToEnd()); string ext; if (type == FileType.Xml) { ext = ".xml"; } else { ext = Path.GetExtension(DecompilerTextView.CleanUpName(Resource.Name)); } tabPage.ShowTextView(textView => textView.ShowNode(output, this, HighlightingManager.Instance.GetDefinitionByExtension(ext))); tabPage.SupportsLanguageSwitching = false; return(true); } } return(false); }
public override bool View(TabPageModel tabPage) { IHighlightingDefinition highlighting = null; tabPage.SupportsLanguageSwitching = false; tabPage.ShowTextView(textView => textView.RunWithCancellation( token => Task.Factory.StartNew( () => { AvalonEditTextOutput output = new AvalonEditTextOutput(); try { if (LoadBaml(output, token)) { highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } } catch (Exception ex) { output.Write(ex.ToString()); } return(output); }, token)) .Then(output => textView.ShowNode(output, this, highlighting)) .HandleExceptions()); return(true); }
void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args) { if (args.NavigateTo != null) { bool found = false; foreach (LoadedAssembly asm in commandLineLoadedAssemblies) { AssemblyDefinition def = asm.AssemblyDefinition; if (def != null) { MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def.MainModule, args.NavigateTo); if (mr != null) { found = true; JumpToReference(mr); break; } } } if (!found) { AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write("Cannot find " + args.NavigateTo); decompilerTextView.Show(output); } } commandLineLoadedAssemblies.Clear(); // clear references once we don't need them anymore }
void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args) { if (args.NavigateTo != null) { bool found = false; if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal)) { string namespaceName = args.NavigateTo.Substring(2); foreach (LoadedAssembly asm in commandLineLoadedAssemblies) { AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm); if (asmNode != null) { NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName); if (nsNode != null) { found = true; SelectNode(nsNode); break; } } } } else { foreach (LoadedAssembly asm in commandLineLoadedAssemblies) { ModuleDefinition def = asm.GetModuleDefinitionOrNull(); if (def != null) { MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def, args.NavigateTo); if (mr != null) { found = true; JumpToReference(mr); break; } } } } if (!found) { AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", args.NavigateTo)); decompilerTextView.ShowText(output); } } else if (commandLineLoadedAssemblies.Count == 1) { // NavigateTo == null and an assembly was given on the command-line: // Select the newly loaded assembly JumpToReference(commandLineLoadedAssemblies[0].GetModuleDefinitionOrNull()); } if (args.Search != null) { SearchPane.Instance.SearchTerm = args.Search; SearchPane.Instance.Show(); } commandLineLoadedAssemblies.Clear(); // clear references once we don't need them anymore }
public override bool View(TabPageModel tabPage) { try { AvalonEditTextOutput output = new AvalonEditTextOutput(); using var data = OpenStream(); if (data == null) { return(false); } IconBitmapDecoder decoder = new IconBitmapDecoder(data, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); foreach (var frame in decoder.Frames) { output.Write(String.Format("{0}x{1}, {2} bit: ", frame.PixelHeight, frame.PixelWidth, frame.Thumbnail.Format.BitsPerPixel)); AddIcon(output, frame); output.WriteLine(); } output.AddButton(Images.Save, Resources.Save, delegate { Save(null); }); tabPage.ShowTextView(textView => textView.ShowNode(output, this)); tabPage.SupportsLanguageSwitching = false; return(true); } catch (Exception) { return(false); } }
public override bool View(DecompilerTextView textView) { try { AvalonEditTextOutput output = new AvalonEditTextOutput(); Data.Position = 0; IconBitmapDecoder decoder = new IconBitmapDecoder(Data, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None); foreach (var frame in decoder.Frames) { output.Write(String.Format("{0}x{1}, {2} bit: ", frame.PixelHeight, frame.PixelWidth, frame.Thumbnail.Format.BitsPerPixel)); AddIcon(output, frame); output.WriteLine(); } output.AddButton(Images.Save, "Save", delegate { Save(null); }); textView.ShowNode(output, this); return(true); } catch (Exception) { return(false); } }
public void Write(string s, TextTokenType tokenType) { if (needsNewLine) { WriteNewLine(); } output.Write(s, tokenType); }
/// <summary> /// Handle exceptions by displaying the error message in the text view. /// </summary> public static void HandleExceptions(this Task task) { task.Catch <Exception>(exception => MainWindow.Instance.Dispatcher.BeginInvoke(new Action(delegate { AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write(exception.ToString(), TextTokenType.Text); MainWindow.Instance.SafeActiveTextView.ShowText(output); }))).IgnoreExceptions(); }
/// <summary> /// Handle exceptions by displaying the error message in the text view. /// </summary> public static void HandleExceptions(this Task task) { task.Catch <Exception>(exception => MainWindow.Instance.Dispatcher.BeginInvoke(new Action(delegate { AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write(exception.ToString()); Docking.DockWorkspace.Instance.ShowText(output); }))).IgnoreExceptions(); }
void LoadBaml(AvalonEditTextOutput output, CancellationToken cancellationToken) { var asm = this.Ancestors().OfType <AssemblyTreeNode>().First().LoadedAssembly; using var data = OpenStream(); XDocument xamlDocument = LoadIntoDocument(asm.GetPEFileOrNull(), asm.GetAssemblyResolver(), data, cancellationToken); output.Write(xamlDocument.ToString()); }
bool LoadBaml(AvalonEditTextOutput output, CancellationToken cancellationToken) { var asm = this.Ancestors().OfType <AssemblyTreeNode>().FirstOrDefault().LoadedAssembly; Data.Position = 0; XDocument xamlDocument = LoadIntoDocument(asm.GetPEFileOrNull(), asm.GetAssemblyResolver(), Data, cancellationToken); output.Write(xamlDocument.ToString()); return(true); }
bool LoadBaml(AvalonEditTextOutput output) { var asm = this.Ancestors().OfType <AssemblyTreeNode>().FirstOrDefault().LoadedAssembly; Data.Position = 0; XDocument xamlDocument = LoadIntoDocument(asm.GetAssemblyResolver(), asm.AssemblyDefinition, Data); output.Write(xamlDocument.ToString()); return(true); }
public override bool View(TabPageModel tabPage) { AvalonEditTextOutput output = new AvalonEditTextOutput(); IHighlightingDefinition highlighting = null; tabPage.ShowTextView(textView => textView.RunWithCancellation( token => Task.Factory.StartNew( () => { try { // cache read XAML because stream will be closed after first read if (xml == null) { using var data = OpenStream(); if (data == null) { output.Write("ILSpy: Failed opening resource stream."); output.WriteLine(); return(output); } using (var reader = new StreamReader(data)) { xml = reader.ReadToEnd(); } } output.Write(xml); highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } catch (Exception ex) { output.Write(ex.ToString()); } return(output); }, token) ).Then(t => textView.ShowNode(t, this, highlighting)) .HandleExceptions()); tabPage.SupportsLanguageSwitching = false; return(true); }
void LoadBaml(AvalonEditTextOutput output, CancellationToken cancellationToken) { var asm = this.Ancestors().OfType <AssemblyTreeNode>().First().LoadedAssembly; using var data = OpenStream(); BamlDecompilerTypeSystem typeSystem = new BamlDecompilerTypeSystem(asm.GetPEFileOrNull(), asm.GetAssemblyResolver()); var decompiler = new XamlDecompiler(typeSystem, new BamlDecompilerSettings()); decompiler.CancellationToken = cancellationToken; var result = decompiler.Decompile(data); output.Write(result.Xaml.ToString()); }
void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args) { if (args.NavigateTo != null) { bool found = false; if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal)) { string namespaceName = args.NavigateTo.Substring(2); foreach (LoadedAssembly asm in commandLineLoadedAssemblies) { AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm); if (asmNode != null) { NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName); if (nsNode != null) { found = true; SelectNode(nsNode); break; } } } } else { foreach (LoadedAssembly asm in commandLineLoadedAssemblies) { AssemblyDefinition def = asm.AssemblyDefinition; if (def != null) { MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def.MainModule, args.NavigateTo); if (mr != null) { found = true; JumpToReference(mr); break; } } } } if (!found) { AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write("Cannot find " + args.NavigateTo); decompilerTextView.ShowText(output); } } commandLineLoadedAssemblies.Clear(); // clear references once we don't need them anymore }
public override bool View(DecompilerTextView textView) { if (resElem.ResourceData.Code == ResourceTypeCode.String) { var output = new AvalonEditTextOutput(); output.Write((string)((BuiltInResourceData)resElem.ResourceData).Data, TextTokenType.Text); textView.ShowNode(output, this, null); return(true); } if (resElem.ResourceData.Code == ResourceTypeCode.ByteArray || resElem.ResourceData.Code == ResourceTypeCode.Stream) { var data = (byte[])((BuiltInResourceData)resElem.ResourceData).Data; return(ResourceTreeNode.View(this, textView, new MemoryStream(data), Name)); } return(base.View(textView)); }
void Window_RequestNavigate(object sender, RequestNavigateEventArgs e) { if (e.Uri.Scheme == "resource") { AvalonEditTextOutput output = new AvalonEditTextOutput(); using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath)) { using (StreamReader r = new StreamReader(s)) { string line; while ((line = r.ReadLine()) != null) { output.Write(line); output.WriteLine(); } } } ILSpy.MainWindow.Instance.TextView.ShowText(output); } }
public override RichText GetRichTextTooltip(IEntity entity) { var output = new AvalonEditTextOutput() { IgnoreNewLineAndIndent = true }; var disasm = CreateDisassembler(output, new DecompilationOptions()); switch (entity.SymbolKind) { case SymbolKind.TypeDefinition: disasm.DisassembleTypeHeader(entity.ParentModule.PEFile, (TypeDefinitionHandle)entity.MetadataToken); break; case SymbolKind.Field: disasm.DisassembleFieldHeader(entity.ParentModule.PEFile, (FieldDefinitionHandle)entity.MetadataToken); break; case SymbolKind.Property: case SymbolKind.Indexer: disasm.DisassemblePropertyHeader(entity.ParentModule.PEFile, (PropertyDefinitionHandle)entity.MetadataToken); break; case SymbolKind.Event: disasm.DisassembleEventHeader(entity.ParentModule.PEFile, (EventDefinitionHandle)entity.MetadataToken); break; case SymbolKind.Method: case SymbolKind.Operator: case SymbolKind.Constructor: case SymbolKind.Destructor: case SymbolKind.Accessor: disasm.DisassembleMethodHeader(entity.ParentModule.PEFile, (MethodDefinitionHandle)entity.MetadataToken); break; default: output.Write(GetDisplayName(entity, true, true, true)); break; } return(new DocumentHighlighter(output.GetDocument(), base.SyntaxHighlighting).HighlightLine(1).ToRichText()); }
public override void Execute(object parameter) { const int numRuns = 100; var language = MainWindow.Instance.CurrentLanguage; var nodes = MainWindow.Instance.SelectedNodes.ToArray(); var options = new DecompilationOptions(); MainWindow.Instance.TextView.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => { options.CancellationToken = ct; Stopwatch w = Stopwatch.StartNew(); for (int i = 0; i < numRuns; ++i) { foreach (var node in nodes) { node.Decompile(language, new PlainTextOutput(), options); } } w.Stop(); AvalonEditTextOutput output = new AvalonEditTextOutput(); double msPerRun = w.Elapsed.TotalMilliseconds / numRuns; output.Write($"Average time: {msPerRun.ToString("f1")}ms\n"); return output; }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions(); }
void Window_RequestNavigate(object sender, RequestNavigateEventArgs e) { if (e.Uri.Scheme == "resource") { AvalonEditTextOutput output = new AvalonEditTextOutput(); using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(dnSpy.StartUpClass), e.Uri.AbsolutePath)) { using (StreamReader r = new StreamReader(s)) { string line; while ((line = r.ReadLine()) != null) { output.Write(line, TextTokenType.Text); output.WriteLine(); } } } var textView = ILSpy.MainWindow.Instance.SafeActiveTextView; textView.ShowText(output); ILSpy.MainWindow.Instance.SetTitle(textView, e.Uri.AbsolutePath); e.Handled = true; } }
bool LoadBaml(AvalonEditTextOutput output) { var asm = this.Ancestors().OfType <AssemblyTreeNode>().FirstOrDefault().LoadedAssembly; AppDomain bamlDecompilerAppDomain = null; try { BamlDecompiler decompiler = CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, asm.FileName); MemoryStream bamlStream = new MemoryStream(); Data.Position = 0; Data.CopyTo(bamlStream); output.Write(decompiler.DecompileBaml(bamlStream, asm.FileName, new ConnectMethodDecompiler(asm), new AssemblyResolver(asm))); return(true); } finally { if (bamlDecompilerAppDomain != null) { AppDomain.Unload(bamlDecompilerAppDomain); } } }
public override bool View(DecompilerTextView textView) { AvalonEditTextOutput output = new AvalonEditTextOutput(); IHighlightingDefinition highlighting = null; textView.RunWithCancellation( token => Task.Factory.StartNew( () => { try { if (LoadBaml(output)) { highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml"); } } catch (Exception ex) { output.Write(ex.ToString()); } return(output); }), t => textView.ShowNode(t.Result, this, highlighting) ); return(true); }
internal static bool View(ILSpyTreeNode node, DecompilerTextView textView, Stream stream, string name) { if (stream == null || stream.Length >= DecompilerTextView.DefaultOutputLengthLimit) { return(false); } stream.Position = 0; FileType type = GuessFileType.DetectFileType(stream); if (type == FileType.Binary) { return(false); } stream.Position = 0; AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write(FileReader.OpenStream(stream, Encoding.UTF8).ReadToEnd(), TextTokenType.Text); string ext; if (type == FileType.Xml) { ext = ".xml"; } else { try { ext = Path.GetExtension(DecompilerTextView.CleanUpName(name)); } catch (ArgumentException) { ext = ".txt"; } } textView.ShowNode(output, node, HighlightingManager.Instance.GetDefinitionByExtension(ext)); return(true); }
async void NavigateOnLaunch(string navigateTo, string[] activeTreeViewPath, ILSpySettings spySettings, List <LoadedAssembly> relevantAssemblies) { var initialSelection = treeView.SelectedItem; if (navigateTo != null) { bool found = false; if (navigateTo.StartsWith("N:", StringComparison.Ordinal)) { string namespaceName = navigateTo.Substring(2); foreach (LoadedAssembly asm in relevantAssemblies) { AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm); if (asmNode != null) { // FindNamespaceNode() blocks the UI if the assembly is not yet loaded, // so use an async wait instead. await asm.GetPEFileAsync().Catch <Exception>(ex => { }); NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName); if (nsNode != null) { found = true; if (treeView.SelectedItem == initialSelection) { SelectNode(nsNode); } break; } } } } else if (navigateTo == "none") { // Don't navigate anywhere; start empty. // Used by ILSpy VS addin, it'll send us the real location to navigate to via IPC. found = true; } else { IEntity mr = await Task.Run(() => FindEntityInRelevantAssemblies(navigateTo, relevantAssemblies)); if (mr != null && mr.ParentModule.PEFile != null) { found = true; if (treeView.SelectedItem == initialSelection) { JumpToReference(mr); } } } if (!found && treeView.SelectedItem == initialSelection) { AvalonEditTextOutput output = new AvalonEditTextOutput(); output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", navigateTo)); decompilerTextView.ShowText(output); } } else if (relevantAssemblies.Count == 1) { // NavigateTo == null and an assembly was given on the command-line: // Select the newly loaded assembly AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(relevantAssemblies[0]); if (asmNode != null && treeView.SelectedItem == initialSelection) { SelectNode(asmNode); } } else if (spySettings != null) { SharpTreeNode node = null; if (activeTreeViewPath?.Length > 0) { foreach (var asm in assemblyList.GetAssemblies()) { if (asm.FileName == activeTreeViewPath[0]) { // FindNodeByPath() blocks the UI if the assembly is not yet loaded, // so use an async wait instead. await asm.GetPEFileAsync().Catch <Exception>(ex => { }); } } node = FindNodeByPath(activeTreeViewPath, true); } if (treeView.SelectedItem == initialSelection) { if (node != null) { SelectNode(node); // only if not showing the about page, perform the update check: await ShowMessageIfUpdatesAvailableAsync(spySettings); } else { AboutPage.Display(decompilerTextView); } } } }