mirror of https://github.com/icsharpcode/ILSpy.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
172 lines
6.4 KiB
172 lines
6.4 KiB
// 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.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"/>. |
|
/// </summary> |
|
[ExportContextMenuEntry(Header = nameof(Resources.GeneratePortable), Category = "Debug", Icon = "Images/ProgramDebugDatabase", Order = 410)] |
|
[Shared] |
|
public sealed class GeneratePdbContextMenuEntry : IContextMenuEntry |
|
{ |
|
readonly DockWorkspace dockWorkspace; |
|
|
|
[ImportingConstructor] |
|
public GeneratePdbContextMenuEntry(DockWorkspace dockWorkspace) |
|
{ |
|
this.dockWorkspace = dockWorkspace; |
|
} |
|
|
|
public bool IsEnabled(TextViewContext context) => true; |
|
|
|
public bool IsVisible(TextViewContext context) |
|
{ |
|
var selectedNodes = context.SelectedTreeNodes; |
|
return selectedNodes?.Length > 0 |
|
&& selectedNodes.All(n => n is AssemblyTreeNode asm && asm.LoadedAssembly.IsLoadedAsValidAssembly); |
|
} |
|
|
|
public void Execute(TextViewContext context) |
|
{ |
|
var selectedNodes = context.SelectedTreeNodes?.OfType<AssemblyTreeNode>().ToArray(); |
|
if (selectedNodes == null || selectedNodes.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. |
|
} |
|
} |
|
} |
|
}
|
|
|