Browse Source

Wire up the File-menu Generate portable PDB command

The File-menu entry was a stub that popped a "not implemented" dialog,
while the working generation logic lived only in the assembly context-
menu entry. Lift that logic into a shared PdbGenerator and route both
entry points through it, so the menu command now generates PDBs for the
selected assemblies (enabled only when the selection holds a valid one).
This was the last NotImplementedDialog caller, so the dialog is removed.

Assisted-by: Claude:claude-opus-4-8:Claude Code
pull/3755/head
Siegfried Pammer 4 weeks ago
parent
commit
08521c8236
  1. 78
      ILSpy.Tests/Commands/GeneratePdbCommandTests.cs
  2. 13
      ILSpy/Commands/FileCommands.cs
  3. 121
      ILSpy/Commands/GeneratePdbContextMenuEntry.cs
  4. 77
      ILSpy/Commands/NotImplementedDialog.cs
  5. 161
      ILSpy/Commands/PdbGenerator.cs

78
ILSpy.Tests/Commands/GeneratePdbCommandTests.cs

@ -0,0 +1,78 @@ @@ -0,0 +1,78 @@
// Copyright (c) 2026 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Threading.Tasks;
using Avalonia.Headless.NUnit;
using AwesomeAssertions;
using ICSharpCode.ILSpy.Properties;
using ILSpy.AppEnv;
using ILSpy.Commands;
using ILSpy.TreeNodes;
using NUnit.Framework;
namespace ICSharpCode.ILSpy.Tests.Commands;
/// <summary>
/// The File-menu "Generate portable PDB" command is wired to the real <see cref="PdbGenerator"/>
/// (it used to be a not-implemented stub). It is enabled exactly when the selection holds at least
/// one valid loaded assembly, the same gate the context-menu entry uses.
/// </summary>
[TestFixture]
public class GeneratePdbCommandTests
{
[AvaloniaTest]
public async Task Generate_Pdb_Command_Tracks_The_Assembly_Selection()
{
var (_, vm) = await TestHarness.BootAsync(3);
var command = AppComposition.Current.GetExport<MainMenuCommandRegistry>()
.GetCommand(nameof(Resources.GeneratePortable));
command.Should().NotBeNull("the File menu exposes a Generate portable PDB command");
vm.AssemblyTreeModel.SelectedItems.Clear();
command.CanExecute(null).Should().BeFalse("with nothing selected there is no assembly to write a PDB for");
var coreLib = vm.AssemblyTreeModel.FindCoreLib();
vm.AssemblyTreeModel.SelectedItems.Clear();
vm.AssemblyTreeModel.SelectedItems.Add(coreLib);
command.CanExecute(null).Should().BeTrue("a selected valid assembly enables the command");
}
[AvaloniaTest]
public async Task TryGetAssemblies_Picks_Only_Valid_Assembly_Nodes()
{
var (_, vm) = await TestHarness.BootAsync(3);
var coreLib = vm.AssemblyTreeModel.FindCoreLib();
PdbGenerator.TryGetAssemblies(new[] { coreLib }, out var assemblies).Should().BeTrue();
assemblies.Should().ContainSingle().Which.Should().BeSameAs(coreLib.LoadedAssembly);
// A non-assembly node (a child of the assembly) is not a candidate.
coreLib.Expand();
var nonAssembly = coreLib.Children[0];
(nonAssembly is AssemblyTreeNode).Should().BeFalse("a child of the assembly node is not itself an assembly");
PdbGenerator.TryGetAssemblies(new[] { nonAssembly }, out var none).Should().BeFalse();
none.Should().BeEmpty();
}
}

13
ILSpy/Commands/FileCommands.cs

@ -261,9 +261,18 @@ namespace ILSpy.Commands @@ -261,9 +261,18 @@ namespace ILSpy.Commands
[ExportMainMenuCommand(ParentMenuID = nameof(Resources._File), Header = nameof(Resources.GeneratePortable), MenuCategory = nameof(Resources.Save), MenuOrder = 22)]
[Shared]
sealed class GeneratePdbCommand : SimpleCommand
[method: ImportingConstructor]
sealed class GeneratePdbCommand(AssemblyTreeModel assemblyTreeModel, DockWorkspace dockWorkspace) : SimpleCommand
{
public override void Execute(object? parameter) => NotImplementedDialog.Show(Resources.GeneratePortable);
public override bool CanExecute(object? parameter)
=> PdbGenerator.TryGetAssemblies(assemblyTreeModel.SelectedItems, out _);
public override void Execute(object? parameter)
{
if (!PdbGenerator.TryGetAssemblies(assemblyTreeModel.SelectedItems, out var assemblies))
return;
PdbGenerator.GenerateAsync(assemblies, dockWorkspace).HandleExceptions();
}
}
[ExportMainMenuCommand(ParentMenuID = nameof(Resources._File), Header = nameof(Resources.E_xit), MenuOrder = 99999, MenuCategory = nameof(Resources.Exit))]

