|
1 | | -using ClrDebug; |
| 1 | +using System.Reflection.PortableExecutable; |
| 2 | +using ClrDebug; |
| 3 | +using ICSharpCode.Decompiler; |
| 4 | +using ICSharpCode.Decompiler.CSharp; |
| 5 | +using ICSharpCode.Decompiler.CSharp.Transforms; |
| 6 | +using ICSharpCode.Decompiler.DebugInfo; |
| 7 | +using ICSharpCode.Decompiler.Metadata; |
| 8 | +using SharpDbg.Infrastructure.Debugger.Decompilation; |
2 | 9 |
|
3 | 10 | namespace SharpDbg.Infrastructure.Debugger; |
4 | 11 |
|
| 12 | +public readonly record struct SourceInfo(string FilePath, int StartLine, int StartColumn, DecompiledSourceInfo? DecompilationReproductionInfo); |
| 13 | +public class DecompiledSourceInfo |
| 14 | +{ |
| 15 | + public required string TypeFullName { get; init; } |
| 16 | + public required AssemblyPathAndMvid Assembly { get; init; } |
| 17 | + public required string CallingUserCodeAssemblyPath { get; init; } |
| 18 | +} |
| 19 | +public record struct AssemblyPathAndMvid(string AssemblyPath, Guid Mvid); |
5 | 20 | public partial class ManagedDebugger |
6 | 21 | { |
7 | 22 | /// This appears to be 1 based, ie requires no adjustment when returned to the user |
8 | | - private (string FilePath, int StartLine, int StartColumn)? GetSourceInfoAtFrame(CorDebugFrame frame) |
| 23 | + private SourceInfo? GetSourceInfoAtFrame(CorDebugFrame frame) |
9 | 24 | { |
10 | 25 | if (frame is not CorDebugILFrame ilFrame) |
11 | 26 | throw new InvalidOperationException("Active frame is not an IL frame"); |
12 | 27 | var function = ilFrame.Function; |
13 | 28 | var module = _modules[function.Module.BaseAddress]; |
| 29 | + if (module.SymbolReader is null) |
| 30 | + { |
| 31 | + if (module.IsUserCode) throw new InvalidOperationException("The module we are decompiling is user code - this should never happen, we should only be decompiling non user code modules"); |
| 32 | + // No PDB on disk — generate one via decompilation and update the module entry |
| 33 | + var result = GetCachedOrGeneratePdb(module); |
| 34 | + if (result is not null) |
| 35 | + { |
| 36 | + module.SymbolReader = result; |
| 37 | + module.SymbolReaderFromDecompiled = true; |
| 38 | + } |
| 39 | + } |
| 40 | + |
14 | 41 | if (module.SymbolReader is not null) |
15 | 42 | { |
16 | 43 | var ilOffset = ilFrame.IP.pnOffset; |
17 | 44 | var methodToken = function.Token; |
18 | 45 | var sourceInfo = module.SymbolReader.GetSourceLocationForOffset(methodToken, ilOffset); |
19 | 46 | if (sourceInfo != null) |
20 | 47 | { |
21 | | - return (sourceInfo.Value.sourceFilePath, sourceInfo.Value.startLine, sourceInfo.Value.startColumn); |
| 48 | + DecompiledSourceInfo? decompiledSourceInfo = null; |
| 49 | + if (module.SymbolReaderFromDecompiled) |
| 50 | + { |
| 51 | + var metadataImport = module.Module.GetMetaDataInterface().MetaDataImport; |
| 52 | + var mvid = metadataImport.ScopeProps.pmvid; |
| 53 | + var containingTypeDef = metadataImport.GetMethodProps(methodToken).pClass; |
| 54 | + var typeProps = metadataImport.GetTypeDefProps(containingTypeDef); |
| 55 | + var typeName = typeProps.szTypeDef; |
| 56 | + |
| 57 | + string? callingUserCodeAssemblyPath = null; |
| 58 | + var caller = frame.Caller; |
| 59 | + while (callingUserCodeAssemblyPath is null) |
| 60 | + { |
| 61 | + if (caller is null) break; |
| 62 | + |
| 63 | + if (caller is CorDebugILFrame callerIlFrame) |
| 64 | + { |
| 65 | + var callerFunction = callerIlFrame.Function; |
| 66 | + var callerModule = _modules[callerFunction.Module.BaseAddress]; |
| 67 | + if (callerModule.IsUserCode) |
| 68 | + { |
| 69 | + callingUserCodeAssemblyPath = callerModule.ModulePath; |
| 70 | + break; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + caller = caller.Caller; |
| 75 | + } |
| 76 | + |
| 77 | + decompiledSourceInfo = new DecompiledSourceInfo |
| 78 | + { |
| 79 | + TypeFullName = typeName, |
| 80 | + Assembly = new AssemblyPathAndMvid(module.ModulePath, mvid), |
| 81 | + CallingUserCodeAssemblyPath = callingUserCodeAssemblyPath ?? throw new InvalidOperationException("Could not find a user code caller in the call stack") |
| 82 | + }; |
| 83 | + } |
| 84 | + |
| 85 | + return new SourceInfo(sourceInfo.Value.sourceFilePath, sourceInfo.Value.startLine, sourceInfo.Value.startColumn, decompiledSourceInfo); |
22 | 86 | } |
23 | 87 | } |
24 | 88 |
|
25 | 89 | return null; |
26 | 90 | } |
| 91 | + |
| 92 | + private SymbolReader? GetCachedOrGeneratePdb(ModuleInfo moduleInfo) |
| 93 | + { |
| 94 | + var sharpIdeSymbolCachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp", "SharpIdeSymbolCache"); |
| 95 | + var metadataImport = moduleInfo.Module.GetMetaDataInterface().MetaDataImport; |
| 96 | + var mvid = metadataImport.ScopeProps.pmvid; |
| 97 | + var assemblyName = Path.GetFileNameWithoutExtension(moduleInfo.ModuleName); |
| 98 | + var pdbPath = Path.Combine(sharpIdeSymbolCachePath, assemblyName, mvid.ToString(), $"{assemblyName}.decompiled.pdb"); |
| 99 | + if (File.Exists(pdbPath)) |
| 100 | + { |
| 101 | + var symbolReader = SymbolReader.TryLoadWithPdbPath(moduleInfo.ModulePath, pdbPath); |
| 102 | + if (symbolReader is null) |
| 103 | + { |
| 104 | + _logger?.Invoke($"GetCachedOrGeneratePdb: SymbolReader could not load cached PDB '{pdbPath}'"); |
| 105 | + return null; |
| 106 | + } |
| 107 | + return symbolReader; |
| 108 | + } |
| 109 | + return GeneratePdb(moduleInfo, pdbPath); |
| 110 | + } |
| 111 | + |
| 112 | + |
| 113 | + private SymbolReader? GeneratePdb(ModuleInfo moduleInfo, string pdbPathToWriteTo) |
| 114 | + { |
| 115 | + var assemblyPath = moduleInfo.ModulePath; |
| 116 | + if (!File.Exists(assemblyPath)) return null; |
| 117 | + |
| 118 | + var allModulePaths = _modules.Values.Select(m => m.ModulePath).Where(p => !string.IsNullOrEmpty(p)).ToList(); |
| 119 | + var resolver = new DebuggingAssemblyResolver(allModulePaths); |
| 120 | + |
| 121 | + PEFile file; |
| 122 | + try |
| 123 | + { |
| 124 | + file = new PEFile(assemblyPath, PEStreamOptions.PrefetchEntireImage); |
| 125 | + } |
| 126 | + catch (Exception ex) |
| 127 | + { |
| 128 | + _logger?.Invoke($"GeneratePdb: failed to open PE file '{assemblyPath}': {ex.Message}"); |
| 129 | + return null; |
| 130 | + } |
| 131 | + |
| 132 | + using (file) |
| 133 | + { |
| 134 | + var decompilerSettings = new DecompilerSettings(); |
| 135 | + var decompiler = new CSharpDecompiler(file, resolver, decompilerSettings) |
| 136 | + { |
| 137 | + AstTransforms = { |
| 138 | + new TransformFieldAndConstructorInitializers(), |
| 139 | + new AddXmlDocumentationTransform(), |
| 140 | + new EscapeInvalidIdentifiers(), |
| 141 | + new FixNameCollisions(), |
| 142 | + new ReplaceMethodCallsWithOperators() |
| 143 | + } |
| 144 | + }; |
| 145 | + |
| 146 | + _logger?.Invoke($"GeneratePdb: writing PDB to '{pdbPathToWriteTo}' for '{assemblyPath}'"); |
| 147 | + try |
| 148 | + { |
| 149 | + var pdbDirectory = Path.GetDirectoryName(pdbPathToWriteTo)!; |
| 150 | + if (!Directory.Exists(pdbDirectory)) Directory.CreateDirectory(pdbDirectory); |
| 151 | + using var pdbStream = File.Create(pdbPathToWriteTo); |
| 152 | + // noLogo: true until https://github.com/icsharpcode/ILSpy/pull/3667 is merged |
| 153 | + PortablePdbWriter.WritePdb(file, decompiler, decompilerSettings, pdbStream, noLogo: true); |
| 154 | + } |
| 155 | + catch (Exception ex) |
| 156 | + { |
| 157 | + _logger?.Invoke($"GeneratePdb: exception writing PDB: {ex}"); |
| 158 | + return null; |
| 159 | + } |
| 160 | + |
| 161 | + var symbolReader = SymbolReader.TryLoadWithPdbPath(assemblyPath, pdbPathToWriteTo); |
| 162 | + if (symbolReader is null) |
| 163 | + { |
| 164 | + _logger?.Invoke($"GeneratePdb: SymbolReader could not load generated PDB '{pdbPathToWriteTo}'"); |
| 165 | + return null; |
| 166 | + } |
| 167 | + |
| 168 | + _logger?.Invoke($"GeneratePdb: successfully loaded generated PDB for '{Path.GetFileName(assemblyPath)}'"); |
| 169 | + return symbolReader; |
| 170 | + } |
| 171 | + } |
27 | 172 | } |
0 commit comments