Wer meine vorherigen Einträge gelesen hat, der weiß das der MDdb ( Managed Debugger ) ein hilfreiches Werkzeug sein kann. Ich verwende diesen gern, detaillierte Bugreports zu erstellen. Hierfür wurde ein Service geschrieben indem der Debugger immer bei einer unbehandelten Exception aktive wurde. Dieser Service lädt alle verwendeten Variablen und dessen Werte und speichert diese in einer Datei.

Problem:
Obwohl der oben beschriebene Service sehr nützlich ist, gibt es einiges schachern. In diesem Blogeintrag gehen wir auf die Formatierung ein. Sobald eine Variabel geschrieben wird, verwendet Microsoft das folgende Format. In jeder Zeile ist jeweils eine Kind-Variable, die mittels Tabstops eingerückt wurden. Für das reine Lesen ist diese Darstellung ausreichend. Für eine automatische Analyse ist diese Darstellung nicht ausreichend. Hier wäre ein Parser notwendig der diese Format versteht und es auswerten kann.
Beispiel:

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
LPLMind.Example.ArchiveClient
    _Parameters=System.Collections.Generic.Dictionary`2<System.String,System.String>
            buckets=array [17]
                    [0] = 0
                    [1] = -1
                    [2] = 6
                    [3] = 5
                    [4] = 10
                    [5] = -1
                    [6] = -1
                    [7] = 4
                    [8] = -1
                    [9] = -1
                    [10] = -1
                    [11] = 9
                    [12] = 11
                    [13] = 12
                    [14] = -1
                    [15] = 8
                    [16] = -1
            entries=array [17]
                    [0] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [1] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [2] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [3] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [4] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [5] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [6] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [7] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [8] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [9] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [10] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [11] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [12] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [13] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [14] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [15] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
                    [16] = System.Collections.Generic.Dictionary`2+Entry<System.String,System.String>
            count=13
            version=13
            freeList=-1
            freeCount=0
            comparer=System.Collections.Generic.GenericEqualityComparer`1<System.String>
            keys=<null>
            values=<null>
            _syncRoot=<null>
    _Factory=PortCMIS.Client.Impl.SessionFactory
    _Session=<null>
    _Log=NLogLogger
            _Log=NLog.Logger
                    _loggerType=System.RuntimeType
                    _configuration=NLog.Internal.LoggerConfiguration
                    _isTraceEnabled=False
                    _isDebugEnabled=False
                    _isInfoEnabled=True
                    _isWarnEnabled=True
                    _isErrorEnabled=True
                    _isFatalEnabled=False
                    LoggerReconfigured=<null>
                    <Name>k__BackingField="Default"
                    <Factory>k__BackingField=NLog.LogFactory
            BeforeLogged=<null>
            AfterLogged=<null>
    _RootFolder=<null>
    _Disposed=False
    <InstanceId>k__BackingField=System.Guid
            _a=108708905
            _b=4093
            _c=19931
            _d=157
            _e=37
            _f=75
            _g=251
            _h=101
            _i=59
            _j=121
            _k=60
    <InstanceDateTime>k__BackingField=System.DateTimeOffset
            m_dateTime=System.DateTime
                    dateData=637218401922876399
            m_offsetMinutes=120

Lösung:
Meine Lösung nutzt einen anderen Weg als das schreiben einer Parsers. Ziel ist es die Ausgabe zu erweitern / verändern sodass ein Json Format ausgeben wird. Vorteil von Json ist das Libs gibt die dieses Format verstehen und eine passende Oberfläche, bzw. Navigation bieten. Leider entpuppt sich dieses Vorhaben als nicht ganz trivial. Eine Orientierung an der Klasse MDbgValue diese implementierte das oben beschriebene Format.

Leider ist die Klasse MDbgValue sealt und somit nicht vererbbar. Unsere Jsonvariante der Klasse MDbgValue wird somit vom MarshalByRefObject erben müssen.
Wie auch schon in MDbgValue verwenden wir dieselben Methoden, jedoch erweitern wir diese um einen JsonWriter. Das Ergebnis wird dann folglich im JsonWriter landen. Es gibt drei Hauptmethoden die zu anpassen sind. InternalGetValue, welches immer aufgerufen wird falls eine Variable ausgelesen werden soll. Hier sind alle Typen aufgelistet, sowohl auch die nativen Typen. PrintObject diese Methode ist für das Auslesen von komplexen Typen verantwortlich. Diese ruft InternalGetValue aus. PrintArray ist für das Auslesen von Arrays zuständig, diese nutzt auch die Methode InternalGetValue. Der untere Schnipsel zeigt das auswertet der Verschiedenen nativen Typen.

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
switch (corValue2.Type)
            {
                case CorElementType.ELEMENT_TYPE_R4:
                case CorElementType.ELEMENT_TYPE_R8:
                    jsonWriter.WriteValue(
                        corValue2.CastToGenericValue()
                            .GetValue());
                    return;
                case CorElementType.ELEMENT_TYPE_BOOLEAN:
                case CorElementType.ELEMENT_TYPE_CHAR:
                case CorElementType.ELEMENT_TYPE_I1:
                case CorElementType.ELEMENT_TYPE_U1:
                case CorElementType.ELEMENT_TYPE_I2:
                case CorElementType.ELEMENT_TYPE_U2:
                case CorElementType.ELEMENT_TYPE_I4:
                case CorElementType.ELEMENT_TYPE_U4:
                case CorElementType.ELEMENT_TYPE_I8:
                case CorElementType.ELEMENT_TYPE_U8:
                    var obj = corValue2.CastToGenericValue()
                        .GetValue();
                    jsonWriter.WriteValue(obj);
                    return;
                case CorElementType.ELEMENT_TYPE_U:
                case CorElementType.ELEMENT_TYPE_I:
                    var ptj = corValue2.CastToGenericValue()
                        .GetValue();
                    jsonWriter.WriteValue(ptj.ToString());
                    return;

                case CorElementType.ELEMENT_TYPE_STRING:
                    var stringValue = corValue2.CastToStringValue();
                    jsonWriter.WriteValue(stringValue.String);
                    return;
                case CorElementType.ELEMENT_TYPE_PTR:
                    jsonWriter.WriteValue("N/A");
                    return;
                case CorElementType.ELEMENT_TYPE_VALUETYPE:
                case CorElementType.ELEMENT_TYPE_CLASS:
                    var objectValue = corValue2.CastToObjectValue();
                    PrintObject(
                        jsonWriter,
                        objectValue,
                        expandDepth,
                        canDoFunceval);
                    return;
                case CorElementType.ELEMENT_TYPE_ARRAY:
                case CorElementType.ELEMENT_TYPE_SZARRAY:
                    var arrayValue = corValue2.CastToArrayValue();
                    PrintArray(
                        jsonWriter,
                        arrayValue,
                        expandDepth,
                        canDoFunceval);
                    return;
                case CorElementType.ELEMENT_TYPE_FNPTR:
                    jsonWriter.WriteValue(
                        "0x" + corValue2.CastToReferenceValue()
                            .Value.ToString("X"));
                    return;
                default:
                    jsonWriter.WritePropertyName(corValue2.Type.ToString());
                    jsonWriter.WriteValue("N/A");
                    return;
            }

Resultat:

Das Resultat falls alles richtig gemacht wurde sieht wie folgt aus:

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
{
                    "Name": "this",
                    "TypeName": "Net.LPLMmind.ArchiveClient",
                    "ValueO": {
                        "_Parameters": {
                            "buckets": [
                                0,
                                -1,
                                6,
                                5,
                                10,
                                -1,
                                -1,
                                4,
                                -1,
                                -1,
                                -1,
                                9,
                                11,
                                12,
                                -1,
                                8,
                                -1
                            ],
                            "entries": [
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A",
                                "N/A"
                            ],
                            "count": 13,
                            "version": 13,
                            "freeList": -1,
                            "freeCount": 0,
                            "comparer": {
                                "Type-": "System.Collections.Generic.GenericEqualityComparer`1<System.String>"
                            },
                            "keys": null,
                            "values": null,
                            "_syncRoot": null,
                            "Type-": "System.Collections.Generic.Dictionary`2<System.String,System.String>"
                        },
                        "_Factory": {
                            "Type-": "PortCMIS.Client.Impl.SessionFactory"
                        },
                        "_Session": null,
                        "_Log": {
                            "BeforeLogged": null,
                            "AfterLogged": null,
                            "_Log": {
                                "_loggerType": "N/A",
                                "_configuration": "N/A",
                                "_isTraceEnabled": false,
                                "_isDebugEnabled": false,
                                "_isInfoEnabled": true,
                                "_isWarnEnabled": true,
                                "_isErrorEnabled": true,
                                "_isFatalEnabled": false,
                                "LoggerReconfigured": null,
                                "<Name>k__BackingField": "Default",
                                "<Factory>k__BackingField": "N/A",
                                "--Type": "NLog.Logger"
                            },
                            "Type-": "NLogLogger"
                        },
                        "_RootFolder": null,
                        "_Disposed": false,
                        "<InstanceId>k__BackingField": {
                            "_a": -877632076,
                            "_b": -10274,
                            "_c": 16639,
                            "_d": 130,
                            "_e": 1,
                            "_f": 191,
                            "_g": 177,
                            "_h": 120,
                            "_i": 205,
                            "_j": 157,
                            "_k": 74,
                            "--Type": "System.Guid"
                        },
                        "<InstanceDateTime>k__BackingField": {
                            "m_dateTime": {
                                "dateData": 637221137525654467,
                                "Type-": "System.DateTime"
                            },
                            "m_offsetMinutes": 120,
                            "Type-": "System.DateTimeOffset"
                        },
                        "Type-": "Net.LPLMind.ArchiveClient"
                    }
                }

