-
Notifications
You must be signed in to change notification settings - Fork 219
/
Natvis.cs
executable file
·1390 lines (1302 loc) · 60.6 KB
/
Natvis.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using MICore;
using Microsoft.DebugEngineHost;
using Microsoft.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Debugger.Interop.DAP;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
namespace Microsoft.MIDebugEngine.Natvis
{
internal class SimpleWrapper : IVariableInformation
{
public SimpleWrapper(string name, AD7Engine engine, IVariableInformation underlyingVariable)
{
Parent = underlyingVariable;
Name = name;
_engine = engine;
}
public readonly IVariableInformation Parent;
private AD7Engine _engine;
public string Name { get; private set; }
public string Value { get { return Parent.Value; } }
public virtual string TypeName { get { return Parent.TypeName; } }
public bool IsParameter { get { return Parent.IsParameter; } }
public VariableInformation[] Children { get { return Parent.Children; } }
public AD7Thread Client { get { return Parent.Client; } }
public bool Error { get { return Parent.Error; } }
public uint CountChildren { get { return Parent.CountChildren; } }
public bool IsChild { get { return Parent.IsChild; } set { Parent.IsChild = value; } }
public enum_DBG_ATTRIB_FLAGS Access { get { return Parent.Access; } }
public bool IsStringType { get { return Parent.IsStringType; } }
public ThreadContext ThreadContext { get { return Parent.ThreadContext; } }
public virtual bool IsVisualized { get { return Parent.IsVisualized; } }
public virtual enum_DEBUGPROP_INFO_FLAGS PropertyInfoFlags { get; set; }
public virtual bool IsReadOnly() => Parent.IsReadOnly();
public VariableInformation FindChildByName(string name) => Parent.FindChildByName(name);
public string EvalDependentExpression(string expr) => Parent.EvalDependentExpression(expr);
public void AsyncEval(IDebugEventCallback2 pExprCallback) => Parent.AsyncEval(pExprCallback);
public void SyncEval(enum_EVALFLAGS dwFlags, DAPEvalFlags dwDAPFlags) => Parent.SyncEval(dwFlags, dwDAPFlags);
public virtual string FullName() => Name;
public void EnsureChildren() => Parent.EnsureChildren();
public void AsyncError(IDebugEventCallback2 pExprCallback, IDebugProperty2 error)
{
VariableInformation.AsyncErrorImpl(pExprCallback != null ? new EngineCallback(_engine, pExprCallback) : _engine.Callback, this, error);
}
public void Dispose()
{
}
public bool IsPreformatted { get { return Parent.IsPreformatted; } set { } }
public string Address()
{
return Parent.Address();
}
public uint Size()
{
return Parent.Size();
}
}
internal class VisualizerWrapper : SimpleWrapper
{
public readonly Natvis.VisualizerInfo Visualizer;
private readonly bool _isVisualizerView;
public VisualizerWrapper(string name, AD7Engine engine, IVariableInformation underlyingVariable, Natvis.VisualizerInfo viz, bool isVisualizerView)
: base(name, engine, underlyingVariable)
{
Visualizer = viz;
_isVisualizerView = isVisualizerView;
}
public override bool IsVisualized { get { return _isVisualizerView; } }
public override string TypeName { get { return String.Empty; } }
public override string FullName()
{
return _isVisualizerView ? Parent.Name + ",viz" : Name;
}
}
/// <summary>
/// Represents a VisualizedWrapper that starts at an offset.
/// </summary>
internal class PaginatedVisualizerWrapper : VisualizerWrapper
{
public readonly uint StartIndex;
public PaginatedVisualizerWrapper(string name, AD7Engine engine, IVariableInformation underlyingVariable, Natvis.VisualizerInfo viz, bool isVisualizerView, uint startIndex=0)
: base(name, engine, underlyingVariable, viz, isVisualizerView)
{
StartIndex = startIndex;
}
}
/// <summary>
/// Represents the continuation of a LinkedListItemsType.
/// </summary>
internal sealed class LinkedListContinueWrapper : PaginatedVisualizerWrapper
{
public readonly IVariableInformation ContinueNode;
public LinkedListContinueWrapper(string name, AD7Engine engine, IVariableInformation underlyingVariable, Natvis.VisualizerInfo viz, bool isVisualizerView, IVariableInformation continueNode, uint startIndex)
: base(name, engine, underlyingVariable, viz, isVisualizerView, startIndex)
{
ContinueNode = continueNode;
}
}
internal class Node
{
public enum ScanState
{
left, value, right
}
public ScanState State { get; set; }
public IVariableInformation Content { get; private set; }
public Node(IVariableInformation v)
{
Content = v;
State = ScanState.left;
}
}
/// <summary>
/// Represents the continuation of a TreeItemsType.
/// </summary>
internal sealed class TreeContinueWrapper : PaginatedVisualizerWrapper
{
public readonly Node ContinueNode;
public readonly Stack<Node> Nodes;
public TreeContinueWrapper(string name, AD7Engine engine, IVariableInformation underlyingVariable, Natvis.VisualizerInfo viz, bool isVisualizerView, Node continueNode, Stack<Node> nodes, uint startIndex)
: base (name, engine, underlyingVariable, viz, isVisualizerView, startIndex)
{
ContinueNode = continueNode;
Nodes = nodes;
}
}
internal struct VisualizerId
{
public string Name { get; }
public int Id { get; }
public VisualizerId(string name,int id)
{
this.Name = name;
this.Id = id;
}
};
public class Natvis : IDisposable
{
private class AliasInfo
{
public TypeName ParsedName { get; private set; }
public AliasType Alias { get; private set; }
public AliasInfo(TypeName name, AliasType alias)
{
ParsedName = name;
Alias = alias;
}
}
private class TypeInfo
{
public TypeName ParsedName { get; private set; }
public VisualizerType Visualizer { get; private set; }
public TypeInfo(TypeName name, VisualizerType visualizer)
{
ParsedName = name;
Visualizer = visualizer;
}
}
private class FileInfo
{
public List<TypeInfo> Visualizers { get; private set; }
public List<AliasInfo> Aliases { get; private set; }
public List<UIVisualizerType> UIVisualizers { get; set; } = null;
public readonly AutoVisualizer Environment;
public FileInfo(AutoVisualizer env)
{
Environment = env;
Visualizers = new List<TypeInfo>();
Aliases = new List<AliasInfo>();
}
}
internal class VisualizerInfo
{
public VisualizerType Visualizer { get; private set; }
public Dictionary<string, string> ScopedNames { get; private set; }
public VisualizerId[] GetUIVisualizers()
{
return this.Visualizer.Items.Where((i) => i is UIVisualizerItemType).Select(i =>
{
var visualizer = (UIVisualizerItemType)i;
return new VisualizerId(visualizer.ServiceId, visualizer.Id);
}).ToArray();
}
public VisualizerInfo(VisualizerType viz, TypeName name)
{
Visualizer = viz;
// add the template parameter macro values
ScopedNames = new Dictionary<string, string>();
for (int i = 0; i < name.Args.Count; ++i)
{
ScopedNames["$T" + (i + 1).ToString(CultureInfo.InvariantCulture)] = name.Args[i].FullyQualifiedName;
}
}
}
private static Regex s_variableName = new Regex("[a-zA-Z$_][a-zA-Z$_0-9]*");
private static Regex s_subfieldNameHere = new Regex(@"\G((\.|->)[a-zA-Z$_][a-zA-Z$_0-9]*)+");
private static Regex s_expression = new Regex(@"^\{[^\}]*\}");
private List<FileInfo> _typeVisualizers;
private DebuggedProcess _process;
private HostConfigurationStore _configStore;
private Dictionary<string, VisualizerInfo> _vizCache;
private uint _depth;
public HostWaitDialog WaitDialog { get; private set; }
public VisualizationCache Cache { get; private set; }
private const uint MAX_EXPAND = 50;
private const int MAX_FORMAT_DEPTH = 10;
private const int MAX_ALIAS_CHAIN = 10;
private IDisposable _natvisSettingWatcher;
public enum DisplayStringsState
{
On,
Off,
ForVisualizedItems
}
public DisplayStringsState ShowDisplayStrings { get; set; }
internal Natvis(DebuggedProcess process, bool showDisplayString, HostConfigurationStore configStore)
{
_typeVisualizers = new List<FileInfo>();
_process = process;
_vizCache = new Dictionary<string, VisualizerInfo>();
WaitDialog = new HostWaitDialog(ResourceStrings.VisualizingExpressionMessage, ResourceStrings.VisualizingExpressionCaption);
ShowDisplayStrings = showDisplayString ? DisplayStringsState.On : DisplayStringsState.ForVisualizedItems; // don't compute display strings unless explicitly requested
_depth = 0;
Cache = new VisualizationCache();
_configStore = configStore;
}
private void InitializeNatvisServices()
{
try
{
_natvisSettingWatcher = HostNatvisProject.WatchNatvisOptionSetting(_configStore, _process.Logger.NatvisLogger);
HostNatvisProject.FindNatvis((s) => LoadFile(s));
}
catch (FileNotFoundException)
{
// failed to find the VS Service
}
}
/*
* Handle multiple Natvis files
*/
public void Initialize(List<string> fileNames)
{
InitializeNatvisServices();
if (fileNames != null && fileNames.Count > 0)
{
foreach (var fileName in fileNames)
{
if (!string.IsNullOrEmpty(fileName))
{
if (!Path.IsPathRooted(fileName))
{
string globalVisualizersDirectory = _process.Engine.GetMetric("GlobalVisualizersDirectory") as string;
string globalNatVisPath = null;
if (!string.IsNullOrEmpty(globalVisualizersDirectory) && !string.IsNullOrEmpty(fileName))
{
globalNatVisPath = Path.Combine(globalVisualizersDirectory, fileName);
}
// For local launch, try and load natvis next to the target exe if it exists and if
// the exe is rooted. If the file doesn't exist, and also doesn't exist in the global folder fail.
if (_process.LaunchOptions is LocalLaunchOptions)
{
string exePath = (_process.LaunchOptions as LocalLaunchOptions).ExePath;
if (Path.IsPathRooted(exePath))
{
string localNatvisPath = Path.Combine(Path.GetDirectoryName(exePath), fileName);
if (File.Exists(localNatvisPath))
{
LoadFile(localNatvisPath);
return;
}
else if (globalNatVisPath == null || !File.Exists(globalNatVisPath))
{
// Neither local or global path exists, report an error.
_process.WriteOutput(String.Format(CultureInfo.CurrentCulture, ResourceStrings.FileNotFound, localNatvisPath));
return;
}
}
}
// Local wasn't supported or the file didn't exist. Try and load from globally registered visualizer directory if local didn't work
// or wasn't supported by the launch options
if (!string.IsNullOrEmpty(globalNatVisPath))
{
LoadFile(globalNatVisPath);
}
}
else
{
// Full path to the natvis file.. Just try the load
LoadFile(fileName);
}
}
}
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security.Xml", "CA3053: UseSecureXmlResolver.",
Justification = "Usage is secure -- XmlResolver property is set to 'null' in desktop CLR, and is always null in CoreCLR. But CodeAnalysis cannot understand the invocation since it happens through reflection.")]
private bool LoadFile(string path)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(AutoVisualizer));
if (!File.Exists(path))
{
_process.Logger.NatvisLogger?.WriteLine(LogLevel.Error, ResourceStrings.FileNotFound, path);
return false;
}
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
settings.IgnoreProcessingInstructions = true;
settings.IgnoreWhitespace = true;
// set XmlResolver via reflection, if it exists. This is required for desktop CLR, as otherwise the XML reader may
// attempt to hit untrusted external resources.
var xmlResolverProperty = settings.GetType().GetProperty("XmlResolver", BindingFlags.Public | BindingFlags.Instance);
xmlResolverProperty?.SetValue(settings, null);
using (var stream = new System.IO.FileStream(path, FileMode.Open, FileAccess.Read))
using (var reader = XmlReader.Create(stream, settings))
{
AutoVisualizer autoVis = null;
autoVis = serializer.Deserialize(reader) as AutoVisualizer;
if (autoVis != null)
{
FileInfo f = new FileInfo(autoVis);
if (autoVis.Items == null)
{
return false;
}
foreach (var o in autoVis.Items)
{
if (o is VisualizerType)
{
VisualizerType v = (VisualizerType)o;
TypeName t = TypeName.Parse(v.Name, _process.Logger.NatvisLogger);
if (t != null)
{
lock (_typeVisualizers)
{
f.Visualizers.Add(new TypeInfo(t, v));
}
}
// add an entry for each alternative name too
if (v.AlternativeType != null)
{
foreach (var a in v.AlternativeType)
{
t = TypeName.Parse(a.Name, _process.Logger.NatvisLogger);
if (t != null)
{
lock (_typeVisualizers)
{
f.Visualizers.Add(new TypeInfo(t, v));
}
}
}
}
}
else if (o is AliasType)
{
AliasType a = (AliasType)o;
TypeName t = TypeName.Parse(a.Name, _process.Logger.NatvisLogger);
if (t != null)
{
lock (_typeVisualizers)
{
f.Aliases.Add(new AliasInfo(t, a));
}
}
}
}
if (autoVis.UIVisualizer != null)
{
f.UIVisualizers = autoVis.UIVisualizer.ToList();
}
_typeVisualizers.Add(f);
}
return autoVis != null;
}
}
catch (Exception exception)
{
// don't allow natvis failures to stop debugging
_process.Logger.NatvisLogger?.WriteLine(LogLevel.Error, ResourceStrings.ErrorReadingFile, exception.Message, path);
return false;
}
}
internal (string value, VisualizerId[] uiVisualizers) FormatDisplayString(IVariableInformation variable)
{
VisualizerInfo visualizer = null;
try
{
_depth++;
if (_depth < MAX_FORMAT_DEPTH)
{
if (!(variable is VisualizerWrapper) && //no displaystring for dummy vars ([Raw View])
(ShowDisplayStrings == DisplayStringsState.On
|| (ShowDisplayStrings == DisplayStringsState.ForVisualizedItems && variable.IsVisualized)) &&
!variable.IsPreformatted)
{
visualizer = FindType(variable);
if (visualizer == null)
{
return (variable.Value, null);
}
Cache.Add(variable); // vizualized value has been displayed
foreach (var item in visualizer.Visualizer.Items)
{
if (item is DisplayStringType)
{
DisplayStringType display = item as DisplayStringType;
// e.g. <DisplayString>{{ size={_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst} }}</DisplayString>
if (!EvalCondition(display.Condition, variable, visualizer.ScopedNames))
{
continue;
}
return (FormatValue(display.Value, variable, visualizer.ScopedNames), visualizer.GetUIVisualizers());
}
}
}
}
}
catch (Exception e)
{
// don't allow natvis to mess up debugging
// eat any exceptions and return the variable's value
_process.Logger.NatvisLogger?.WriteLine(LogLevel.Error, "FormatDisplayString: " + e.Message);
}
finally
{
_depth--;
}
return (variable.Value, visualizer?.GetUIVisualizers());
}
private IVariableInformation GetVisualizationWrapper(IVariableInformation variable)
{
if (variable.IsPreformatted)
{
return null;
}
VisualizerInfo visualizer = FindType(variable);
if (visualizer == null || variable is VisualizerWrapper) // don't stack wrappers
{
return null;
}
ExpandType1 expandType = (ExpandType1)Array.Find(visualizer.Visualizer.Items, (o) => { return o is ExpandType1; });
if (expandType == null)
{
return null;
}
// return expansion with [Visualizer View] child as first element
return new VisualizerWrapper(ResourceStrings.VisualizedView, _process.Engine, variable, visualizer, isVisualizerView: true);
}
internal IVariableInformation[] Expand(IVariableInformation variable)
{
try
{
variable.EnsureChildren();
if (variable.IsVisualized
|| ((ShowDisplayStrings == DisplayStringsState.On) && !(variable is VisualizerWrapper))) // visualize right away if DisplayStringsState.On, but only if not dummy var ([Raw View])
{
return ExpandVisualized(variable);
}
IVariableInformation visView = GetVisualizationWrapper(variable);
if (visView == null)
{
return variable.Children;
}
List<IVariableInformation> children = new List<IVariableInformation>();
children.Add(visView);
children.AddRange(variable.Children);
return children.ToArray();
}
catch (Exception e)
{
_process.Logger.WriteLine(LogLevel.Error, "natvis Expand: " + e.Message); // TODO: add telemetry
return variable.Children;
}
}
internal IVariableInformation GetVariable(string expr, AD7StackFrame frame)
{
IVariableInformation variable;
if (!EngineUtils.IsConsoleExecCmd(expr, out string _, out string _)
&& expr.EndsWith(",viz", StringComparison.Ordinal))
{
expr = expr.Substring(0, expr.Length - 4);
variable = new VariableInformation(expr, expr, frame.ThreadContext, frame.Engine, frame.Thread);
variable.SyncEval();
if (!variable.Error)
{
variable = GetVisualizationWrapper(variable) ?? variable;
}
}
else
{
variable = new VariableInformation(expr, expr, frame.ThreadContext, frame.Engine, frame.Thread);
}
return variable;
}
internal string GetUIVisualizerName(string serviceId, int id)
{
string result = string.Empty;
this._typeVisualizers.ForEach((f)=>
{
UIVisualizerType uiViz;
if ((uiViz = f.UIVisualizers?.FirstOrDefault((u) => u.ServiceId == serviceId && u.Id == id)) != null)
{
result = uiViz.MenuName;
}
});
return result;
}
private delegate IVariableInformation Traverse(IVariableInformation node);
private IVariableInformation[] ExpandVisualized(IVariableInformation variable)
{
VisualizerInfo visualizer = FindType(variable);
if (visualizer == null)
{
return variable.Children;
}
List<IVariableInformation> children = new List<IVariableInformation>();
ExpandType1 expandType = (ExpandType1)Array.Find(visualizer.Visualizer.Items, (o) => { return o is ExpandType1; });
if (expandType == null)
{
return variable.Children;
}
foreach (var i in expandType.Items)
{
if (i is ItemType && !(variable is PaginatedVisualizerWrapper)) // we do not want to repeatedly display other ItemTypes when expanding the "[More...]" node
{
ItemType item = (ItemType)i;
if (!EvalCondition(item.Condition, variable, visualizer.ScopedNames))
{
continue;
}
IVariableInformation expr = GetExpression(item.Value, variable, visualizer.ScopedNames, item.Name);
children.Add(expr);
}
else if (i is ArrayItemsType)
{
ArrayItemsType item = (ArrayItemsType)i;
if (!EvalCondition(item.Condition, variable, visualizer.ScopedNames))
{
continue;
}
uint totalSize = 0;
int rank = 0;
uint[] dimensions = null;
if (!string.IsNullOrEmpty(item.Rank))
{
totalSize = 1;
if (!int.TryParse(item.Rank, NumberStyles.None, CultureInfo.InvariantCulture, out rank))
{
string expressionValue = GetExpressionValue(item.Rank, variable, visualizer.ScopedNames);
rank = Int32.Parse(expressionValue, CultureInfo.InvariantCulture);
}
if (rank <= 0)
{
throw new Exception("Invalid rank value");
}
dimensions = new uint[rank];
for (int idx = 0; idx < rank; idx++)
{
// replace $i with Item.Rank here before passing it into GetExpressionValue
string substitute = item.Size.Replace("$i", idx.ToString(CultureInfo.InvariantCulture));
string val = GetExpressionValue(substitute, variable, visualizer.ScopedNames);
uint tmp = MICore.Debugger.ParseUint(val, throwOnError: true);
dimensions[idx] = tmp;
totalSize *= tmp;
}
}
else
{
string val = GetExpressionValue(item.Size, variable, visualizer.ScopedNames);
totalSize = MICore.Debugger.ParseUint(val, throwOnError: true);
}
uint startIndex = 0;
if (variable is PaginatedVisualizerWrapper pvwVariable)
{
startIndex = pvwVariable.StartIndex;
}
ValuePointerType[] vptrs = item.ValuePointer;
foreach (var vp in vptrs)
{
if (EvalCondition(vp.Condition, variable, visualizer.ScopedNames))
{
IVariableInformation ptrExpr = GetExpression("*(" + vp.Value + ")", variable, visualizer.ScopedNames);
string typename = ptrExpr.TypeName;
if (String.IsNullOrWhiteSpace(typename))
{
continue;
}
// Creates an expression: (T[50])*(<ValuePointer> + 50)
// This evaluates for 50 elements of type T, starting at <ValuePointer> with an offet of 50 elements.
// E.g. This will grab elements 50 - 99 from <ValuePointer>.
// Note:
// If requestedSize > 1000, the evaluation will only grab the first 1000 elements.
// We want to limit it to at most 50.
uint requestedSize = Math.Min(MAX_EXPAND, totalSize - startIndex);
StringBuilder arrayBuilder = new StringBuilder();
arrayBuilder.Append('(');
arrayBuilder.Append(typename);
arrayBuilder.Append('[');
arrayBuilder.Append(requestedSize);
arrayBuilder.Append("])*(");
arrayBuilder.Append(vp.Value);
arrayBuilder.Append('+');
arrayBuilder.Append(startIndex);
arrayBuilder.Append(')');
string arrayStr = arrayBuilder.ToString();
IVariableInformation arrayExpr = GetExpression(arrayStr, variable, visualizer.ScopedNames);
arrayExpr.EnsureChildren();
if (arrayExpr.CountChildren != 0)
{
uint offset = startIndex + requestedSize;
bool isForward = item.Direction != ArrayDirectionType.Backward;
for (uint index = 0; index < requestedSize; ++index)
{
uint currentOffsetIndex = startIndex + index;
string displayName = rank > 1 ? GetDisplayNameFromArrayIndex(currentOffsetIndex, rank, dimensions, isForward) : currentOffsetIndex.ToString(CultureInfo.InvariantCulture);
children.Add(new SimpleWrapper("[" + displayName + "]", _process.Engine, arrayExpr.Children[index]));
}
if (totalSize > offset)
{
IVariableInformation moreVariable = new PaginatedVisualizerWrapper(ResourceStrings.MoreView, _process.Engine, variable, FindType(variable), isVisualizerView: true, offset);
children.Add(moreVariable);
}
}
break;
}
}
}
else if (i is TreeItemsType)
{
TreeItemsType item = (TreeItemsType)i;
if (!EvalCondition(item.Condition, variable, visualizer.ScopedNames))
{
continue;
}
if (String.IsNullOrWhiteSpace(item.Size) || String.IsNullOrWhiteSpace(item.HeadPointer) || String.IsNullOrWhiteSpace(item.LeftPointer) ||
String.IsNullOrWhiteSpace(item.RightPointer))
{
continue;
}
if (item.ValueNode == null || String.IsNullOrWhiteSpace(item.ValueNode.Value))
{
continue;
}
string val = GetExpressionValue(item.Size, variable, visualizer.ScopedNames);
uint size = MICore.Debugger.ParseUint(val, throwOnError: true);
IVariableInformation headVal;
if (variable is TreeContinueWrapper tcw)
{
headVal = tcw.ContinueNode.Content;
}
else
{
headVal = GetExpression(item.HeadPointer, variable, visualizer.ScopedNames);
}
ulong head = MICore.Debugger.ParseAddr(headVal.Value);
var content = new List<IVariableInformation>();
if (head != 0 && size != 0)
{
headVal.EnsureChildren();
Traverse goLeft = GetTraverse(item.LeftPointer, headVal);
Traverse goRight = GetTraverse(item.RightPointer, headVal);
Traverse getValue = null;
if (item.ValueNode.Value == "this") // TODO: handle condition
{
getValue = (v) => v;
}
else if (headVal.FindChildByName(item.ValueNode.Value) != null)
{
getValue = (v) => v.FindChildByName(item.ValueNode.Value);
}
else if (GetExpression(item.ValueNode.Value, headVal, visualizer.ScopedNames) != null)
{
getValue = (v) => GetExpression(item.ValueNode.Value, v, visualizer.ScopedNames);
}
if (goLeft == null || goRight == null || getValue == null)
{
continue;
}
uint startIndex = 0;
IVariableInformation parent = variable;
if (variable is PaginatedVisualizerWrapper visualizerWrapper)
{
startIndex = visualizerWrapper.StartIndex;
parent = visualizerWrapper.Parent;
}
else if (variable is SimpleWrapper simpleWrapper)
{
parent = simpleWrapper.Parent;
}
TraverseTree(headVal, goLeft, goRight, getValue, children, size, variable, parent, startIndex);
}
}
else if (i is LinkedListItemsType)
{
// example:
// <LinkedListItems>
// <Size>m_nElements</Size> -- optional, will go until NextPoint is 0 or == HeadPointer
// <HeadPointer>m_pHead</HeadPointer>
// <NextPointer>m_pNext</NextPointer>
// <ValueNode>m_element</ValueNode>
// </LinkedListItems>
LinkedListItemsType item = (LinkedListItemsType)i;
if (String.IsNullOrWhiteSpace(item.Condition))
{
if (!EvalCondition(item.Condition, variable, visualizer.ScopedNames))
continue;
}
if (String.IsNullOrWhiteSpace(item.HeadPointer) || String.IsNullOrWhiteSpace(item.NextPointer))
{
continue;
}
if (String.IsNullOrWhiteSpace(item.ValueNode))
{
continue;
}
uint size = MAX_EXPAND;
if (!String.IsNullOrWhiteSpace(item.Size))
{
string val = GetExpressionValue(item.Size, variable, visualizer.ScopedNames);
size = MICore.Debugger.ParseUint(val);
}
IVariableInformation headVal;
if (variable is LinkedListContinueWrapper llcw)
{
headVal = llcw.ContinueNode;
}
else
{
headVal = GetExpression(item.HeadPointer, variable, visualizer.ScopedNames);
}
ulong head = MICore.Debugger.ParseAddr(headVal.Value);
var content = new List<IVariableInformation>();
if (head != 0 && size != 0)
{
headVal.EnsureChildren();
Traverse goNext = GetTraverse(item.NextPointer, headVal);
Traverse getValue = null;
if (item.ValueNode == "this")
{
getValue = (v) => v;
}
else if (headVal.FindChildByName(item.ValueNode) != null)
{
getValue = (v) => v.FindChildByName(item.ValueNode);
}
else
{
var value = GetExpression(item.ValueNode, headVal, visualizer.ScopedNames);
if (value != null && !value.Error)
{
getValue = (v) => GetExpression(item.ValueNode, v, visualizer.ScopedNames);
}
}
if (goNext == null || getValue == null)
{
continue;
}
uint startIndex = 0;
IVariableInformation parent = variable;
if (variable is PaginatedVisualizerWrapper visualizerWrapper)
{
startIndex = visualizerWrapper.StartIndex;
parent = visualizerWrapper.Parent;
}
else if (variable is SimpleWrapper simpleWrapper)
{
parent = simpleWrapper.Parent;
}
TraverseList(headVal, goNext, getValue, children, size, item.NoValueHeadPointer, parent, startIndex);
}
}
else if (i is IndexListItemsType)
{
// example:
// <IndexListItems>
// <Size>_M_vector._M_index</Size>
// <ValueNode>*(_M_vector._M_array[$i])</ValueNode>
// </IndexListItems>
IndexListItemsType item = (IndexListItemsType)i;
if (!EvalCondition(item.Condition, variable, visualizer.ScopedNames))
{
continue;
}
var sizes = item.Size;
uint size = 0;
if (sizes == null)
{
continue;
}
foreach (var s in sizes)
{
if (string.IsNullOrWhiteSpace(s.Value))
continue;
if (EvalCondition(s.Condition, variable, visualizer.ScopedNames))
{
string val = GetExpressionValue(s.Value, variable, visualizer.ScopedNames);
size = MICore.Debugger.ParseUint(val);
break;
}
}
var values = item.ValueNode;
if (values == null)
{
continue;
}
foreach (var v in values)
{
if (string.IsNullOrWhiteSpace(v.Value))
continue;
if (EvalCondition(v.Condition, variable, visualizer.ScopedNames))
{
string processedExpr = ReplaceNamesInExpression(v.Value, variable, visualizer.ScopedNames);
Dictionary<string, string> indexDic = new Dictionary<string, string>();
uint currentIndex = 0;
if (variable is PaginatedVisualizerWrapper pvwVariable)
{
currentIndex = pvwVariable.StartIndex;
}
uint maxIndex = currentIndex + MAX_EXPAND > size ? size : currentIndex + MAX_EXPAND;
for (uint index = currentIndex; index < maxIndex; ++index) // limit expansion to first 50 elements
{
indexDic["$i"] = index.ToString(CultureInfo.InvariantCulture);
string finalExpr = ReplaceNamesInExpression(processedExpr, null, indexDic);
IVariableInformation expressionVariable = new VariableInformation(finalExpr, variable, _process.Engine, "[" + indexDic["$i"] + "]");
expressionVariable.SyncEval();
children.Add(expressionVariable);
}
currentIndex += MAX_EXPAND;
if (size > currentIndex)
{
IVariableInformation moreVariable = new PaginatedVisualizerWrapper(ResourceStrings.MoreView, _process.Engine, variable, visualizer, isVisualizerView: true, currentIndex);
children.Add(moreVariable);
}
break;
}
}
}
else if (i is ExpandedItemType)
{
ExpandedItemType item = (ExpandedItemType)i;
// example:
// <Type Name="std::auto_ptr<*>">
// <DisplayString>auto_ptr {*_Myptr}</DisplayString>
// <Expand>
// <ExpandedItem>_Myptr</ExpandedItem>
// </Expand>
// </Type>
if (item.Condition != null)
{
if (!EvalCondition(item.Condition, variable, visualizer.ScopedNames))
{
continue;
}
}
if (String.IsNullOrWhiteSpace(item.Value))
{
continue;
}
var expand = GetExpression(item.Value, variable, visualizer.ScopedNames);
var eChildren = Expand(expand);
if (eChildren != null)
{
children.AddRange(eChildren);
}
}
}
if (!(variable is VisualizerWrapper)) // don't stack wrappers
{
// add the [Raw View] field
IVariableInformation rawView = new VisualizerWrapper(ResourceStrings.RawView, _process.Engine, variable, visualizer, isVisualizerView: false);
children.Add(rawView);
}
return children.ToArray();
}
private Traverse GetTraverse(string direction, IVariableInformation node)
{
Traverse go;
var val = node.FindChildByName(direction);
if (val == null)
{
return null;
}
if (val.TypeName == node.TypeName)
{
go = (v) => v.FindChildByName(direction);
}
else
{
go = (v) =>
{
ulong addr = MICore.Debugger.ParseAddr(v.Value);
if (addr != 0)
{
var next = v.FindChildByName(direction);
next = new VariableInformation("(" + v.TypeName + ")" + next.Value, next, _process.Engine, "");
next.SyncEval();
return next;
}
return null;
};
}
return go;
}
/// <summary>
/// Traverse tree based on specified startIndex.
/// Then add wrappers for Natvis tree visualizations.
/// </summary>
/// <param name="root">Root of the tree</param>
/// <param name="goLeft">Traverse callback to retrieve left child of root</param>
/// <param name="goRight">Traverse callback to retrieve right child of root</param>
/// <param name="getValue">Callback to retrieve value of root</param>
/// <param name="content">List of variables to display given current variable</param>
/// <param name="size">Number of nodes in tree</param>
/// <param name="variable">Tree to traverse if size <= 50. Otherwise, expandable continue wrapper.</param>
/// <param name="parent">The tree to traverse</param>
/// <param name="startIndex">Index to start traversing from</param>
/// <returns></returns>
private void TraverseTree(IVariableInformation root, Traverse goLeft, Traverse goRight, Traverse getValue, List<IVariableInformation> content, uint size, IVariableInformation variable, IVariableInformation parent, uint startIndex)
{
uint i = startIndex;
var nodes = new Stack<Node>();
if (variable is TreeContinueWrapper tcwVariable)
{
nodes = tcwVariable.Nodes;
}
else
{
nodes.Push(new Node(root));
}