121
ILSpy/Commands/GeneratePdbContextMenuEntry.cs

@ -16,32 +16,19 @@ @@ -16,32 +16,19 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.CSharp.ProjectDecompiler;
using ICSharpCode.Decompiler.DebugInfo;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpyX;
using ILSpy.Docking;
using ILSpy.TextView;
using ILSpy.TreeNodes;
namespace ILSpy.Commands
{
/// <summary>
/// Right-click an assembly → "Generate Portable PDB". Picks an output folder, then
/// runs <see cref="PortablePdbWriter"/> for each selected assembly that has a
/// CodeView debug-directory entry. Output report (per-file success / fail / total
/// elapsed time) lands in the active decompiler tab via <see cref="DockWorkspace.ShowText"/>.
/// Right-click an assembly → "Generate Portable PDB". Delegates to <see cref="PdbGenerator"/>,
/// which is shared with the File-menu command of the same name.
/// </summary>
[ExportContextMenuEntry(Header = nameof(Resources.GeneratePortable), Category = "Debug", Icon = "Images/ProgramDebugDatabase", Order = 410)]
[Shared]
@ -66,107 +53,11 @@ namespace ILSpy.Commands @@ -66,107 +53,11 @@ namespace ILSpy.Commands
public void Execute(TextViewContext context)
{
var selectedNodes = context.SelectedTreeNodes?.OfType<AssemblyTreeNode>().ToArray();
if (selectedNodes == null || selectedNodes.Length == 0)
var assemblies = context.SelectedTreeNodes?.OfType<AssemblyTreeNode>()
.Select(n => n.LoadedAssembly).ToArray();
if (assemblies == null || assemblies.Length == 0)
return;
ExecuteAsync(selectedNodes.Select(n => n.LoadedAssembly).ToArray()).HandleExceptions();
}
async Task ExecuteAsync(LoadedAssembly[] assemblies)
{
// First pass: classify assemblies. Only those with a CodeView debug-directory
// entry can have a portable PDB generated by the writer; surface unsupported
// ones in the report rather than silently skipping.
var supported = new Dictionary<LoadedAssembly, PEFile>();
var unsupported = new List<LoadedAssembly>();
foreach (var a in assemblies)
{
try
{
if (a.GetMetadataFileOrNull() is PEFile file && PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
supported.Add(a, file);
else
unsupported.Add(a);
}
catch
{
unsupported.Add(a);
}
}
if (supported.Count == 0)
{
// Surface the failure via ShowText rather than a MessageBox — keeps the UX
// consistent with the rest of the long-running command surface.
var fail = new AvaloniaEditTextOutput { Title = "Generate Portable PDB" };
fail.Write(string.Format(Resources.CannotCreatePDBFile,
":" + Environment.NewLine + string.Join(Environment.NewLine, unsupported.Select(u => Path.GetFileName(u.FileName)))));
fail.WriteLine();
dockWorkspace.ShowText(fail);
return;
}
var folder = await FilePickers.PickFolderAsync(Resources.SelectPDBOutputFolder);
if (string.IsNullOrEmpty(folder))
return;
// Run in a dedicated frozen tab so browsing the tree while PDBs generate can't cancel it.
await dockWorkspace.RunInNewTabAsync(Resources.GeneratingPortablePDB, token => Task.Run(() => {
var output = new AvaloniaEditTextOutput { Title = "Generate Portable PDB" };
var totalWatch = Stopwatch.StartNew();
foreach (var (assembly, file) in supported)
{
var pdbFileName = Path.Combine(folder, WholeProjectDecompiler.CleanUpFileName(assembly.ShortName, ".pdb"));
try
{
using var stream = new FileStream(pdbFileName, FileMode.Create, FileAccess.Write);
var resolver = assembly.GetAssemblyResolver();
var settings = new ICSharpCode.Decompiler.DecompilerSettings();
var decompiler = new CSharpDecompiler(file, resolver, settings) {
CancellationToken = token,
};
new PortablePdbWriter().WritePdb(file, decompiler, settings, stream);
output.Write(string.Format(Resources.GeneratedPDBFile, pdbFileName));
output.WriteLine();
}
catch (OperationCanceledException)
{
output.WriteLine();
output.Write(Resources.GenerationWasCancelled);
output.WriteLine();
throw;
}
catch (Exception ex)
{
output.Write(string.Format(Resources.GenerationFailedForAssembly, assembly.FileName, ex.Message));
output.WriteLine();
}
}
totalWatch.Stop();
output.WriteLine();
output.Write(string.Format(Resources.GenerationCompleteInSeconds, totalWatch.Elapsed.TotalSeconds.ToString("F1")));
output.WriteLine();
output.WriteLine();
output.AddButton(null, Resources.OpenExplorer, (_, _) => OpenFolder(folder));
output.WriteLine();
return output;
}, token)).ConfigureAwait(true);
}
static void OpenFolder(string path)
{
try
{
if (OperatingSystem.IsWindows())
Process.Start(new ProcessStartInfo("explorer.exe", $"\"{path}\"") { UseShellExecute = false });
else if (OperatingSystem.IsMacOS())
Process.Start(new ProcessStartInfo("open", $"\"{path}\"") { UseShellExecute = false });
else
Process.Start(new ProcessStartInfo("xdg-open", path) { UseShellExecute = false });
}
catch
{
// Best-effort.
}
PdbGenerator.GenerateAsync(assemblies, dockWorkspace).HandleExceptions();
}
}
}