Dies kann nun für weitere Analysen genutzt werden. Den gesamten Quellcode findet ihr unten.

JsonMDbgValue.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.CorMetadata;
using Microsoft.Samples.Debugging.MdbgEngine;
using Newtonsoft.Json;

namespace Net.LPLMind.StackTraceApp
{
    /// <summary>
    /// A MDbgValue representation to print the debug values into an Json format.
    /// </summary>
    internal class JsonMDbgValue : MarshalByRefObject
    {
        private JsonMDbgValue[] m_cachedFields;

       
        public static string[] WhiteList =
        {
            "^System.[^.]+$", //Alle "einfache" typen
            "^System.Collections.*" //Alle Collections
        };

        /// <summary>
        /// Creates a new instance of the JsonMDbgValue Object.
        /// This constructor is public so that applications can use this class to print values (CorValue).
        /// CorValue\'s can be returned for example by funceval(CorEval.Result).
        /// </summary>
        /// <param name="process">The Process that will own the Value.</param>
        /// <param name="value">The CorValue that this JsonMDbgValue will start with.</param>
        public JsonMDbgValue(
            MDbgProcess process,
            CorValue value)
        {
            Initialize(process, null, value);
        }

        /// <summary>
        /// Creates a new instance of the JsonMDbgValue Object.
        /// This constructor is public so that applications can use this class to print values (CorValue).
        /// CorValue\'s can be returned for example by funceval(CorEval.Result).
        /// </summary>
        /// <param name="process">The Process that will own the Value.</param>
        /// <param name="name">The name of the variable.</param>
        /// <param name="value">The CorValue that this JsonMDbgValue will start with.</param>
        public JsonMDbgValue(
            MDbgProcess process,
            string name,
            CorValue value)
        {
            Initialize(process, name, value);
        }

