-
Notifications
You must be signed in to change notification settings - Fork 167
/
AssemblyTreeNode.cs
572 lines (513 loc) · 19.3 KB
/
AssemblyTreeNode.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
// Copyright (c) 2011 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.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.ILSpy.TextView;
using ICSharpCode.TreeView;
using Microsoft.Win32;
using ICSharpCode.Decompiler.TypeSystem;
using TypeDefinitionHandle = System.Reflection.Metadata.TypeDefinitionHandle;
using System.Text;
using ICSharpCode.ILSpy.Properties;
namespace ICSharpCode.ILSpy.TreeNodes
{
/// <summary>
/// Tree node representing an assembly.
/// This class is responsible for loading both namespace and type nodes.
/// </summary>
public sealed class AssemblyTreeNode : ILSpyTreeNode
{
readonly Dictionary<string, NamespaceTreeNode> namespaces = new Dictionary<string, NamespaceTreeNode>();
readonly Dictionary<TypeDefinitionHandle, TypeTreeNode> typeDict = new Dictionary<TypeDefinitionHandle, TypeTreeNode>();
ICompilation typeSystem;
public AssemblyTreeNode(LoadedAssembly assembly)
{
this.LoadedAssembly = assembly ?? throw new ArgumentNullException(nameof(assembly));
assembly.ContinueWhenLoaded(OnAssemblyLoaded, TaskScheduler.FromCurrentSynchronizationContext());
this.LazyLoading = true;
}
public AssemblyList AssemblyList {
get { return LoadedAssembly.AssemblyList; }
}
public LoadedAssembly LoadedAssembly { get; }
public override bool IsAutoLoaded {
get {
return LoadedAssembly.IsAutoLoaded;
}
}
public override object Text => LoadedAssembly.Text;
public override object Icon {
get {
if (LoadedAssembly.IsLoaded) {
return LoadedAssembly.HasLoadError ? Images.AssemblyWarning : Images.Assembly;
} else {
return Images.AssemblyLoading;
}
}
}
//TextBlock tooltip;
string tooltip;
public override object ToolTip {
get {
if (LoadedAssembly.HasLoadError)
return "Assembly could not be loaded. Click here for details.";
// TODO: AVALONIA: add inlines tooltip
//if (tooltip == null && LoadedAssembly.IsLoaded) {
// tooltip = new TextBlock();
// var module = LoadedAssembly.GetPEFileOrNull();
// var metadata = module?.Metadata;
// if (metadata?.IsAssembly == true) {
// tooltip.Inlines.Add(new Bold(new Run("Name: ")));
// tooltip.Inlines.Add(new Run(metadata.GetFullAssemblyName()));
// tooltip.Inlines.Add(new LineBreak());
// }
// tooltip.Inlines.Add(new Bold(new Run("Location: ")));
// tooltip.Inlines.Add(new Run(LoadedAssembly.FileName));
// tooltip.Inlines.Add(new LineBreak());
// tooltip.Inlines.Add(new Bold(new Run("Architecture: ")));
// tooltip.Inlines.Add(new Run(Language.GetPlatformDisplayName(module)));
// string runtimeName = Language.GetRuntimeDisplayName(module);
// if (runtimeName != null) {
// tooltip.Inlines.Add(new LineBreak());
// tooltip.Inlines.Add(new Bold(new Run("Runtime: ")));
// tooltip.Inlines.Add(new Run(runtimeName));
// }
// var debugInfo = LoadedAssembly.GetDebugInfoOrNull();
// tooltip.Inlines.Add(new LineBreak());
// tooltip.Inlines.Add(new Bold(new Run("Debug info: ")));
// tooltip.Inlines.Add(new Run(debugInfo?.Description ?? "none"));
//}
if (tooltip == null && LoadedAssembly.IsLoaded) {
var sb = new StringBuilder();
var module = LoadedAssembly.GetPEFileOrNull();
var metadata = module?.Metadata;
if (metadata?.IsAssembly == true) {
sb.Append("Name: ");
sb.Append(metadata.GetFullAssemblyName());
sb.AppendLine();
}
sb.Append("Location: ");
sb.Append(LoadedAssembly.FileName);
sb.AppendLine();
sb.Append("Architecture: ");
sb.Append(Language.GetPlatformDisplayName(module));
string runtimeName = Language.GetRuntimeDisplayName(module);
if (runtimeName != null)
{
sb.AppendLine();
sb.Append("Runtime: ");
sb.Append(runtimeName);
}
sb.AppendLine();
var debugInfo = LoadedAssembly.GetDebugInfoOrNull();
sb.AppendLine();
sb.Append("Debug info: ");
sb.Append(debugInfo?.Description ?? "none");
tooltip = sb.ToString();
}
return tooltip;
}
}
public override bool ShowExpander {
get { return !LoadedAssembly.HasLoadError; }
}
void OnAssemblyLoaded(Task<PEFile> moduleTask)
{
// change from "Loading" icon to final icon
RaisePropertyChanged("Icon");
RaisePropertyChanged("ExpandedIcon");
RaisePropertyChanged("Tooltip");
if (moduleTask.IsFaulted) {
RaisePropertyChanged("ShowExpander"); // cannot expand assemblies with load error
// observe the exception so that the Task's finalizer doesn't re-throw it
try { moduleTask.Wait(); } catch (AggregateException) { }
} else {
RaisePropertyChanged("Text"); // shortname might have changed
}
}
protected override void LoadChildren()
{
var module = LoadedAssembly.GetPEFileOrNull();
if (module == null) {
// if we crashed on loading, then we don't have any children
return;
}
typeSystem = LoadedAssembly.GetTypeSystemOrNull();
var assembly = (MetadataModule)typeSystem.MainModule;
var metadata = module.Metadata;
this.Children.Add(new ReferenceFolderTreeNode(module, this));
if (module.Resources.Any())
this.Children.Add(new ResourceListTreeNode(module));
foreach (NamespaceTreeNode ns in namespaces.Values) {
ns.Children.Clear();
}
foreach (var type in assembly.TopLevelTypeDefinitions.OrderBy(t => t.ReflectionName, NaturalStringComparer.Instance)) {
var escapedNamespace = Language.EscapeName(type.Namespace);
if (!namespaces.TryGetValue(type.Namespace, out NamespaceTreeNode ns)) {
ns = new NamespaceTreeNode(escapedNamespace);
namespaces.Add(type.Namespace, ns);
}
TypeTreeNode node = new TypeTreeNode(type, this);
typeDict[(TypeDefinitionHandle)type.MetadataToken] = node;
ns.Children.Add(node);
}
foreach (NamespaceTreeNode ns in namespaces.Values.OrderBy(n => n.Name, NaturalStringComparer.Instance)) {
if (ns.Children.Count > 0)
this.Children.Add(ns);
}
}
public override bool CanExpandRecursively => true;
/// <summary>
/// Finds the node for a top-level type.
/// </summary>
public TypeTreeNode FindTypeNode(ITypeDefinition type)
{
if (type == null)
return null;
EnsureLazyChildren();
TypeTreeNode node;
if (typeDict.TryGetValue((TypeDefinitionHandle)type.MetadataToken, out node))
return node;
else
return null;
}
/// <summary>
/// Finds the node for a namespace.
/// </summary>
public NamespaceTreeNode FindNamespaceNode(string namespaceName)
{
if (string.IsNullOrEmpty(namespaceName))
return null;
EnsureLazyChildren();
NamespaceTreeNode node;
if (namespaces.TryGetValue(namespaceName, out node))
return node;
else
return null;
}
public override bool CanDrag(SharpTreeNode[] nodes)
{
return nodes.All(n => n is AssemblyTreeNode);
}
public override void StartDrag(PointerEventArgs e, AvaloniaObject dragSource, SharpTreeNode[] nodes)
{
DragDrop.DoDragDrop(e, Copy(nodes), DragDropEffects.Copy | DragDropEffects.Link | DragDropEffects.Move);
}
public override bool CanDelete()
{
return true;
}
public override void Delete()
{
DeleteCore();
}
public override void DeleteCore()
{
LoadedAssembly.AssemblyList.Unload(LoadedAssembly);
}
internal const string DataFormat = "ILSpyAssemblies";
public override IDataObject Copy(SharpTreeNode[] nodes)
{
DataObject dataObject = new DataObject();
dataObject.Set(DataFormat, nodes.OfType<AssemblyTreeNode>().Select(n => n.LoadedAssembly.FileName).ToArray());
return dataObject;
}
public override FilterResult Filter(FilterSettings settings)
{
if (settings.SearchTermMatches(LoadedAssembly.ShortName))
return FilterResult.Match;
else
return FilterResult.Recurse;
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
void HandleException(Exception ex, string message)
{
language.WriteCommentLine(output, message);
output.WriteLine();
output.MarkFoldStart("Exception details", true);
output.Write(ex.ToString());
output.MarkFoldEnd();
}
try {
LoadedAssembly.WaitUntilLoaded(); // necessary so that load errors are passed on to the caller
} catch (AggregateException ex) {
language.WriteCommentLine(output, LoadedAssembly.FileName);
switch (ex.InnerException) {
case BadImageFormatException badImage:
HandleException(badImage, "This file does not contain a managed assembly.");
return;
case FileNotFoundException fileNotFound:
HandleException(fileNotFound, "The file was not found.");
return;
case DirectoryNotFoundException dirNotFound:
HandleException(dirNotFound, "The directory was not found.");
return;
case PEFileNotSupportedException notSupported:
HandleException(notSupported, notSupported.Message);
return;
default:
throw;
}
}
language.DecompileAssembly(LoadedAssembly, output, options);
}
public override async Task<bool> Save(DecompilerTextView textView)
{
Language language = this.Language;
if (string.IsNullOrEmpty(language.ProjectFileExtension))
return false;
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Save file";
dlg.InitialFileName = DecompilerTextView.CleanUpName(LoadedAssembly.ShortName);
dlg.Filters = new List<FileDialogFilter>()
{
new FileDialogFilter() { Name = language.Name + " project", Extensions = { language.ProjectFileExtension.TrimStart('.') } },
new FileDialogFilter() { Name = language.Name + " single file", Extensions = { language.FileExtension.TrimStart('.') }},
new FileDialogFilter() { Name = "All files", Extensions = { "*" }}
};
var filename = await dlg.ShowAsync(App.Current.GetMainWindow());
if (!string.IsNullOrEmpty(filename)) {
DecompilationOptions options = new DecompilationOptions();
options.FullDecompilation = true;
if (filename.Contains(language.ProjectFileExtension)) {
options.SaveAsProjectDirectory = Path.GetDirectoryName(filename);
foreach (string entry in Directory.GetFileSystemEntries(options.SaveAsProjectDirectory)) {
if (!string.Equals(entry, filename, StringComparison.OrdinalIgnoreCase)) {
var result = await MessageBox.Show(
Resources.AssemblySaveCodeDirectoryNotEmpty,
Resources.AssemblySaveCodeDirectoryNotEmptyTitle,
MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (result == MessageBoxResult.No)
return true; // don't save, but mark the Save operation as handled
break;
}
}
}
textView.SaveToDisk(language, new[] { this }, options, filename);
}
return true;
}
public override string ToString()
{
// ToString is used by FindNodeByPath/GetPathForNode
// Fixes #821 - Reload All Assemblies Should Point to the Correct Assembly
return LoadedAssembly.FileName;
}
}
[ExportContextMenuEntry(Header = nameof(Resources._Remove), Icon = "Images/Delete.png")]
sealed class RemoveAssembly : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.All(n => n is AssemblyTreeNode);
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var node in context.SelectedTreeNodes) {
node.Delete();
}
}
}
[ExportContextMenuEntry(Header = nameof(Resources._Reload), Icon = "Images/Refresh.png")]
sealed class ReloadAssembly : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.All(n => n is AssemblyTreeNode);
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
var paths = new List<string[]>();
using (context.TreeView.LockUpdates()) {
foreach (var node in context.SelectedTreeNodes) {
paths.Add(MainWindow.GetPathForNode(node));
var la = ((AssemblyTreeNode)node).LoadedAssembly;
la.AssemblyList.ReloadAssembly(la.FileName);
}
}
MainWindow.Instance.SelectNodes(paths.Select(p => MainWindow.Instance.FindNodeByPath(p, true)).ToArray());
MainWindow.Instance.RefreshDecompiledView();
}
}
[ExportContextMenuEntry(Header = nameof(Resources._LoadDependencies), Category = nameof(Resources.Dependencies))]
sealed class LoadDependencies : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.All(n => n is AssemblyTreeNode);
}
public bool IsEnabled(TextViewContext context)
{
return true;
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var node in context.SelectedTreeNodes) {
var la = ((AssemblyTreeNode)node).LoadedAssembly;
var module = la.GetPEFileOrNull();
if (module != null) {
var metadata = module.Metadata;
foreach (var assyRef in metadata.AssemblyReferences) {
la.LookupReferencedAssembly(new AssemblyReference(module, assyRef));
}
}
}
MainWindow.Instance.RefreshDecompiledView();
}
}
[ExportContextMenuEntry(Header = nameof(Resources._AddMainList), Category = nameof(Resources.Dependencies))]
sealed class AddToMainList : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.Where(n => n is AssemblyTreeNode).Any(n => ((AssemblyTreeNode)n).IsAutoLoaded);
}
public bool IsEnabled(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes.Where(n => n is AssemblyTreeNode).Any(n => !((AssemblyTreeNode)n).LoadedAssembly.FileName.StartsWith("nupkg://"));
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var node in context.SelectedTreeNodes) {
var loadedAssm = ((AssemblyTreeNode)node).LoadedAssembly;
if (!loadedAssm.HasLoadError && !loadedAssm.FileName.StartsWith("nupkg://")) {
loadedAssm.IsAutoLoaded = false;
node.RaisePropertyChanged("Foreground");
}
}
MainWindow.Instance.CurrentAssemblyList.RefreshSave();
}
}
[ExportContextMenuEntry(Header = nameof(Resources._OpenContainingFolder), Category = nameof(Resources.Shell))]
sealed class OpenContainingFolder : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
internal static AssemblyTreeNode GetAssemblyTreeNode(SharpTreeNode node)
{
while (node != null)
{
if (node is AssemblyTreeNode a)
return a;
node = node.Parent;
}
return null;
}
public bool IsEnabled(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var n in context.SelectedTreeNodes) {
var node = GetAssemblyTreeNode(n);
var path = Path.GetDirectoryName(node.LoadedAssembly.FileName);
if (Directory.Exists(path)) {
MainWindow.OpenFolder(path);
}
}
}
}
[ExportContextMenuEntry(Header = nameof(Resources._OpenCommandLineHere), Category = nameof(Resources.Shell))]
sealed class OpenCmdHere : IContextMenuEntry
{
public bool IsVisible(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = OpenContainingFolder.GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
public bool IsEnabled(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return false;
return context.SelectedTreeNodes
.All(n => {
var a = OpenContainingFolder.GetAssemblyTreeNode(n);
return a != null && File.Exists(a.LoadedAssembly.FileName);
});
}
public void Execute(TextViewContext context)
{
if (context.SelectedTreeNodes == null)
return;
foreach (var n in context.SelectedTreeNodes) {
var node = OpenContainingFolder.GetAssemblyTreeNode(n);
var path = Path.GetDirectoryName(node.LoadedAssembly.FileName);
if (Directory.Exists(path)) {
MainWindow.OpenCommandLine(path);
}
}
}
}
}