77
ILSpy/Commands/NotImplementedDialog.cs

@ -1,77 +0,0 @@ @@ -1,77 +0,0 @@
// Copyright (c) 2026 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System.Linq;
using global::Avalonia.Controls;
using global::Avalonia.Controls.ApplicationLifetimes;
using global::Avalonia.Layout;
namespace ILSpy.Commands
{
/// <summary>
/// Lightweight modal "Not yet implemented" dialog. Used by menu commands whose underlying
/// feature (Options dialog, About page, GAC browser, save dialogs, &hellip;) isn't yet
/// available — the menu still surfaces the entry so the structure stays consistent, but
/// invocation tells the user clearly that the feature is unavailable.
/// </summary>
internal static class NotImplementedDialog
{
public static void Show(string feature)
{
var owner = (global::Avalonia.Application.Current?.ApplicationLifetime
as IClassicDesktopStyleApplicationLifetime)?.MainWindow;
var dialog = new Window {
Title = "ILSpy",
Width = 380,
Height = 140,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
CanResize = false,
ShowInTaskbar = false,
};
var ok = new Button {
Content = "OK",
IsDefault = true,
HorizontalAlignment = HorizontalAlignment.Right,
MinWidth = 80,
Margin = new global::Avalonia.Thickness(0, 16, 0, 0),
};
ok.Click += (_, _) => dialog.Close();
var stack = new StackPanel {
Margin = new global::Avalonia.Thickness(16),
Children = {
new TextBlock {
Text = $"\"{feature}\" hasn't been ported to the Avalonia UI yet.",
TextWrapping = global::Avalonia.Media.TextWrapping.Wrap,
},
ok,
},
};
dialog.Content = stack;
if (owner != null)
dialog.ShowDialog(owner);
else
dialog.Show();
}
}
}

161
ILSpy/Commands/PdbGenerator.cs