        private void Initialize(
            MDbgProcess process,
            string name,
            CorValue value)
        {
            Process = process;
            Name = name;
            CorValue = value;
        }

        /// <summary>The CorValue stored in the JsonMDbgValue.</summary>
        /// <value>The CorValue.</value>
        public CorValue CorValue { get; private set; }

        /// <summary>The Process that owns this Value.</summary>
        /// <value>The Process.</value>
        public MDbgProcess Process { get; private set; }

        /// <summary>The Name of this Value.</summary>
        /// <value>The Name.</value>
        public string Name { get; private set; }

        /// <summary>The Name of this Type.</summary>
        /// <value>The TypeName.</value>
        public string TypeName
        {
            get
            {
                if (CorValue == null) return "N/A";
                return InternalUtil.PrintCorType(Process, CorValue.ExactType);
            }
        }

        /// <summary>Is this type a complex type.</summary>
        /// <value>true if it is complex, else false.</value>
        public bool IsComplexType
        {
            get
            {
                if (CorValue == null) return false;
                CorValue corValue;
                try
                {
                    corValue = Dereference(CorValue);
                }
                catch (COMException ex)
                {
                    if (ex.ErrorCode == -2146233595) return false;
                    throw;
                }

                if (corValue == null) return false;
                if (corValue.Type != CorElementType.ELEMENT_TYPE_CLASS) return corValue.Type == CorElementType.ELEMENT_TYPE_VALUETYPE;
                return true;
            }
        }

