-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAssemblyLoadDebuggerControlViewModel.cs
387 lines (334 loc) · 13.3 KB
/
AssemblyLoadDebuggerControlViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace ToolWindow
{
public class AssemblyLoadDebuggerControlViewModel : INotifyPropertyChanged
{
private string _tempDirectory;
private bool _isCapturing;
private string _selectedBreakCondition;
private string _userEntryBreakCondition;
private string _searchString;
private string _applicationInfo;
public event PropertyChangedEventHandler PropertyChanged;
private Settings _settings;
public AssemblyLoadDebuggerControlViewModel()
{
_applicationInfo = $"Window Title: {Process.GetCurrentProcess().MainWindowTitle} (Process ID: {Process.GetCurrentProcess().Id}){Environment.NewLine}";
_applicationInfo += $"Main Module File: {Process.GetCurrentProcess().MainModule.FileName}{Environment.NewLine}";
_applicationInfo += $"Main Module Version: {Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion}{Environment.NewLine}";
Events = new ObservableCollection<string>();
FilteredEvents = CollectionViewSource.GetDefaultView(Events);
FilteredEvents.Filter = FilterEvents;
string tempFile = Path.GetTempFileName();
File.Delete(tempFile);
Directory.CreateDirectory(tempFile);
_tempDirectory = tempFile;
_settings = Settings.FromFile(SettingsFilePath);
OpenLogCommand = ActionCommand.From<string>(file =>
{
DTE2 dte = ServiceProvider.GlobalProvider.GetService(typeof(SDTE)) as DTE2;
dte?.ItemOperations?.OpenFile($@"{_tempDirectory}\{file.Replace(": ", "-")}.txt");
});
ToggleCaptureCommand = ActionCommand.From(ToggleCapture);
AddBreakConditionCommand = ActionCommand.From(AddBreakCondition, CanAddBreakCondition, false);
RemoveBreakConditionCommand = ActionCommand.From(RemoveBreakCondition, CanRemoveBreakCondition, false);
ClearAllBreakpointsCommand = ActionCommand.From(ClearAllBreakpoints, CanClearAllBreakpointsCondition, false);
ClearEntriesCommand = ActionCommand.From(ClearEntries);
CopyEntriesCommand = ActionCommand.From(CopyEntries);
if (IsAutoCapturing)
{
ToggleCapture();
}
}
private string _settingsFilePath;
private string SettingsFilePath
{
get
{
if (_settingsFilePath == null)
{
var shell = ServiceProvider.GlobalProvider.GetService(typeof(SVsShell)) as IVsShell;
object oPath;
shell.GetProperty((int)__VSSPROPID4.VSSPROPID_LocalAppDataDir, out oPath);
string localVsDataPath = (oPath is string) ? (string)oPath : Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_settingsFilePath = Path.Combine(localVsDataPath, "AssemblyLoadDebuggerSettings.json");;
}
return _settingsFilePath;
}
}
internal void Close()
{
_settings?.SaveSettings(SettingsFilePath);
if (Directory.Exists(_tempDirectory))
{
try
{
Directory.Delete(_tempDirectory, recursive: true);
}
catch
{
}
}
}
private void ClearEntries()
{
Events.Clear();
}
private void CopyEntries()
{
StringBuilder sb = new StringBuilder();
foreach(string evt in FilteredEvents)
{
sb.AppendLine(evt);
sb.AppendLine(File.ReadAllText($@"{_tempDirectory}\{evt}.txt"));
}
if (sb.Length > 0)
{
SetClipboardText(sb.ToString());
}
}
private void SetClipboardText(string text)
{
int retries = 2;
while(retries-- > 0)
{
try
{
Clipboard.SetText(text);
return;
}
catch (ExternalException)
{
}
System.Threading.Thread.Sleep(50);
}
}
private bool FilterEvents(object obj)
{
if (string.IsNullOrWhiteSpace(SearchString))
{
return true;
}
string evt = (string)obj;
return evt.IndexOf(SearchString, StringComparison.OrdinalIgnoreCase) > -1;
}
public string SearchString
{
get { return _searchString; }
set
{
_searchString = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SearchString)));
FilteredEvents.Refresh();
}
}
public string CaptureButtonText
{
get
{
return IsCapturing ? "Stop Capture" : "Capture";
}
}
private bool CanAddBreakCondition()
{
return !string.IsNullOrWhiteSpace(UserEntryBreakCondition);
}
private bool CanRemoveBreakCondition()
{
return SelectedBreakCondition != null;
}
private bool CanClearAllBreakpointsCondition()
{
return BreakOn?.Count > 0;
}
private void AddBreakCondition()
{
BreakOn.Add(UserEntryBreakCondition.Trim());
BreakOn = new List<string>(BreakOn);
UserEntryBreakCondition = null;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(BreakOn)));
}
public bool IsCapturing
{
get { return _isCapturing; }
set
{
_isCapturing = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsCapturing)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CaptureButtonText)));
}
}
public bool IsAutoCapturing
{
get
{
return _settings.AutoCapture;
}
set
{
_settings.AutoCapture = value;
}
}
private void RemoveBreakCondition()
{
BreakOn.Remove(SelectedBreakCondition);
BreakOn = new List<string>(BreakOn);
SelectedBreakCondition = null;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(BreakOn)));
}
private void ClearAllBreakpoints()
{
BreakOn = new List<string>();
SelectedBreakCondition = null;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(BreakOn)));
}
public List<string> BreakOn
{
get
{
return _settings.BreakPoints;
}
private set
{
_settings.BreakPoints = value;
}
}
private void ToggleCapture()
{
IsCapturing = !_isCapturing;
if (_isCapturing)
{
AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoaded;
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
}
else
{
AppDomain.CurrentDomain.AssemblyLoad -= OnAssemblyLoaded;
AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve;
}
}
private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
BreakIfAssemblyMatches(args.Name);
string s = _applicationInfo;
s += $"Managed thread ID: {Thread.CurrentThread.ManagedThreadId}{Environment.NewLine}";
s += $"Requested name: {args.Name}{Environment.NewLine}";
s += $"Requesting assembly: {args.RequestingAssembly?.FullName ?? "(Unknown)"}{Environment.NewLine}";
s += $"Time: {DateTime.Now}{Environment.NewLine}";
s += new StackTrace(3, true).ToString();
Application.Current.Dispatcher.BeginInvoke((Action)(() => Events.Add("BIND: " + args.Name)), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
using (Stream str = File.OpenWrite($@"{_tempDirectory}\BIND-{args.Name}.txt"))
using (StreamWriter w = new StreamWriter(str, Encoding.UTF8, 8192, true))
{
w.WriteLine(s);
}
return null;
}
[DebuggerStepThrough]
private void OnAssemblyLoaded(object sender, AssemblyLoadEventArgs args)
{
BreakIfAssemblyMatches(args.LoadedAssembly.FullName);
AssemblyName name = args.LoadedAssembly.GetName();
string s = _applicationInfo;
s += $"Managed thread ID: {Thread.CurrentThread.ManagedThreadId}{Environment.NewLine}";
s += $"Image: {args.LoadedAssembly.FullName}{Environment.NewLine}";
s += $"Codebase: {args.LoadedAssembly.CodeBase}{Environment.NewLine}";
s += $"Location: {args.LoadedAssembly.Location}{Environment.NewLine}";
s += $"Name: {name.Name}{Environment.NewLine}";
s += $"Version: {name.Version}{Environment.NewLine}";
s += $"Architecture: {name.ProcessorArchitecture}{Environment.NewLine}";
s += $"Culture: {name.CultureName}{Environment.NewLine}";
byte[] publicKey = name.GetPublicKey();
if (publicKey != null)
{
string hex = string.Join("", publicKey.Select(x => x.ToString("X2")));
s += $"Public Key: {hex}{Environment.NewLine}";
s += $"Hash Algorithm: {name.HashAlgorithm}{Environment.NewLine}";
}
s += $"Image Runtime Version: {args.LoadedAssembly.ImageRuntimeVersion}{Environment.NewLine}";
s += $"Flags: {name.Flags}{Environment.NewLine}";
s += $"Is Dynamic: {args.LoadedAssembly.IsDynamic}{Environment.NewLine}";
s += $"Is Fully Trusted: {args.LoadedAssembly.IsFullyTrusted}{Environment.NewLine}";
s += $"Reflection Only: {args.LoadedAssembly.ReflectionOnly}{Environment.NewLine}";
s += $"Time: {DateTime.Now}{Environment.NewLine}";
s += new StackTrace(3, true).ToString();
Application.Current.Dispatcher.BeginInvoke((Action)(() => Events.Add(args.LoadedAssembly.FullName)), System.Windows.Threading.DispatcherPriority.ApplicationIdle);
using (Stream str = File.OpenWrite($@"{_tempDirectory}\{args.LoadedAssembly.FullName}.txt"))
using (StreamWriter w = new StreamWriter(str, Encoding.UTF8, 8192, true))
{
w.WriteLine(s);
}
}
private void BreakIfAssemblyMatches(string assemblyName)
{
if (BreakOn.Any(x =>
{
try
{
return Regex.IsMatch(assemblyName, x, RegexOptions.IgnoreCase);
}
catch
{
return false;
}
}))
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
else
{
Debugger.Launch();
}
}
}
public ObservableCollection<string> Events { get; }
public static AssemblyLoadDebuggerControlViewModel Instance { get; } = new AssemblyLoadDebuggerControlViewModel();
public ICommand ToggleCaptureCommand { get; }
public ICommand OpenLogCommand { get; }
public ICommand AddBreakConditionCommand { get; }
public ICommand RemoveBreakConditionCommand { get; }
public ICommand ClearAllBreakpointsCommand { get; }
public ICommand ClearEntriesCommand { get; }
public ICommand CopyEntriesCommand { get; }
public ICollectionView FilteredEvents { get; }
public string SelectedBreakCondition
{
get { return _selectedBreakCondition; }
set
{
_selectedBreakCondition = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedBreakCondition)));
RemoveBreakConditionCommand.CanExecute(value);
}
}
public string UserEntryBreakCondition
{
get { return _userEntryBreakCondition; }
set
{
_userEntryBreakCondition = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(UserEntryBreakCondition)));
AddBreakConditionCommand.CanExecute(value);
}
}
}
}