-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathSoftDebuggerAdaptor.cs
More file actions
2286 lines (1839 loc) · 71.9 KB
/
SoftDebuggerAdaptor.cs
File metadata and controls
2286 lines (1839 loc) · 71.9 KB
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
//
// SoftDebuggerAdaptor.cs
//
// Authors: Lluis Sanchez Gual <lluis@novell.com>
// Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
// Copyright (c) 2011,2012 Xamain Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Mono.Debugger.Soft;
using Mono.Debugging.Backend;
using Mono.Debugging.Evaluation;
using Mono.Debugging.Client;
namespace Mono.Debugging.Soft
{
public class SoftDebuggerAdaptor : ObjectValueAdaptor
{
static readonly Dictionary<Type, OpCode> convertOps = new Dictionary<Type, OpCode> ();
delegate object TypeCastDelegate (object value);
static SoftDebuggerAdaptor ()
{
convertOps.Add (typeof (double), OpCodes.Conv_R8);
convertOps.Add (typeof (float), OpCodes.Conv_R4);
convertOps.Add (typeof (ulong), OpCodes.Conv_U8);
convertOps.Add (typeof (uint), OpCodes.Conv_U4);
convertOps.Add (typeof (ushort), OpCodes.Conv_U2);
convertOps.Add (typeof (char), OpCodes.Conv_U2);
convertOps.Add (typeof (byte), OpCodes.Conv_U1);
convertOps.Add (typeof (long), OpCodes.Conv_I8);
convertOps.Add (typeof (int), OpCodes.Conv_I4);
convertOps.Add (typeof (short), OpCodes.Conv_I2);
convertOps.Add (typeof (sbyte), OpCodes.Conv_I1);
}
public SoftDebuggerAdaptor ()
{
}
public SoftDebuggerSession Session {
get; set;
}
static string GetPrettyMethodName (EvaluationContext ctx, MethodMirror method)
{
var name = new System.Text.StringBuilder ();
name.Append (ctx.Adapter.GetDisplayTypeName (method.ReturnType.FullName));
name.Append (" ");
name.Append (ctx.Adapter.GetDisplayTypeName (method.DeclaringType.FullName));
name.Append (".");
name.Append (method.Name);
if (method.VirtualMachine.Version.AtLeast (2, 12)) {
if (method.IsGenericMethodDefinition || method.IsGenericMethod) {
name.Append ("<");
if (method.VirtualMachine.Version.AtLeast (2, 15)) {
var argTypes = method.GetGenericArguments ();
for (int i = 0; i < argTypes.Length; i++) {
if (i != 0)
name.Append (", ");
name.Append (ctx.Adapter.GetDisplayTypeName (argTypes[i].FullName));
}
}
name.Append (">");
}
}
name.Append (" (");
var @params = method.GetParameters ();
for (int i = 0; i < @params.Length; i++) {
if (i != 0)
name.Append (", ");
if (@params[i].Attributes.HasFlag (ParameterAttributes.Out)) {
if (@params[i].Attributes.HasFlag (ParameterAttributes.In))
name.Append ("ref ");
else
name.Append ("out ");
}
name.Append (ctx.Adapter.GetDisplayTypeName (@params[i].ParameterType.FullName));
name.Append (" ");
name.Append (@params[i].Name);
}
name.Append (")");
return name.ToString ();
}
string InvokeToString (SoftEvaluationContext ctx, MethodMirror method, object obj)
{
try {
var res = ctx.RuntimeInvoke (method, obj, new Value [0]) as StringMirror;
if (res != null) {
return MirrorStringToString (ctx, res);
} else {
return null;
}
} catch {
return GetDisplayTypeName (GetValueTypeName (ctx, obj));
}
}
public override string CallToString (EvaluationContext ctx, object obj)
{
if (obj == null)
return null;
var str = obj as StringMirror;
if (str != null)
return str.Value;
var em = obj as EnumMirror;
if (em != null)
return em.StringValue;
var primitive = obj as PrimitiveValue;
if (primitive != null)
return primitive.Value.ToString ();
var pointer = obj as PointerValue;
if (pointer != null)
return string.Format ("0x{0:x}", pointer.Address);
var cx = (SoftEvaluationContext) ctx;
var sm = obj as StructMirror;
var om = obj as ObjectMirror;
if (sm != null && sm.Type.IsPrimitive) {
// Boxed primitive
if (sm.Fields.Length > 0 && (sm.Fields[0] is PrimitiveValue))
return ((PrimitiveValue) sm.Fields[0]).Value.ToString ();
} else if (om != null && cx.Options.AllowTargetInvoke) {
var method = OverloadResolve (cx, om.Type, "ToString", null, new TypeMirror[0], true, false, false);
if (method != null && method.DeclaringType.FullName != "System.Object")
return InvokeToString (cx, method, obj);
} else if (sm != null && cx.Options.AllowTargetInvoke) {
var method = OverloadResolve (cx, sm.Type, "ToString", null, new TypeMirror[0], true, false, false);
if (method != null && method.DeclaringType.FullName != "System.ValueType")
return InvokeToString (cx, method, obj);
}
return GetDisplayTypeName (GetValueTypeName (ctx, obj));
}
public override object TryConvert (EvaluationContext ctx, object obj, object targetType)
{
var res = TryCast (ctx, obj, targetType);
if (res != null || obj == null)
return res;
var otype = GetValueType (ctx, obj) as Type;
if (otype != null) {
var tm = targetType as TypeMirror;
if (tm != null)
targetType = Type.GetType (tm.FullName, false);
var tt = targetType as Type;
if (tt != null) {
try {
var primitive = obj as PrimitiveValue;
if (primitive != null)
obj = primitive.Value;
res = System.Convert.ChangeType (obj, tt);
return CreateValue (ctx, res);
} catch {
return null;
}
}
}
return null;
}
static Dictionary<string, TypeCastDelegate> typeCastDelegatesCache = new Dictionary<string, TypeCastDelegate> ();
static TypeCastDelegate GenerateTypeCastDelegate (string methodName, Type fromType, Type toType)
{
lock(typeCastDelegatesCache) {
TypeCastDelegate cached;
if (typeCastDelegatesCache.TryGetValue (methodName, out cached))
return cached;
var argTypes = new [] { typeof (object) };
var method = new DynamicMethod (methodName, typeof (object), argTypes, true);
ILGenerator il = method.GetILGenerator ();
ConstructorInfo ctorInfo;
MethodInfo methodInfo;
OpCode conv;
il.Emit (OpCodes.Ldarg_0);
il.Emit (OpCodes.Unbox_Any, fromType);
if (fromType.IsSubclassOf (typeof (Nullable))) {
PropertyInfo propInfo = fromType.GetProperty ("Value");
methodInfo = propInfo.GetGetMethod ();
il.Emit (OpCodes.Stloc_0);
il.Emit (OpCodes.Ldloca_S);
il.Emit (OpCodes.Call, methodInfo);
fromType = methodInfo.ReturnType;
}
if (!convertOps.TryGetValue (toType, out conv)) {
argTypes = new [] { fromType };
if (toType == typeof (string)) {
methodInfo = fromType.GetMethod ("ToString", new Type [0]);
il.Emit (OpCodes.Call, methodInfo);
} else if ((methodInfo = toType.GetMethod ("op_Explicit", argTypes)) != null) {
il.Emit (OpCodes.Call, methodInfo);
} else if ((methodInfo = toType.GetMethod ("op_Implicit", argTypes)) != null) {
il.Emit (OpCodes.Call, methodInfo);
} else if ((ctorInfo = toType.GetConstructor (argTypes)) != null) {
il.Emit (OpCodes.Call, ctorInfo);
} else {
// No idea what else to try...
throw new InvalidCastException ();
}
} else {
il.Emit (conv);
}
il.Emit (OpCodes.Box, toType);
il.Emit (OpCodes.Ret);
cached = (TypeCastDelegate)method.CreateDelegate (typeof (TypeCastDelegate));
typeCastDelegatesCache [methodName] = cached;
return cached;
}
}
static object DynamicCast (object value, Type target)
{
var methodName = string.Format ("CastFrom{0}To{1}", value.GetType ().Name, target.Name);
var method = GenerateTypeCastDelegate (methodName, value.GetType (), target);
return method.Invoke (value);
}
static bool CanForceCast (EvaluationContext ctx, TypeMirror fromType, TypeMirror toType)
{
var cx = (SoftEvaluationContext) ctx;
MethodMirror method;
// check for explicit and implicit cast operators in the target type
method = OverloadResolve (cx, toType, "op_Explicit", null, new [] { fromType }, false, true, false, false);
if (method != null)
return true;
method = OverloadResolve (cx, toType, "op_Implicit", null, new [] { fromType }, false, true, false, false);
if (method != null)
return true;
// check for explicit and implicit cast operators on the source type
method = OverloadResolve (cx, fromType, "op_Explicit", null, toType, new [] { fromType }, false, true, false, false);
if (method != null)
return true;
method = OverloadResolve (cx, fromType, "op_Implicit", null, toType, new [] { fromType }, false, true, false, false);
if (method != null)
return true;
method = OverloadResolve (cx, toType, ".ctor", null, new [] { fromType }, true, false, false, false);
if (method != null)
return true;
return false;
}
object TryForceCast (EvaluationContext ctx, Value value, TypeMirror fromType, TypeMirror toType)
{
var cx = (SoftEvaluationContext) ctx;
MethodMirror method;
// check for explicit and implicit cast operators in the target type
method = OverloadResolve (cx, toType, "op_Explicit", null, new [] { fromType }, false, true, false, false);
if (method != null)
return cx.RuntimeInvoke (method, toType, new [] { value });
method = OverloadResolve (cx, toType, "op_Implicit", null, new [] { fromType }, false, true, false, false);
if (method != null)
return cx.RuntimeInvoke (method, toType, new [] { value });
// check for explicit and implicit cast operators on the source type
method = OverloadResolve (cx, fromType, "op_Explicit", null, toType, new [] { fromType }, false, true, false, false);
if (method != null)
return cx.RuntimeInvoke (method, fromType, new [] { value });
method = OverloadResolve (cx, fromType, "op_Implicit", null, toType, new [] { fromType }, false, true, false, false);
if (method != null)
return cx.RuntimeInvoke (method, fromType, new [] { value });
// Finally, try a ctor...
try {
return CreateValue (ctx, toType, value);
} catch {
return null;
}
}
public override object TryCast (EvaluationContext ctx, object val, object type)
{
var cx = (SoftEvaluationContext) ctx;
var toType = type as TypeMirror;
TypeMirror fromType;
if (val == null)
return null;
var valueType = GetValueType (ctx, val);
fromType = valueType as TypeMirror;
// If we are trying to cast into non-primitive/enum value(e.g. System.nint)
// that class might have implicit operator and this must be handled via TypeMirrors
if (toType != null && !toType.IsPrimitive && !toType.IsEnum)
fromType = ToTypeMirror (ctx, valueType);
if (fromType != null) {
if (toType != null && toType.IsAssignableFrom (fromType))
return val;
// Try casting the primitive type of the enum
var em = val as EnumMirror;
if (em != null)
return TryCast (ctx, CreateValue (ctx, em.Value), type);
if (toType == null)
return null;
MethodMirror method;
if (fromType.IsGenericType && fromType.FullName.StartsWith ("System.Nullable`1", StringComparison.Ordinal)) {
method = OverloadResolve (cx, fromType, "get_Value", null, new TypeMirror[0], true, false, false);
if (method != null) {
val = cx.RuntimeInvoke (method, val, new Value[0]);
return TryCast (ctx, val, type);
}
}
return TryForceCast (ctx, (Value) val, fromType, toType);
}
var vtype = valueType as Type;
if (vtype != null) {
if (toType != null) {
if (toType.IsEnum) {
var casted = TryCast (ctx, val, toType.EnumUnderlyingType) as PrimitiveValue;
return casted != null ? cx.Session.VirtualMachine.CreateEnumMirror (toType, casted) : null;
}
type = Type.GetType (toType.FullName, false);
}
var tt = type as Type;
if (tt != null) {
if (tt.IsAssignableFrom (vtype))
return val;
try {
if (tt.IsPrimitive || tt == typeof (string)) {
var primitive = val as PrimitiveValue;
if (primitive != null)
val = primitive.Value;
if (val == null)
return null;
return CreateValue (ctx, DynamicCast (val, tt));
}
fromType = (TypeMirror) ForceLoadType (ctx, ((Type) valueType).FullName);
if (toType == null)
toType = (TypeMirror) ForceLoadType (ctx, tt.FullName);
return TryForceCast (ctx, (Value) val, fromType, toType);
} catch {
return null;
}
}
}
return null;
}
public override IStringAdaptor CreateStringAdaptor (EvaluationContext ctx, object str)
{
return new StringAdaptor ((StringMirror) str);
}
public override ICollectionAdaptor CreateArrayAdaptor (EvaluationContext ctx, object arr)
{
return new ArrayAdaptor ((ArrayMirror) arr);
}
public override object CreateNullValue (EvaluationContext ctx, object type)
{
var cx = (SoftEvaluationContext) ctx;
return new PrimitiveValue (cx.Session.VirtualMachine, null);
}
public override object CreateTypeObject (EvaluationContext ctx, object type)
{
return ((TypeMirror) type).GetTypeObject ();
}
public override object CreateValue (EvaluationContext ctx, object type, params object[] argValues)
{
ctx.AssertTargetInvokeAllowed ();
var cx = (SoftEvaluationContext) ctx;
var tm = (TypeMirror) type;
var types = new TypeMirror [argValues.Length];
var values = new Value[argValues.Length];
for (int n = 0; n < argValues.Length; n++) {
types[n] = ToTypeMirror (ctx, GetValueType (ctx, argValues[n]));
}
var method = OverloadResolve (cx, tm, ".ctor", null, types, true, false, false);
if (method != null) {
var mparams = method.GetParameters ();
for (int n = 0; n < argValues.Length; n++) {
var param_type = mparams [n].ParameterType;
if (param_type.FullName != types [n].FullName && !param_type.IsAssignableFrom (types [n]) && param_type.IsGenericType) {
/* TODO: Add genericTypeArgs and handle this
bool throwCastException = true;
if (method.VirtualMachine.Version.AtLeast (2, 15)) {
var args = param_type.GetGenericArguments ();
if (args.Length == genericTypes.Length) {
var real_type = soft.Adapter.GetType (soft, param_type.GetGenericTypeDefinition ().FullName, genericTypes);
values [n] = (Value)TryCast (soft, (Value)argValues [n], real_type);
if (!(values [n] == null && argValues [n] != null && !soft.Adapter.IsNull (soft, argValues [n])))
throwCastException = false;
}
}
if (throwCastException) {
string fromType = !IsGeneratedType (types [n]) ? soft.Adapter.GetDisplayTypeName (soft, types [n]) : types [n].FullName;
string toType = soft.Adapter.GetDisplayTypeName (soft, param_type);
throw new EvaluatorException ("Argument {0}: Cannot implicitly convert `{1}' to `{2}'", n, fromType, toType);
}*/
} else if (param_type.FullName != types [n].FullName && !param_type.IsAssignableFrom (types [n]) && CanForceCast (ctx, types [n], param_type)) {
values [n] = (Value)TryCast (ctx, argValues [n], param_type);
} else {
values [n] = (Value)argValues [n];
}
}
lock(method.VirtualMachine) {
return tm.NewInstance (cx.Thread, method, values);
}
}
if (argValues.Length == 0 && tm.VirtualMachine.Version.AtLeast (2, 31))
return tm.NewInstance ();
string typeName = ctx.Adapter.GetDisplayTypeName (ctx, type);
throw new EvaluatorException ("Constructor not found for type `{0}'.", typeName);
}
public override object CreateValue (EvaluationContext ctx, object value)
{
var cx = (SoftEvaluationContext) ctx;
var str = value as string;
if (str != null)
return cx.Domain.CreateString (str);
if (value is decimal) {
var bits = decimal.GetBits ((decimal)value);
return CreateValue (ctx, ToTypeMirror (ctx, typeof (decimal)), CreateValue (ctx, bits [0]), CreateValue (ctx, bits [1]), CreateValue (ctx, bits [2]), CreateValue (ctx, (bits [3] & unchecked((int)0x80000000)) != 0), CreateValue (ctx, (byte)(bits [3] >> 16)));
}
return cx.Session.VirtualMachine.CreateValue (value);
}
public override object GetBaseValue (EvaluationContext ctx, object val)
{
return val;
}
public override bool NullableHasValue (EvaluationContext ctx, object type, object obj)
{
var hasValue = GetMember (ctx, type, obj, "has_value");
return (bool) hasValue.ObjectValue;
}
public override ValueReference NullableGetValue (EvaluationContext ctx, object type, object obj)
{
return GetMember (ctx, type, obj, "value");
}
public override object GetEnclosingType (EvaluationContext ctx)
{
return ((SoftEvaluationContext) ctx).Frame.Method.DeclaringType;
}
public override string[] GetImportedNamespaces (EvaluationContext ctx)
{
var namespaces = new HashSet<string> ();
var cx = (SoftEvaluationContext) ctx;
foreach (TypeMirror type in cx.Session.GetAllTypes ())
namespaces.Add (type.Namespace);
var nss = new string [namespaces.Count];
namespaces.CopyTo (nss);
return nss;
}
public override ValueReference GetIndexerReference (EvaluationContext ctx, object target, object type, object [] indices)
{
var values = new Value [indices.Length];
var types = new TypeMirror [indices.Length];
for (int n = 0; n < indices.Length; n++) {
types[n] = ToTypeMirror (ctx, GetValueType (ctx, indices[n]));
values[n] = (Value) indices[n];
}
var candidates = new List<MethodMirror> ();
var props = new List<PropertyInfoMirror> ();
var mirType = type as TypeMirror;
while (mirType != null) {
foreach (PropertyInfoMirror prop in mirType.GetProperties ()) {
MethodMirror met = prop.GetGetMethod (true);
if (met != null &&
!met.IsStatic &&
met.GetParameters ().Length > 0 &&
!(met.IsPrivate && met.IsVirtual)) {//Don't use explicit interface implementation
candidates.Add (met);
props.Add (prop);
}
}
mirType = mirType.BaseType;
}
var idx = OverloadResolve ((SoftEvaluationContext) ctx, mirType, null, null, null, types, candidates, true);
int i = candidates.IndexOf (idx);
var getter = props[i].GetGetMethod (true);
return getter != null ? new PropertyValueReference (ctx, props[i], target, null, getter, values) : null;
}
public override ValueReference GetIndexerReference (EvaluationContext ctx, object target, object[] indices)
{
object valueType = GetValueType (ctx, target);
var targetType = valueType as TypeMirror;
if (targetType == null) {
var tt = valueType as Type;
if (tt == null)
return null;
targetType = (TypeMirror) ForceLoadType (ctx, tt.FullName);
}
return GetIndexerReference (ctx, target, targetType, indices);
}
static bool InGeneratedClosureOrIteratorType (EvaluationContext ctx)
{
var cx = (SoftEvaluationContext) ctx;
if (cx.Frame.Method.IsStatic)
return false;
var tm = cx.Frame.Method.DeclaringType;
return IsGeneratedType (tm);
}
internal static bool IsGeneratedType (TypeMirror tm)
{
//
// This should cover all C# generated special containers
// - anonymous methods
// - lambdas
// - iterators
// - async methods
//
// which allow stepping into
//
// Note: mcs uses the form <${NAME}>c__${KIND}${NUMBER} where the leading '<' seems to have been dropped in 3.4.x
// csc uses the form <${NAME}>d__${NUMBER}
// roslyn uses the form <${NAME}>d
return tm.Name.IndexOf (">c__", StringComparison.Ordinal) > 0 || tm.Name.IndexOf (">d", StringComparison.Ordinal) > 0;
}
internal static string GetNameFromGeneratedType (TypeMirror tm)
{
return tm.Name.Substring (1, tm.Name.IndexOf ('>') - 1);
}
static bool IsHoistedThisReference (FieldInfoMirror field)
{
// mcs is "<>f__this" or "$this" (if in an async compiler generated type)
// csc is "<>4__this"
return field.Name == "$this" ||
(field.Name.StartsWith ("<>", StringComparison.Ordinal) &&
field.Name.EndsWith ("__this", StringComparison.Ordinal));
}
static bool IsClosureReferenceField (FieldInfoMirror field)
{
// mcs is "$locvar"
// old mcs is "<>f__ref"
// csc is "CS$<>"
// roslyn is "<>8__"
return field.Name.StartsWith ("CS$<>", StringComparison.Ordinal) ||
field.Name.StartsWith ("<>f__ref", StringComparison.Ordinal) ||
field.Name.StartsWith ("$locvar", StringComparison.Ordinal) ||
field.Name.StartsWith ("<>8__", StringComparison.Ordinal);
}
static bool IsClosureReferenceLocal (LocalVariable local)
{
if (local.Name == null)
return false;
// mcs is "$locvar" or starts with '<'
// csc is "CS$<>"
return local.Name.Length == 0 || local.Name[0] == '<' || local.Name.StartsWith ("$locvar", StringComparison.Ordinal) ||
local.Name.StartsWith ("CS$<>", StringComparison.Ordinal);
}
static bool IsGeneratedTemporaryLocal (LocalVariable local)
{
// csc uses CS$ prefix for temporary variables and <>t__ prefix for async task-related state variables
return local.Name != null && (local.Name.StartsWith ("CS$", StringComparison.Ordinal) || local.Name.StartsWith ("<>t__", StringComparison.Ordinal));
}
static string GetHoistedIteratorLocalName (FieldInfoMirror field, SoftEvaluationContext cx)
{
//mcs captured args, of form <$>name
if (field.Name.StartsWith ("<$>", StringComparison.Ordinal)) {
return field.Name.Substring (3);
}
// csc, mcs locals of form <name>__#, where # represents index of scope
if (field.Name [0] == '<') {
var i = field.Name.IndexOf (">__", StringComparison.Ordinal);
if (i != -1 && field.VirtualMachine.Version.AtLeast (2, 43)) {
int scopeIndex;
if (int.TryParse (field.Name.Substring (i + 3), out scopeIndex) && scopeIndex > 0) {//0 means whole method scope
scopeIndex--;//Scope index is 1 based(not zero)
var scopes = cx.Frame.Method.GetScopes ();
if (scopeIndex < scopes.Length) {
var scope = scopes [scopeIndex];
if (scope.LiveRangeStart > cx.Frame.Location.ILOffset || scope.LiveRangeEnd < cx.Frame.Location.ILOffset)
return null;
}
}
}
i = field.Name.IndexOf ('>');
if (i > 1) {
return field.Name.Substring (1, i - 1);
}
}
return null;
}
IEnumerable<ValueReference> GetHoistedLocalVariables (SoftEvaluationContext cx, ValueReference vthis, HashSet<FieldInfoMirror> alreadyVisited = null)
{
if (vthis == null)
return new ValueReference [0];
object val = vthis.Value;
if (IsNull (cx, val))
return new ValueReference [0];
var tm = (TypeMirror) vthis.Type;
var isIterator = IsGeneratedType (tm);
var list = new List<ValueReference> ();
var type = (TypeMirror) vthis.Type;
foreach (var field in type.GetFields ()) {
if (IsHoistedThisReference (field))
continue;
if (IsClosureReferenceField (field)) {
alreadyVisited = alreadyVisited ?? new HashSet<FieldInfoMirror> ();
if (alreadyVisited.Contains (field))
continue;
alreadyVisited.Add (field);
list.AddRange (GetHoistedLocalVariables (cx, new FieldValueReference (cx, field, val, type), alreadyVisited));
continue;
}
if (field.Name[0] == '<') {
if (isIterator) {
var name = GetHoistedIteratorLocalName (field, cx);
if (!string.IsNullOrEmpty (name))
list.Add (new FieldValueReference (cx, field, val, type, name, ObjectValueFlags.Variable) {
ParentSource = vthis
});
}
} else if (!field.Name.Contains ("$")) {
list.Add (new FieldValueReference (cx, field, val, type, field.Name, ObjectValueFlags.Variable) {
ParentSource = vthis
});
}
}
return list;
}
ValueReference GetHoistedThisReference (SoftEvaluationContext cx)
{
try {
var val = cx.Frame.GetThis ();
var type = (TypeMirror) GetValueType (cx, val);
return GetHoistedThisReference (cx, type, val);
} catch (AbsentInformationException) {
}
return null;
}
ValueReference GetHoistedThisReference (SoftEvaluationContext cx, TypeMirror type, object val, HashSet<FieldInfoMirror> alreadyVisited = null)
{
foreach (var field in type.GetFields ()) {
if (IsHoistedThisReference (field))
return new FieldValueReference (cx, field, val, type, "this", ObjectValueFlags.Literal);
if (IsClosureReferenceField (field)) {
alreadyVisited = alreadyVisited ?? new HashSet<FieldInfoMirror> ();
if (alreadyVisited.Contains (field))
continue;
alreadyVisited.Add (field);
var fieldRef = new FieldValueReference (cx, field, val, type);
var thisRef = GetHoistedThisReference (cx, field.FieldType, fieldRef.Value, alreadyVisited);
if (thisRef != null)
return thisRef;
}
}
return null;
}
// if the local does not have a name, constructs one from the index
static string GetLocalName (SoftEvaluationContext cx, LocalVariable local)
{
if (!string.IsNullOrEmpty (local.Name) || cx.SourceCodeAvailable)
return local.Name;
return "loc" + local.Index;
}
protected override ValueReference OnGetLocalVariable (EvaluationContext ctx, string name)
{
var cx = (SoftEvaluationContext) ctx;
if (InGeneratedClosureOrIteratorType (cx))
return FindByName (OnGetLocalVariables (cx), v => v.Name, name, ctx.CaseSensitive);
try {
LocalVariable local = null;
if (!cx.SourceCodeAvailable) {
if (name.StartsWith ("loc", StringComparison.Ordinal)) {
int idx;
if (int.TryParse (name.Substring (3), out idx))
local = cx.Frame.Method.GetLocals ().FirstOrDefault (loc => loc.Index == idx);
}
} else {
local = ctx.CaseSensitive
? cx.Frame.GetVisibleVariableByName (name)
: FindByName (cx.Frame.GetVisibleVariables(), v => v.Name, name, false);
}
if (local != null)
return new VariableValueReference (ctx, GetLocalName (cx, local), local);
return FindByName (OnGetLocalVariables (ctx), v => v.Name, name, ctx.CaseSensitive);
} catch (AbsentInformationException) {
return null;
}
}
protected override IEnumerable<ValueReference> OnGetLocalVariables (EvaluationContext ctx)
{
var cx = (SoftEvaluationContext) ctx;
if (InGeneratedClosureOrIteratorType (cx)) {
ValueReference vthis = GetThisReference (cx);
return GetHoistedLocalVariables (cx, vthis).Union (GetLocalVariables (cx));
}
return GetLocalVariables (cx);
}
IEnumerable<ValueReference> GetLocalVariables (SoftEvaluationContext cx)
{
LocalVariable[] locals;
try {
locals = cx.Frame.GetVisibleVariables ().Where (x => !x.IsArg && ((IsClosureReferenceLocal (x) && IsGeneratedType (x.Type)) || !IsGeneratedTemporaryLocal (x))).ToArray ();
} catch (AbsentInformationException) {
yield break;
}
if (locals.Length == 0)
yield break;
var batch = new LocalVariableBatch (cx.Frame, locals);
for (int i = 0; i < locals.Length; i++) {
if (IsClosureReferenceLocal (locals[i]) && IsGeneratedType (locals[i].Type)) {
foreach (var gv in GetHoistedLocalVariables (cx, new VariableValueReference (cx, locals[i].Name, locals[i], batch))) {
yield return gv;
}
} else if (!IsGeneratedTemporaryLocal (locals[i])) {
yield return new VariableValueReference (cx, GetLocalName (cx, locals[i]), locals[i], batch);
}
}
}
public override bool HasMember (EvaluationContext ctx, object type, string memberName, BindingFlags bindingFlags)
{
var tm = (TypeMirror) type;
while (tm != null) {
var field = FindByName (tm.GetFields (), f => f.Name, memberName, ctx.CaseSensitive);
if (field != null)
return true;
var prop = FindByName (tm.GetProperties (), p => p.Name, memberName, ctx.CaseSensitive);
if (prop != null) {
var getter = prop.GetGetMethod (bindingFlags.HasFlag (BindingFlags.NonPublic));
if (getter != null)
return true;
}
if (bindingFlags.HasFlag (BindingFlags.DeclaredOnly))
break;
tm = tm.BaseType;
}
return false;
}
static bool IsAnonymousType (TypeMirror type)
{
return type.Name.StartsWith ("<>__AnonType", StringComparison.Ordinal);
}
protected override ValueReference GetMember (EvaluationContext ctx, object t, object co, string name)
{
var type = t as TypeMirror;
while (type != null) {
var field = FindByName (type.GetFields (), f => f.Name, name, ctx.CaseSensitive);
if (field != null && (field.IsStatic || co != null))
return new FieldValueReference (ctx, field, co, type);
var prop = FindByName (type.GetProperties (), p => p.Name, name, ctx.CaseSensitive);
if (prop != null && (IsStatic (prop) || co != null)) {
// Optimization: if the property has a CompilerGenerated backing field, use that instead.
// This way we avoid overhead of invoking methods on the debugee when the value is requested.
string cgFieldName = string.Format ("<{0}>{1}", prop.Name, IsAnonymousType (type) ? "" : "k__BackingField");
if ((field = FindByName (type.GetFields (), f => f.Name, cgFieldName, true)) != null && IsCompilerGenerated (field))
return new FieldValueReference (ctx, field, co, type, prop.Name, ObjectValueFlags.Property);
// Backing field not available, so do things the old fashioned way.
var getter = prop.GetGetMethod (true);
return getter != null ? new PropertyValueReference (ctx, prop, co, type, getter, null) : null;
}
type = type.BaseType;
}
return null;
}
static bool IsCompilerGenerated (FieldInfoMirror field)
{
var attrs = field.GetCustomAttributes (true);
var generated = GetAttribute<CompilerGeneratedAttribute> (attrs);
return generated != null;
}
static bool IsStatic (PropertyInfoMirror prop)
{
var met = prop.GetGetMethod (true) ?? prop.GetSetMethod (true);
return met.IsStatic;
}
static T FindByName<T> (IEnumerable<T> items, Func<T,string> getName, string name, bool caseSensitive)
{
T best = default(T);
foreach (T item in items) {
string itemName = getName (item);
if (itemName == name)
return item;
if (!caseSensitive && itemName.Equals (name, StringComparison.CurrentCultureIgnoreCase))
best = item;
}
return best;
}
protected override IEnumerable<ValueReference> GetMembers (EvaluationContext ctx, object t, object co, BindingFlags bindingFlags)
{
var subProps = new Dictionary<string, PropertyInfoMirror> ();
var type = t as TypeMirror;
TypeMirror realType = null;
if (co != null && (bindingFlags & BindingFlags.Instance) != 0)
realType = GetValueType (ctx, co) as TypeMirror;
// First of all, get a list of properties overriden in sub-types
while (realType != null && realType != type) {
foreach (var prop in realType.GetProperties (bindingFlags | BindingFlags.DeclaredOnly)) {
var met = prop.GetGetMethod (true);
if (met == null || met.GetParameters ().Length != 0 || met.IsAbstract || !met.IsVirtual || met.IsStatic)
continue;
if (met.IsPublic && ((bindingFlags & BindingFlags.Public) == 0))
continue;
if (!met.IsPublic && ((bindingFlags & BindingFlags.NonPublic) == 0))
continue;
subProps [prop.Name] = prop;
}
realType = realType.BaseType;
}
bool hasExplicitInterface = false;
while (type != null) {
var fieldsBatch = new FieldReferenceBatch (co);
foreach (var field in type.GetFields ()) {
if (field.IsStatic && ((bindingFlags & BindingFlags.Static) == 0))
continue;
if (!field.IsStatic && ((bindingFlags & BindingFlags.Instance) == 0))