        /// <summary>Is this type an array type.</summary>
        /// <value>true if it is an array type, else false.</value>
        public bool IsArrayType
        {
            get
            {
                if (CorValue == null) return false;
                CorValue corValue;
                try
                {
                    corValue = Dereference(CorValue);
                }
                catch (COMException ex)
                {
                    if (ex.ErrorCode == -2146233595) return false;
                    throw;
                }

                if (corValue == null) return false;
                if (corValue.Type != CorElementType.ELEMENT_TYPE_SZARRAY) return corValue.Type == CorElementType.ELEMENT_TYPE_ARRAY;
                return true;
            }
        }

        /// <summary>Is this Value Null.</summary>
        /// <value>true if it is Null, else false.</value>
        public bool IsNull
        {
            get
            {
                if (CorValue == null) return true;
                CorValue corValue;
                try
                {
                    corValue = Dereference(CorValue);
                }
                catch (COMException ex)
                {
                    if (ex.ErrorCode == -2146233595) return false;
                    throw;
                }

                return corValue == null;
            }
        }

        /// <summary>Gets the Value.</summary>
        /// <param name="expand">Should it expand inner objects.</param>
        /// <returns>A string representation of the Value.</returns>
        public void GetStringValue(
            JsonWriter jsonWriter,
            bool expand)
        {
            GetStringValue(jsonWriter, expand ? 1 : 0);
        }

        /// <summary>Gets the Value.</summary>
        /// <param name="expandDepth">
        ///     How deep inner objects should be expanded. Value
        ///     0 means don\'t expand at all.
        /// </param>
        /// <returns>A string representation of the Value.</returns>
        public void GetStringValue(
            JsonWriter jsonWriter,
            int expandDepth)
        {
            GetStringValue(jsonWriter, expandDepth, true);
        }

        /// <summary>Gets the Value.</summary>
        /// <param name="expandDepth">
        ///     How deep inner objects should be expanded. Value
        ///     0 means don\'t expand at all.
        /// </param>
        /// <param name="canDoFunceval">Set to true if ToString() should be called to get better description.</param>
        /// <returns>A string representation of the Value.</returns>
        public void GetStringValue(
            JsonWriter jsonWriter,
            int expandDepth,
            bool canDoFunceval)
        {
            InternalGetValue(jsonWriter, expandDepth, canDoFunceval);
        }

        /// <summary>Gets the specified Field.</summary>
        /// <param name="name">The Name of the Field to get.</param>
        /// <returns>The Value of the specified Field.</returns>
        public JsonMDbgValue GetField(
            string name)
        {
            var mdbgValue = (JsonMDbgValue) null;
            foreach (var field in GetFields())
                if (field.Name.Equals(name))
                {
                    mdbgValue = field;
                    break;
                }

            if (mdbgValue == null) throw new MDbgValueException("Field \'" + name + "\' not found.");
            return mdbgValue;
        }

