-
Notifications
You must be signed in to change notification settings - Fork 219
/
Variables.cs
890 lines (804 loc) · 34.7 KB
/
Variables.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
// 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.VisualStudio.Debugger.Interop;
using Microsoft.VisualStudio.Debugger.Interop.DAP;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Microsoft.MIDebugEngine
{
internal interface IVariableInformation : IDisposable
{
string Name { get; }
string Value { get; }
string TypeName { get; }
bool IsParameter { get; }
VariableInformation[] Children { get; } // children are never synthetic
AD7Thread Client { get; }
bool Error { get; }
uint CountChildren { get; }
bool IsChild { get; set; }
enum_DBG_ATTRIB_FLAGS Access { get; }
string FullName();
bool IsStringType { get; }
void EnsureChildren();
void AsyncEval(IDebugEventCallback2 pExprCallback);
void AsyncError(IDebugEventCallback2 pExprCallback, IDebugProperty2 error);
void SyncEval(enum_EVALFLAGS dwFlags = 0, DAPEvalFlags dwDAPFlags = 0);
ThreadContext ThreadContext { get; }
VariableInformation FindChildByName(string name);
string EvalDependentExpression(string expr);
bool IsVisualized { get; }
bool IsReadOnly();
enum_DEBUGPROP_INFO_FLAGS PropertyInfoFlags { get; set; }
bool IsPreformatted { get; set; }
string Address();
uint Size();
}
internal class SimpleVariableInformation
{
public string Name { get; private set; }
public string Value { get; private set; }
public string TypeName { get; private set; }
public bool IsParameter { get; private set; }
internal SimpleVariableInformation(string name, bool isParam = false, string value = null, string type = null)
{
Name = name;
Value = value;
TypeName = type;
IsParameter = isParam;
}
internal async Task<VariableInformation> CreateMIDebuggerVariable(ThreadContext ctx, AD7Engine engine, AD7Thread thread)
{
VariableInformation vi = new VariableInformation(Name, Name, ctx, engine, thread, IsParameter);
await vi.Eval(engine.CurrentRadix());
return vi;
}
}
internal class ArgumentList : Tuple<int, List<SimpleVariableInformation>>
{
public ArgumentList(int level, List<SimpleVariableInformation> args)
: base(level, args)
{ }
}
internal sealed class VariableInformation : IVariableInformation
{
public string Name { get; private set; }
public string Value { get; private set; }
public string TypeName { get; private set; }
public bool IsParameter { get; private set; }
public VariableInformation[] Children { get; private set; }
public AD7Thread Client { get; private set; }
public bool Error { get; private set; }
public uint CountChildren { get; private set; }
public bool IsChild { get; set; }
public enum_DBG_ATTRIB_FLAGS Access { get; private set; }
public bool IsVisualized { get { return _parent == null ? false : _parent.IsVisualized; } }
public enum_DEBUGPROP_INFO_FLAGS PropertyInfoFlags { get; set; }
private string DisplayHint { get; set; }
public bool IsPreformatted { get; set; }
static readonly Lazy<Regex> s_addressPattern = new Lazy<Regex>(() => new Regex(@"^(0x[0-9a-fA-F]+)\b"));
public string Address()
{
// ask GDB to evaluate "&expression"
string command = "&("+FullName()+")";
var result = EvalDependentExpression(command);
Match m = s_addressPattern.Value.Match(result);
if (m.Success)
{
return m.Captures[0].ToString();
}
string errorMessage = String.Format(CultureInfo.InvariantCulture, "Unexpected result {0} from evaluating {1}", result, command);
throw new UnexpectedMIResultException(_debuggedProcess.MICommandFactory.Name, "-data-evaluate-expression", errorMessage);
}
public uint Size()
{
// ask GDB to evaluate "sizeof(expression)"
string command = "sizeof("+FullName()+")";
return Convert.ToUInt32(EvalDependentExpression(command), CultureInfo.InvariantCulture);
}
private static bool IsPointer(string typeName)
{
return typeName.Trim().EndsWith("*", StringComparison.Ordinal);
}
public string FullName() // Full expression used to re-compute the value
{
if (_fullname == null)
{
switch (VariableNodeType)
{
case NodeType.Root:
case NodeType.Synthetic:
_fullname = _strippedName;
break;
case NodeType.Field:
//Task evalTask = Task.Run(async () =>
//{
// m_fullname = await m_engine.DebuggedProcess.MICommandFactory.VarInfoPathExpression(m_internalName);
//});
//evalTask.Wait();
string op = ".";
string parentName = _parent.FullName();
if (IsPointer(_parent.TypeName))
{
op = "->";
// Underlying debugger sometimes has trouble with long expressions (parent-expression can be arbitrarily long),
// so attempt to simplify the expression by using ((parent-type)0xabc)->field instead of (parent-expression)->field
ulong addr;
if (_parent.Value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
&& ulong.TryParse(_parent.Value.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out addr))
{
parentName = '(' + _parent.TypeName + ')' + _parent.Value;
}
}
_fullname = '(' + parentName + ')' + op + _strippedName;
break;
case NodeType.Dereference:
_fullname = "*(" + _parent.FullName() + ")";
break;
case NodeType.BaseClass:
case NodeType.AccessQualifier:
_fullname = _parent.FullName();
break;
case NodeType.ArrayElement:
_fullname = '(' + _parent.FullName() + ')' + Name;
break;
case NodeType.AnonymousUnion:
_fullname = _parent.FullName();
break;
default:
_fullname = String.Empty;
break;
}
}
return _fullname;
}
public bool IsStringType
{
get
{
if (!string.IsNullOrWhiteSpace(this.TypeName))
{
for (int i = 0; i < s_stringTypes.Length; ++i)
{
if (Regex.IsMatch(this.TypeName.Trim(), s_stringTypes[i]))
{
return true;
}
}
}
return false;
}
}
private VariableInformation(ThreadContext ctx, AD7Engine engine, AD7Thread thread)
{
_engine = engine;
_debuggedProcess = _engine.DebuggedProcess;
_ctx = ctx;
Client = thread;
IsParameter = false;
IsChild = false;
_attribsFetched = false;
_isReadonly = false;
Access = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_NONE;
_fullname = null;
lock (_debuggedProcess.ActiveVariables)
{
_debuggedProcess.ActiveVariables.Add(this);
}
}
//this constructor is used to create root nodes (local/params)
internal VariableInformation(string displayName, string expr, ThreadContext ctx, AD7Engine engine, AD7Thread thread, bool isParameter = false)
: this(ctx, engine, thread)
{
// strip off formatting string
_strippedName = StripFormatSpecifier(expr, out _format);
Name = displayName;
IsParameter = isParameter;
_parent = null;
VariableNodeType = NodeType.Root;
}
//this constructor is used to create synthetic child nodes (local/params). These nodes are never in the parent's children list
internal VariableInformation(string expr, IVariableInformation parent, AD7Engine engine, string displayName)
: this(parent.ThreadContext, engine, parent.Client)
{
// strip off formatting string
_strippedName = StripFormatSpecifier(expr, out _format);
Name = displayName ?? expr;
_parent = parent;
VariableNodeType = NodeType.Synthetic;
}
//this constructor is used to create modified expressions from a parent
internal VariableInformation(string expr, VariableInformation parent)
: this(parent._ctx, parent._engine, parent.Client)
{
// strip off formatting string
_strippedName = StripFormatSpecifier(expr, out _format);
Name = expr;
VariableNodeType = NodeType.Root;
}
//this constructor is private because it should only be used internally to create children
private VariableInformation(TupleValue results, VariableInformation parent, string name = null)
: this(parent._ctx, parent._engine, parent.Client)
{
TypeName = results.TryFindString("type");
Value = results.TryFindString("value");
Name = name ?? results.FindString("exp");
if (results.Contains("dynamic"))
{
CountChildren = results.TryFindUint("has_more").GetValueOrDefault(1);
IsPreformatted = true;
}
else
{
CountChildren = results.FindUint("numchild");
}
if (results.Contains("displayhint"))
{
DisplayHint = results.FindString("displayhint");
}
if (results.Contains("attributes"))
{
if (results.FindString("attributes") == "noneditable")
{
_isReadonly = true;
}
_attribsFetched = true;
}
int index;
if (!results.Contains("value") && (Name == TypeName || Name.Contains("::")))
{
// base classes show up with no value and exp==type
// (sometimes underlying debugger does not follow this convention, when using typedefs in templated types so look for "::" in the field name too)
Name = TypeName + " (base)";
Value = TypeName;
VariableNodeType = NodeType.BaseClass;
}
else if (Int32.TryParse(this.Name, System.Globalization.NumberStyles.Integer, null, out index)) // array element
{
Name = '[' + this.Name + ']';
VariableNodeType = NodeType.ArrayElement;
}
else if (this.Name.Length > 2 && this.Name[0] == '[' && this.Name[this.Name.Length - 1] == ']')
{
VariableNodeType = NodeType.ArrayElement;
}
else if (Name == "<anonymous union>")
{
VariableNodeType = NodeType.AnonymousUnion;
}
else if (Name.Length > 1 && Name[0] == '*')
{
VariableNodeType = NodeType.Dereference;
}
else
{
_strippedName = Name;
VariableNodeType = NodeType.Field;
}
_internalName = results.FindString("name");
IsChild = true;
_format = parent._format; // inherit formatting
_parent = parent.VariableNodeType == NodeType.AccessQualifier ? parent._parent : parent;
this.PropertyInfoFlags = parent.PropertyInfoFlags;
}
public ThreadContext ThreadContext { get { return _ctx; } }
public VariableInformation FindChildByName(string name)
{
EnsureChildren();
if (CountChildren == 0)
{
return null;
}
Debug.Assert(Children != null, "Failed to find children");
VariableInformation var = Array.Find(Children, (c) => c.Name == name);
if (var != null)
{
return var;
}
VariableInformation baseChild = null;
var = Array.Find(Children, (c) => (c.VariableNodeType == NodeType.BaseClass || c.VariableNodeType == NodeType.AnonymousUnion) && (baseChild = c.FindChildByName(name)) != null);
return baseChild;
}
private string _internalName; // the MI debugger's private name for this value
private AD7Engine _engine;
private DebuggedProcess _debuggedProcess;
private ThreadContext _ctx;
private bool _attribsFetched;
private bool _isReadonly;
private string _format;
private string _strippedName; // "Name" stripped of format specifiers
private IVariableInformation _parent;
private string _fullname;
public enum NodeType
{
Root,
Field,
Dereference,
ArrayElement,
BaseClass,
AccessQualifier,
Synthetic,
AnonymousUnion
};
public NodeType VariableNodeType { get; private set; }
private static readonly string[] s_stringTypes = new string[] {
@"^char *\*$",
@"^char *\[[0-9]*\]$",
@"^const +char *\*$",
@"^const +char *\[[0-9]*\]$"
};
private static Regex s_isFunction = new Regex(@".+\(.*\).*");
private string StripFormatSpecifier(string exp, out string formatSpecifier)
{
formatSpecifier = null; // will be used with -var-set-format
int lastComma = exp.LastIndexOf(',');
if (lastComma <= 0)
return exp;
// https://docs.microsoft.com/en-us/visualstudio/debugger/format-specifiers-in-cpp
string expFS = exp.Substring(lastComma + 1);
string trimmed = expFS.Trim();
switch (trimmed)
{
case "x":
case "X":
case "h":
case "H":
case "xb":
case "Xb":
case "hb":
case "Hb":
// could be improved upon via post-processing with ToUpperInvariant/SubString
formatSpecifier = "zero-hexadecimal";
goto case "";
case "o":
formatSpecifier = "octal";
goto case "";
case "d":
formatSpecifier = "decimal";
goto case "";
case "b":
case "bb":
formatSpecifier = "binary";
goto case "";
case "e":
case "g":
goto case "";
case "s":
case "sb":
case "s8":
case "s8b":
return "(const char*)(" + exp.Substring(0, lastComma) + ")";
case "su":
case "sub":
return "(const char16_t*)(" + exp.Substring(0, lastComma) + ")";
case "c":
return "(char)(" + exp.Substring(0, lastComma) + ")";
// just remove and ignore these
case "en":
case "na":
case "nd":
case "nr":
case "!":
case "":
return exp.Substring(0, lastComma);
}
// array with static size
// TODO: could return '(T(*)[n])(exp)' but requires T
var m = Regex.Match(trimmed, @"^\[?(\d+)\]?$");
if (m.Success)
return exp.Substring(0, lastComma);
// array with dynamic size
if (Regex.Match(trimmed, @"^\[([a-zA-Z_][a-zA-Z_\d]*)\]$").Success)
return exp.Substring(0, lastComma);
return exp;
}
public void AsyncEval(IDebugEventCallback2 pExprCallback)
{
EngineCallback engineCallback;
if (pExprCallback != null)
{
engineCallback = new EngineCallback(_engine, pExprCallback);
}
else
{
engineCallback = _engine.Callback;
}
uint radix = _engine.CurrentRadix();
Task evalTask = Task.Run(async () =>
{
await Eval(radix);
});
Action<Task> onComplete = (Task t) =>
{
engineCallback.OnExpressionEvaluationComplete(this);
};
evalTask.ContinueWith(onComplete, TaskContinuationOptions.ExecuteSynchronously);
}
public static void AsyncErrorImpl(EngineCallback engineCallback, IVariableInformation var, IDebugProperty2 error)
{
Task.Run(() =>
{
engineCallback.OnExpressionEvaluationComplete(var, error);
});
}
public void AsyncError(IDebugEventCallback2 pExprCallback, IDebugProperty2 error)
{
AsyncErrorImpl(pExprCallback != null ? new EngineCallback(_engine, pExprCallback) : _engine.Callback, this, error);
}
public void SyncEval(enum_EVALFLAGS dwFlags = 0, DAPEvalFlags dwDAPFlags = 0)
{
uint radix = _engine.CurrentRadix();
Task eval = Task.Run(async () =>
{
await Eval(radix, dwFlags, dwDAPFlags);
});
eval.Wait();
}
public string EvalDependentExpression(string expr)
{
this.VerifyNotDisposed();
string val = null;
Task eval = Task.Run(async () =>
{
val = await _engine.DebuggedProcess.MICommandFactory.DataEvaluateExpression(expr, Client.GetDebuggedThread().Id, _ctx.Level);
});
eval.Wait();
return val;
}
internal async Task Eval(uint radix, enum_EVALFLAGS dwFlags = 0, DAPEvalFlags dwDAPFlags = 0)
{
this.VerifyNotDisposed();
if (radix != 0)
{
await _engine.UpdateRadixAsync(radix); // ensure the radix value is up-to-date
}
try
{
if (EngineUtils.IsConsoleExecCmd(_strippedName, out string _, out string consoleCommand))
{
// special case for executing raw mi commands.
string consoleResults = null;
consoleResults = await MIDebugCommandDispatcher.ExecuteCommand(consoleCommand, _debuggedProcess, ignoreFailures: true);
Value = String.Empty;
this.TypeName = null;
if (!String.IsNullOrEmpty(consoleResults))
{
_debuggedProcess.WriteOutput(consoleResults);
}
}
else
{
bool canRunClipboardContextCommands = this._debuggedProcess.MICommandFactory.Mode == MIMode.Gdb && dwDAPFlags.HasFlag(DAPEvalFlags.CLIPBOARD_CONTEXT);
int numElements = 200;
if (canRunClipboardContextCommands)
{
string showPrintElementsResult = await MIDebugCommandDispatcher.ExecuteCommand("show print elements", _debuggedProcess, ignoreFailures: true);
// Possible values for 'numElementsStr'
// "Limit on string chars or array elements to print is <number>."
// "Limit on string chars or array elements to print is unlimited."
string numElementsStr = Regex.Match(showPrintElementsResult, @"\d+").Value;
if (!string.IsNullOrEmpty(numElementsStr) && int.TryParse(numElementsStr, out numElements) && numElements != 0)
{
await MIDebugCommandDispatcher.ExecuteCommand("set print elements 0", _debuggedProcess, ignoreFailures: true);
}
}
int threadId = Client.GetDebuggedThread().Id;
uint frameLevel = _ctx.Level;
Results results = await _engine.DebuggedProcess.MICommandFactory.VarCreate(_strippedName, threadId, frameLevel, dwFlags, ResultClass.None);
if (results.ResultClass == ResultClass.done)
{
_internalName = results.FindString("name");
TypeName = results.TryFindString("type");
if (results.Contains("dynamic"))
{
IsPreformatted = true;
}
if (results.Contains("dynamic") && results.Contains("has_more"))
{
CountChildren = results.FindUint("has_more");
}
else
{
CountChildren = results.FindUint("numchild");
}
if (results.Contains("displayhint"))
{
DisplayHint = results.FindString("displayhint");
}
if (results.Contains("attributes"))
{
if (results.FindString("attributes") == "noneditable")
{
_isReadonly = true;
}
_attribsFetched = true;
}
Value = results.TryFindString("value");
if ((string.IsNullOrEmpty(Value) || _format != null) && !string.IsNullOrEmpty(_internalName))
{
if (_format != null)
{
await Format();
}
else
{
results = await _engine.DebuggedProcess.MICommandFactory.VarEvaluateExpression(_internalName, ResultClass.None);
if (results.ResultClass == ResultClass.done)
{
Value = results.FindString("value");
}
else if (results.ResultClass == ResultClass.error)
{
SetAsError(results.FindString("msg"));
}
else
{
Debug.Fail("Unexpected format of msg from -var-evaluate-expression");
}
}
}
}
else if (results.ResultClass == ResultClass.error)
{
SetAsError(results.FindString("msg"));
}
else
{
Debug.Fail("Unexpected format of msg from -var-create");
}
if (canRunClipboardContextCommands && numElements != 0)
{
await MIDebugCommandDispatcher.ExecuteCommand(string.Format(CultureInfo.InvariantCulture, "set print elements {0}", numElements), _debuggedProcess, ignoreFailures: true);
}
}
}
catch (Exception e)
{
if (e.InnerException != null)
e = e.InnerException;
UnexpectedMIResultException miException = e as UnexpectedMIResultException;
string message;
if (miException != null && miException.MIError != null)
message = miException.MIError;
else
message = e.Message;
SetAsError(string.Format(CultureInfo.CurrentCulture, ResourceStrings.Failed_ExecCommandError, message));
}
}
internal async Task Format()
{
this.VerifyNotDisposed();
Debug.Assert(_internalName != null);
Debug.Assert(_format != null);
Results results = await _engine.DebuggedProcess.MICommandFactory.VarSetFormat(_internalName, _format, ResultClass.None);
if (results.ResultClass == ResultClass.done)
{
Value = results.FindString("value");
}
else if (results.ResultClass == ResultClass.error)
{
SetAsError(results.FindString("msg"));
}
else
{
Debug.Fail("Unexpected format of msg from expression formatting");
}
}
// If we have some children, go get them
public void EnsureChildren()
{
if ((CountChildren != 0) && (Children == null))
{
Task task = FetchChildren();
task.Wait();
}
}
private Task FetchChildren()
{
// Note: I am not sure if it is actually useful to run the evaluation code off of the poll thread (will GDB actually handle other commands at the same time)
// but this seems like one place where we might want to to, so I am allowing it
return Task.Run((Func<Task>)InternalFetchChildren);
}
private async Task InternalFetchChildren()
{
this.VerifyNotDisposed();
Results results = await _engine.DebuggedProcess.MICommandFactory.VarListChildren(_internalName, PropertyInfoFlags, ResultClass.None);
if (results.ResultClass == ResultClass.done)
{
TupleValue[] children = results.Contains("children")
? results.Find<ResultListValue>("children").FindAll<TupleValue>("child")
: new TupleValue[0];
int i = 0;
bool isArray = IsArrayType();
if (isArray)
{
CountChildren = results.FindUint("numchild");
Children = new VariableInformation[CountChildren];
foreach (var c in children)
{
Children[i] = new VariableInformation(c, this);
i++;
}
}
else if (IsMapType())
{
//
// support for gdb's pretty-printing built-in displayHint "map", from the gdb docs:
// 'Indicate that the object being printed is “map-like”, and that the
// children of this value can be assumed to alternate between keys and values.'
//
List<VariableInformation> listChildren = new List<VariableInformation>();
for (int p = 0; (p + 1) < children.Length; p += 2)
{
if (children[p].TryFindUint("numchild") > 0)
{
var variable = new VariableInformation("[" + (p / 2).ToString(CultureInfo.InvariantCulture) + "]", this);
variable.CountChildren = 2;
var first = new VariableInformation(children[p], variable, "first");
var second = new VariableInformation(children[p + 1], this, "second");
variable.Children = new VariableInformation[] { first, second };
variable.TypeName = FormattableString.Invariant($"std::pair<{first.TypeName}, {second.TypeName}>");
listChildren.Add(variable);
}
else
{
// One Variable is created for each pair returned with the first element (p) being the name of the child
// and the second element (p+1) becoming the value.
string name = children[p].TryFindString("value");
var variable = new VariableInformation(children[p + 1], this, '[' + name + ']');
listChildren.Add(variable);
}
}
Children = listChildren.ToArray();
CountChildren = (uint)Children.Length;
}
else
{
List<VariableInformation> listChildren = new List<VariableInformation>();
foreach (var c in children)
{
var variable = new VariableInformation(c, this);
enum_DBG_ATTRIB_FLAGS access = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_NONE;
if (variable.Name == "public")
{
access = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_ACCESS_PUBLIC;
variable.VariableNodeType = NodeType.AccessQualifier;
}
else if (variable.Name == "private")
{
access = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_ACCESS_PRIVATE;
variable.VariableNodeType = NodeType.AccessQualifier;
}
else if (variable.Name == "protected")
{
access = enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_ACCESS_PROTECTED;
variable.VariableNodeType = NodeType.AccessQualifier;
}
if (access != enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_NONE)
{
// Add this child's children
await variable.InternalFetchChildren();
foreach (var child in variable.Children)
{
((VariableInformation)child).Access = access;
listChildren.Add(child);
}
}
else
{
listChildren.Add(variable);
}
}
Children = listChildren.ToArray();
CountChildren = (uint)Children.Length;
}
}
else
{
Children = new VariableInformation[0];
CountChildren = 0;
}
if (_format != null)
{
foreach (var child in Children)
{
await child.Format();
}
}
}
private void SetAsError(string msg)
{
TypeName = "";
Value = msg;
CountChildren = 0;
Error = true;
}
private bool IsArrayType()
{
if (DisplayHint == "array")
{
return true;
}
else if (!string.IsNullOrWhiteSpace(TypeName))
{
return TypeName[TypeName.Length - 1] == ']';
}
return false;
}
private bool IsMapType()
{
return DisplayHint == "map";
}
public bool IsReadOnly()
{
if (!_attribsFetched)
{
if (string.IsNullOrEmpty(_internalName))
{
return true;
}
this.VerifyNotDisposed();
string attribute = string.Empty;
_engine.DebuggedProcess.WorkerThread.RunOperation(async () =>
{
attribute = await _engine.DebuggedProcess.MICommandFactory.VarShowAttributes(_internalName);
});
_isReadonly = (attribute == "noneditable");
_attribsFetched = true;
}
return _isReadonly;
}
public void Assign(string expression)
{
this.VerifyNotDisposed();
_engine.DebuggedProcess.WorkerThread.RunOperation(async () =>
{
int threadId = Client.GetDebuggedThread().Id;
uint frameLevel = _ctx.Level;
_engine.DebuggedProcess.FlushBreakStateData();
Value = await _engine.DebuggedProcess.MICommandFactory.VarAssign(_internalName, expression, threadId, frameLevel);
});
}
#region IDisposable Implementation
private bool _isDisposed = false;
private void VerifyNotDisposed()
{
if (_isDisposed)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool isDisposing)
{
_isDisposed = true;
//mi -var-delete deletes all children, so only top level variables should be added to the delete list
//Additionally, we create variables for anything we try to evaluate. Only succesful evaluations get internal names,
//so look for that.
if (!IsChild && !string.IsNullOrWhiteSpace(_internalName))
{
if (!_debuggedProcess.IsClosed)
{
lock (_debuggedProcess.VariablesToDelete)
{
_debuggedProcess.VariablesToDelete.Add(_internalName);
}
}
}
}
~VariableInformation()
{
this.Dispose(false);
}
#endregion
}
}