@ -0,0 +1,161 @@ @@ -0,0 +1,161 @@
// Copyright (c) 2026 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.CSharp.ProjectDecompiler;
using ICSharpCode.Decompiler.DebugInfo;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.Properties;
using ICSharpCode.ILSpyX;
using ICSharpCode.ILSpyX.TreeView;
using ILSpy.Docking;
using ILSpy.TextView;
using ILSpy.TreeNodes;
namespace ILSpy.Commands
{
/// <summary>
/// Shared "Generate Portable PDB" logic behind both the File-menu command and the
/// assembly-node context-menu entry: pick an output folder, then run
/// <see cref="PortablePdbWriter"/> for every selected assembly that carries a CodeView
/// debug-directory entry. The per-file report (success / fail / total elapsed time) lands
/// in a dedicated frozen tab via <see cref="DockWorkspace.RunInNewTabAsync"/>.
/// </summary>
internal static class PdbGenerator
{
/// <summary>
/// Picks the valid loaded assemblies out of <paramref name="nodes"/>. PDB generation is
/// gated further on the CodeView debug-directory entry at write time, so unsupported ones
/// are still surfaced (not silently dropped) by <see cref="GenerateAsync"/>.
/// </summary>
public static bool TryGetAssemblies(IReadOnlyList<SharpTreeNode>? nodes, out LoadedAssembly[] assemblies)
{
assemblies = nodes?.OfType<AssemblyTreeNode>()
.Where(n => n.LoadedAssembly.IsLoadedAsValidAssembly)
.Select(n => n.LoadedAssembly)
.ToArray() ?? [];
return assemblies.Length > 0;
}
public static async Task GenerateAsync(LoadedAssembly[] assemblies, DockWorkspace dockWorkspace)
{
// First pass: classify assemblies. Only those with a CodeView debug-directory
// entry can have a portable PDB generated by the writer; surface unsupported
// ones in the report rather than silently skipping.
var supported = new Dictionary<LoadedAssembly, PEFile>();
var unsupported = new List<LoadedAssembly>();
foreach (var a in assemblies)
{
try
{
if (a.GetMetadataFileOrNull() is PEFile file && PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
supported.Add(a, file);
else
unsupported.Add(a);
}
catch
{
unsupported.Add(a);
}
}
if (supported.Count == 0)
{
// Surface the failure via ShowText rather than a MessageBox -- keeps the UX
// consistent with the rest of the long-running command surface.
var fail = new AvaloniaEditTextOutput { Title = "Generate Portable PDB" };
fail.Write(string.Format(Resources.CannotCreatePDBFile,
":" + Environment.NewLine + string.Join(Environment.NewLine, unsupported.Select(u => Path.GetFileName(u.FileName)))));
fail.WriteLine();
dockWorkspace.ShowText(fail);
return;
}
var folder = await FilePickers.PickFolderAsync(Resources.SelectPDBOutputFolder);
if (string.IsNullOrEmpty(folder))
return;
// Run in a dedicated frozen tab so browsing the tree while PDBs generate can't cancel it.
await dockWorkspace.RunInNewTabAsync(Resources.GeneratingPortablePDB, token => Task.Run(() => {
var output = new AvaloniaEditTextOutput { Title = "Generate Portable PDB" };
var totalWatch = Stopwatch.StartNew();
foreach (var (assembly, file) in supported)
{
var pdbFileName = Path.Combine(folder, WholeProjectDecompiler.CleanUpFileName(assembly.ShortName, ".pdb"));
try
{
using var stream = new FileStream(pdbFileName, FileMode.Create, FileAccess.Write);
var resolver = assembly.GetAssemblyResolver();
var settings = new DecompilerSettings();
var decompiler = new CSharpDecompiler(file, resolver, settings) {
CancellationToken = token,
};
new PortablePdbWriter().WritePdb(file, decompiler, settings, stream);
output.Write(string.Format(Resources.GeneratedPDBFile, pdbFileName));
output.WriteLine();
}
catch (OperationCanceledException)
{
output.WriteLine();
output.Write(Resources.GenerationWasCancelled);
output.WriteLine();
throw;
}
catch (Exception ex)
{
output.Write(string.Format(Resources.GenerationFailedForAssembly, assembly.FileName, ex.Message));
output.WriteLine();
}
}
totalWatch.Stop();
output.WriteLine();
output.Write(string.Format(Resources.GenerationCompleteInSeconds, totalWatch.Elapsed.TotalSeconds.ToString("F1")));
output.WriteLine();
output.WriteLine();
output.AddButton(null, Resources.OpenExplorer, (_, _) => OpenFolder(folder));
output.WriteLine();
return output;
}, token)).ConfigureAwait(true);
}
static void OpenFolder(string path)
{
try
{
if (OperatingSystem.IsWindows())
Process.Start(new ProcessStartInfo("explorer.exe", $"\"{path}\"") { UseShellExecute = false });
else if (OperatingSystem.IsMacOS())
Process.Start(new ProcessStartInfo("open", $"\"{path}\"") { UseShellExecute = false });
else
Process.Start(new ProcessStartInfo("xdg-open", path) { UseShellExecute = false });
}
catch
{
// Best-effort.
}
}
}
}
Loading…
Cancel
Save