        /// <summary>Gets all the Fields</summary>
        /// <returns>An array of all Fields.</returns>
        public JsonMDbgValue[] GetFields()
        {
            if (!IsComplexType) throw new MDbgValueException("Type is not complex");
            if (m_cachedFields == null) m_cachedFields = InternalGetFields();
            return m_cachedFields;
        }


        /// <summary>
        ///     Gets or Sets the Value of the JsonMDbgValue to the given value.
        /// </summary>
        /// <value>This is exposed as an Object but can a primitive type, CorReferenceValue, or CorGenericValue.</value>
        public object Value
        {
            get => throw new NotImplementedException();
            set
            {
                if (value == null) throw new ArgumentNullException(nameof(value));
                if (value is CorReferenceValue)
                {
                    var referenceValue = CorValue.CastToReferenceValue();
                    if (referenceValue == null) throw new MDbgValueWrongTypeException("cannot assign reference value to non-reference value");
                    referenceValue.Value = ((CorReferenceValue) value).Value;
                }
                else if (value is CorGenericValue)
                {
                    GetGenericValue()
                        .SetValue(((CorGenericValue) value).GetValue());
                }
                else
                {
                    if (!value.GetType()
                        .IsPrimitive)
                        throw new MDbgValueWrongTypeException("Value is of unsupported type.");
                    GetGenericValue()
                        .SetValue(value);
                }
            }
        }

        internal void InternalSetName(
            string variableName)
        {
            Name = variableName;
        }

        /// <summary>
        ///     Main methode to get an json string of on object
        /// </summary>
        /// <param name="jsonWriter"></param>
        /// <param name="expandDepth"></param>
        /// <param name="canDoFunceval"></param>
        private void InternalGetValue(
            JsonWriter jsonWriter,
            int expandDepth,
            bool canDoFunceval)
        {

            if (!isInWhitelist(this.TypeName))
            {
                jsonWriter.WriteValue("N/A");
                return;
            }

            var corValue1 = CorValue;
            if (corValue1 == null)
            {
                jsonWriter.WriteValue("N/A");
                return;
            }

            CorValue corValue2;
            try
            {
                corValue2 = Dereference(corValue1);
            }
            catch (COMException ex)
            {
                if (ex.ErrorCode == -2146233595)
                {
                    jsonWriter.WriteValue("N/A");
                    return;
                }

                throw;
            }

            if (corValue2 == null)
            {
                jsonWriter.WriteNull();
                return;
            }

            Unbox(ref corValue2);
            switch (corValue2.Type)
            {
                case CorElementType.ELEMENT_TYPE_R4:
                case CorElementType.ELEMENT_TYPE_R8:
                    jsonWriter.WriteValue(
                        corValue2.CastToGenericValue()
                            .GetValue());
                    return;
                case CorElementType.ELEMENT_TYPE_BOOLEAN:
                case CorElementType.ELEMENT_TYPE_CHAR:
                case CorElementType.ELEMENT_TYPE_I1:
                case CorElementType.ELEMENT_TYPE_U1:
                case CorElementType.ELEMENT_TYPE_I2:
                case CorElementType.ELEMENT_TYPE_U2:
                case CorElementType.ELEMENT_TYPE_I4:
                case CorElementType.ELEMENT_TYPE_U4:
                case CorElementType.ELEMENT_TYPE_I8:
                case CorElementType.ELEMENT_TYPE_U8:
                    var obj = corValue2.CastToGenericValue()
                        .GetValue();
                    jsonWriter.WriteValue(obj);
                    return;
                case CorElementType.ELEMENT_TYPE_U:
                case CorElementType.ELEMENT_TYPE_I:
                    var ptj = corValue2.CastToGenericValue()
                        .GetValue();
                    jsonWriter.WriteValue(ptj.ToString());
                    return;

                case CorElementType.ELEMENT_TYPE_STRING:
                    var stringValue = corValue2.CastToStringValue();
                    jsonWriter.WriteValue(stringValue.String);
                    return;
                case CorElementType.ELEMENT_TYPE_PTR:
                    jsonWriter.WriteValue("N/A");
                    return;
                case CorElementType.ELEMENT_TYPE_VALUETYPE:
                case CorElementType.ELEMENT_TYPE_CLASS:
                    var objectValue = corValue2.CastToObjectValue();
                    PrintObject(
                        jsonWriter,
                        objectValue,
                        expandDepth,
                        canDoFunceval);
                    return;
                case CorElementType.ELEMENT_TYPE_ARRAY:
                case CorElementType.ELEMENT_TYPE_SZARRAY:
                    var arrayValue = corValue2.CastToArrayValue();
                    PrintArray(
                        jsonWriter,
                        arrayValue,
                        expandDepth,
                        canDoFunceval);
                    return;
                case CorElementType.ELEMENT_TYPE_FNPTR:
                    jsonWriter.WriteValue(
                        "0x" + corValue2.CastToReferenceValue()
                            .Value.ToString("X"));
                    return;
                default:
                    jsonWriter.WritePropertyName(corValue2.Type.ToString());
                    jsonWriter.WriteValue("N/A");
                    return;
            }
        }

        private void Unbox(
            ref CorValue value)
        {
            var boxValue = value.CastToBoxValue();
            if (!(boxValue != null)) return;
            value = boxValue.GetObject();
        }

        /// <summary>
        /// Recursively dereference the input value until we finally find a non-dereferenceable
        /// value.  Along the way, optionally build up a "ptr string" that shows the addresses
        /// we dereference, separated by "->".
        /// </summary>
        /// <param name="value">Value to dereference</param>
        /// <param name="ptrStringBuilder">
        ///     StringBuilder if caller wants us to generate
        ///     a "ptr string" (in which case we\'ll stick it there).  If caller doesn\'t want
        ///     a ptr string, this can be null
        /// </param>
        /// <returns>CorValue we arrive at after dereferencing as many times as we can</returns>
        private CorValue Dereference(
            CorValue value)
        {
            while (true)
            {
                var referenceValue = value.CastToReferenceValue();
                if (!(referenceValue == null))
                {
                    if (!referenceValue.IsNull)
                    {
                        var corValue = (CorValue) null;
                        try
                        {
                            corValue = referenceValue.Dereference();
                        }
                        catch (COMException ex)
                        {
                            if (ex.ErrorCode != -2146231222) throw;
                        }

                        if (!(corValue == null))
                            value = corValue;
                        else
                            return value;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    return value;
                }
            }

            return null;
        }

        /// <summary>
        /// Return the enum string
        /// </summary>
        /// <param name="ov"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string InternalGetEnumString(
            CorObjectValue ov,
            MetadataType type)
        {
            var enumValues = type.EnumValues;
            var uint64 = Convert.ToUInt64(
                ov.CastToGenericValue()
                    .UnsafeGetValueAsType(type.EnumUnderlyingType),
                CultureInfo.InvariantCulture);
            var stringBuilder = new StringBuilder();
            var num = uint64;
            var flag = true;
            for (var index = enumValues.Count - 1; index >= 0; --index)
                if ((long) enumValues[index]
                        .Value == (long) uint64 || type.ReallyIsFlagsEnum && enumValues[index]
                        .Value != 0UL && ((long) enumValues[index]
                                              .Value & (long) uint64) == (long) enumValues[index]
                        .Value)
                {
                    num &= ~enumValues[index]
                        .Value;
                    if (!flag)
                    {
                        if (type.ReallyIsFlagsEnum)
                            stringBuilder.Insert(0, ", ");
                        else
                            stringBuilder.Insert(0, " / ");
                    }

                    stringBuilder.Insert(
                        0,
                        enumValues[index]
                            .Key);
                    flag = false;
                }

            if (num != 0UL)
            {
                if (flag)
                    stringBuilder.Insert(0, num);
                else
                    stringBuilder.AppendFormat(" (Unnamed bits: {0})", num);
            }

            return stringBuilder.ToString();
        }

        private bool isInWhitelist(
            string typeString)
        {
            foreach (var item in WhiteList)
            {
                bool isMatch = Regex.IsMatch(typeString, item);
                if (isMatch) return true;
            }
            return false;
        }

        /// <summary>
        /// Print an Object into Jsonformat
        /// </summary>
        /// <param name="jsonWriter">The Json Writer</param>
        /// <param name="ov">The object to print</param>
        /// <param name="expandDepth">The Max depth for the object</param>
        /// <param name="canDoFunceval"></param>
        private void PrintObject(
            JsonWriter jsonWriter,
            CorObjectValue ov,
            int expandDepth,
            bool canDoFunceval)
        {
            var flag = true;


            var stringBuilderType = new StringBuilder();
            string coreType=InternalUtil.PrintCorType(Process, ov.ExactType);
            stringBuilderType.Append(coreType);
            if (expandDepth > 0 )
            {
                jsonWriter.WriteStartObject();
                if (IsComplexType)
                {
                    var fields = GetFields();
                    var fieldNames = new HashSet<string>();
                    foreach (var field in fields)
                    {
                        if (fieldNames.Contains(field.Name)) continue;

                        jsonWriter.WritePropertyName(field.Name);
                        field.GetStringValue(jsonWriter, expandDepth - 1, false);
                        fieldNames.Add(field.Name);
                    }
                }

                if (ov.IsValueClass && canDoFunceval)
                {
                    var corClass = ov.ExactType.Class;
                    var type = Process.Modules.Lookup(corClass.Module)
                        .Importer.GetType(corClass.Token) as MetadataType;
                    if (type.ReallyIsEnum)
                        stringBuilderType.AppendFormat(" <{0}>", InternalGetEnumString(ov, type));
                    else if (Process.IsRunning)
                        stringBuilderType.Append(" <N/A during run>");
                    else
                        try
                        {
                            var active = Process.Threads.Active;
                            var heapValue = ov.CastToHeapValue();
                            var corValue = !(heapValue != null) ? ov : (CorValue) heapValue.CreateHandle(CorDebugHandleType.HANDLE_WEAK_TRACK_RESURRECTION);
                            try
                            {
                                var eval = Process.Threads.Active.CorThread.CreateEval();
                                Process.CorProcess.SetAllThreadsDebugState(CorDebugThreadState.THREAD_SUSPEND, active.CorThread);
                                var mdbgFunction = Process.ResolveFunctionName(
                                    null,
                                    "System.Object",
                                    "ToString",
                                    corValue.ExactType.Class.Module.Assembly.AppDomain);
                                eval.CallFunction(
                                    mdbgFunction.CorFunction,
                                    new CorValue[1]
                                    {
                                        corValue
                                    });
                                Process.Go();
                                while (true)
                                {
                                    Process.StopEvent.WaitOne();
                                    if (!(Process.StopReason is EvalCompleteStopReason))
                                    {
                                        if (!(Process.StopReason is ProcessExitedStopReason) && !(Process.StopReason is EvalExceptionStopReason))
                                        {
                                            Process.Go();
                                        }
                                        else
                                        {
                                            stringBuilderType.Append(" <N/A cannot evaluate>");
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }

                                if (eval.Result == null)
                                {
                                    stringBuilderType.Append("N/A");
                                }
                                else
                                {
                                    CorValue corValue2 = null;
                                    try
                                    {
                                        corValue2 = Dereference(eval.Result);
                                        stringBuilderType.Append("<" + InternalUtil.PrintCorType(Process, corValue2.ExactType) + ">");
                                    }
                                    catch (COMException ex)
                                    {
                                        if (ex.ErrorCode == -2146233595) stringBuilderType.Append("N/A");
                                    }

                                    if (corValue2 == null) stringBuilderType.Append("N/A");
                                }
                            }
                            catch (COMException ex)
                            {
                                if (ex.ErrorCode != -2146233573) stringBuilderType.Append("N/A");
                            }
                            catch (NotImplementedException ex)
                            {
                                flag = false;
                            }
                            finally
                            {
                                if (flag) Process.CorProcess.SetAllThreadsDebugState(CorDebugThreadState.THREAD_RUN, active.CorThread);
                            }
                        }
                        catch (MDbgNoActiveInstanceException e)
                        {
                            stringBuilderType.Append("N/A");
                        }
                }

                jsonWriter.WritePropertyName("Type-");

                jsonWriter.WriteValue(stringBuilderType.ToString());
                jsonWriter.WriteEndObject();
                return;
            }

            jsonWriter.WriteValue("N/A");
        }

        /// <summary>
        /// Print an Array into a json format
        /// </summary>
        /// <param name="jsonWriter"></param>
        /// <param name="av"></param>
        /// <param name="expandDepth"></param>
        /// <param name="canDoFunceval"></param>
        private void PrintArray(
            JsonWriter jsonWriter,
            CorArrayValue av,
            int expandDepth,
            bool canDoFunceval)
        {
            jsonWriter.WriteStartArray();
            var dimensions = av.GetDimensions();
            if (expandDepth > 0 && av.Rank == 1 && av.ElementType != CorElementType.ELEMENT_TYPE_VOID)
                for (var position = 0; position < dimensions[0]; ++position)
                {
                    var mdbgValue = new JsonMDbgValue(Process, av.GetElementAtPosition(position));

                    mdbgValue.GetStringValue(jsonWriter, expandDepth - 1, canDoFunceval);
                }

            jsonWriter.WriteEndArray();
        }

        /// <summary>
        ///     Return fields f an object
        /// </summary>
        /// <returns></returns>
        private JsonMDbgValue[] InternalGetFields()
        {
            var mdbgValueList = new List<JsonMDbgValue>();
            var corValue1 = Dereference(CorValue);
            if (corValue1 == null) throw new MDbgValueException("null value");
            Unbox(ref corValue1);
            var objectValue = corValue1.CastToObjectValue();
            var exactType = objectValue.ExactType;
            var frame = (CorFrame) null;
            if (Process.Threads.HaveActive && Process.Threads.Active.HaveCurrentFrame)
            {
                var mdbgFrame = Process.Threads.Active.CurrentFrame;
                while (mdbgFrame != null && !mdbgFrame.IsManaged) mdbgFrame = mdbgFrame.NextUp;
                if (mdbgFrame != null) frame = mdbgFrame.CorFrame;
            }

            var managedClass = objectValue.Class;
            var mdbgModule = Process.Modules.Lookup(managedClass.Module);
            while (true)
            {
                foreach (MetadataFieldInfo field in mdbgModule.Importer.GetType(managedClass.Token)
                    .GetFields())
                {
                    var corValue2 = (CorValue) null;
                    try
                    {
                        if (field.IsLiteral) continue;
                        if (field.IsStatic)
                        {
                            if (!(frame == null))
                                corValue2 = exactType.GetStaticFieldValue(field.MetadataToken, frame);
                            else
                                continue;
                        }
                        else
                        {
                            corValue2 = objectValue.GetFieldValue(managedClass, field.MetadataToken);
                        }
                    }
                    catch (COMException ex)
                    {
                    }

                    mdbgValueList.Add(new JsonMDbgValue(Process, field.Name, corValue2));
                }

                exactType = exactType.Base;
                if (!(exactType == null))
                {
                    managedClass = exactType.Class;
                    mdbgModule = Process.Modules.Lookup(managedClass.Module);
                }
                else
                {
                    break;
                }
            }

            return mdbgValueList.ToArray();
        }

        private CorGenericValue GetGenericValue()
        {
            var genericValue = CorValue.CastToGenericValue();
            if (genericValue == null) throw new MDbgValueWrongTypeException();
            return genericValue;
        }
    }
}
Kategorien: Allgemein

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert