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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
|
//
// 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 Mono.Debugger.Soft;
using Mono.Debugging.Evaluation;
using Mono.Debugging.Client;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
using ST = System.Threading;
using Mono.Debugging.Backend;
namespace Mono.Debugging.Soft
{
public class SoftDebuggerAdaptor : ObjectValueAdaptor
{
static 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 override string CallToString (EvaluationContext ctx, object obj)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
if (obj == null)
return null;
if (obj is StringMirror)
return ((StringMirror)obj).Value;
if (obj is EnumMirror)
return ((EnumMirror) obj).StringValue;
if (obj is PrimitiveValue)
return ((PrimitiveValue)obj).Value.ToString ();
if (obj is PointerValue)
return string.Format ("0x{0:x}", ((PointerValue)obj).Address);
if ((obj is StructMirror) && ((StructMirror)obj).Type.IsPrimitive) {
// Boxed primitive
StructMirror sm = (StructMirror) obj;
if (sm.Fields.Length > 0 && (sm.Fields[0] is PrimitiveValue))
return ((PrimitiveValue)sm.Fields[0]).Value.ToString ();
} else if ((obj is ObjectMirror) && cx.Options.AllowTargetInvoke) {
ObjectMirror ob = (ObjectMirror) obj;
MethodMirror method = OverloadResolve (cx, ob.Type, "ToString", null, new TypeMirror[0], true, false, false);
if (method != null && method.DeclaringType.FullName != "System.Object") {
StringMirror res = cx.RuntimeInvoke (method, obj, new Value[0]) as StringMirror;
return res != null ? res.Value : null;
}
} else if ((obj is StructMirror) && cx.Options.AllowTargetInvoke) {
StructMirror ob = (StructMirror) obj;
MethodMirror method = OverloadResolve (cx, ob.Type, "ToString", null, new TypeMirror[0], true, false, false);
if (method != null && method.DeclaringType.FullName != "System.ValueType") {
StringMirror res = cx.RuntimeInvoke (method, obj, new Value[0]) as StringMirror;
return res != null ? res.Value : null;
}
}
return GetDisplayTypeName (GetValueTypeName (ctx, obj));
}
public override object TryConvert (EvaluationContext ctx, object obj, object targetType)
{
object res = TryCast (ctx, obj, targetType);
if (res != null || obj == null)
return res;
object otype = GetValueType (ctx, obj);
if (otype is Type) {
if (targetType is TypeMirror)
targetType = Type.GetType (((TypeMirror)targetType).FullName, false);
Type tt = targetType as Type;
if (tt != null) {
try {
if (obj is PrimitiveValue)
obj = ((PrimitiveValue)obj).Value;
res = System.Convert.ChangeType (obj, tt);
return CreateValue (ctx, res);
} catch {
}
}
}
return null;
}
static TypeCastDelegate GenerateTypeCastDelegate (string methodName, Type fromType, Type toType)
{
var argTypes = new Type[] {
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 (System.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 Type[] {
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);
return (TypeCastDelegate) method.CreateDelegate (typeof (TypeCastDelegate));
}
static object DynamicCast (object value, Type target)
{
string methodName = string.Format ("CastFrom{0}To{1}", value.GetType ().Name, target.Name);
TypeCastDelegate method = GenerateTypeCastDelegate (methodName, value.GetType (), target);
return method.Invoke (value);
}
object TryForceCast (EvaluationContext ctx, Value value, TypeMirror fromType, TypeMirror toType)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
MethodMirror method;
method = OverloadResolve (cx, toType, "op_Explicit", null, new TypeMirror[] { fromType }, false, true, false);
if (method != null)
return cx.RuntimeInvoke (method, toType, new Value[] { value });
method = OverloadResolve (cx, toType, "op_Implicit", null, new TypeMirror[] { fromType }, false, true, false);
if (method != null)
return cx.RuntimeInvoke (method, toType, new Value[] { value });
// Finally, try a ctor...
try {
return CreateValue (ctx, toType, value);
} catch {
return null;
}
}
public override object TryCast (EvaluationContext ctx, object obj, object targetType)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
TypeMirror toType = targetType as TypeMirror;
TypeMirror fromType;
if (obj == null)
return null;
object valueType = GetValueType (ctx, obj);
if (valueType is TypeMirror) {
fromType = (TypeMirror) valueType;
if (toType != null && toType.IsAssignableFrom (fromType))
return obj;
// Try casting the primitive type of the enum
EnumMirror em = obj as EnumMirror;
if (em != null)
return TryCast (ctx, CreateValue (ctx, em.Value), targetType);
if (toType == null)
return null;
MethodMirror method;
if (toType.CSharpName == "string") {
method = OverloadResolve (cx, fromType, "ToString", null, new TypeMirror[0], true, false, false);
if (method != null)
return cx.RuntimeInvoke (method, obj, new Value[0]);
}
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) {
obj = cx.RuntimeInvoke (method, obj, new Value[0]);
return TryCast (ctx, obj, targetType);
}
}
return TryForceCast (ctx, (Value) obj, fromType, toType);
} else if (valueType is Type) {
if (toType != null) {
if (toType.IsEnum) {
PrimitiveValue casted = TryCast (ctx, obj, toType.EnumUnderlyingType) as PrimitiveValue;
if (casted == null)
return null;
return cx.Session.VirtualMachine.CreateEnumMirror (toType, casted);
}
targetType = Type.GetType (toType.FullName, false);
}
Type tt = targetType as Type;
if (tt != null) {
if (tt.IsAssignableFrom ((Type) valueType))
return obj;
try {
if (tt.IsPrimitive || tt == typeof (string)) {
if (obj is PrimitiveValue)
obj = ((PrimitiveValue) obj).Value;
if (obj == null)
return null;
object res;
try {
res = System.Convert.ChangeType (obj, tt);
} catch {
res = DynamicCast (obj, tt);
}
return CreateValue (ctx, res);
} else {
fromType = (TypeMirror) ForceLoadType (ctx, ((Type) valueType).FullName);
if (toType == null)
toType = (TypeMirror) ForceLoadType (ctx, tt.FullName);
return TryForceCast (ctx, (Value) obj, fromType, toType);
}
} catch {
}
}
}
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)
{
return null;
}
public override object CreateTypeObject (EvaluationContext ctx, object type)
{
TypeMirror t = (TypeMirror) type;
return t.GetTypeObject ();
}
public override object CreateValue (EvaluationContext ctx, object type, params object[] args)
{
ctx.AssertTargetInvokeAllowed ();
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
TypeMirror t = (TypeMirror) type;
TypeMirror[] types = new TypeMirror [args.Length];
Value[] values = new Value[args.Length];
for (int n = 0; n < args.Length; n++) {
types[n] = ToTypeMirror (ctx, GetValueType (ctx, args[n]));
values[n] = (Value) args[n];
}
MethodMirror ctor = OverloadResolve (cx, t, ".ctor", null, types, true, true, true);
if (ctor == null)
return null;
return t.NewInstance (cx.Thread, ctor, values);
}
public override object CreateValue (EvaluationContext ctx, object value)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
if (value is string)
return cx.Thread.Domain.CreateString ((string)value);
else
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)
{
ValueReference 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)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
return cx.Frame.Method.DeclaringType;
}
public override string[] GetImportedNamespaces (EvaluationContext ctx)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
HashSet<string> namespaces = new HashSet<string> ();
foreach (TypeMirror type in cx.Session.GetAllTypes ())
namespaces.Add (type.Namespace);
string[] nss = new string [namespaces.Count];
namespaces.CopyTo (nss);
return nss;
}
public override ValueReference GetIndexerReference (EvaluationContext ctx, object target, object[] indices)
{
object valueType = GetValueType (ctx, target);
TypeMirror targetType = null;
if (valueType is Type)
targetType = (TypeMirror) ForceLoadType (ctx, ((Type) valueType).FullName);
else if (valueType is TypeMirror)
targetType = (TypeMirror) valueType;
else
return null;
Value[] values = new Value [indices.Length];
TypeMirror[] 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];
}
List<MethodMirror> candidates = new List<MethodMirror> ();
List<PropertyInfoMirror> props = new List<PropertyInfoMirror> ();
TypeMirror type = targetType;
while (type != null) {
foreach (PropertyInfoMirror prop in type.GetProperties ()) {
MethodMirror met = prop.GetGetMethod (true);
if (met != null && !met.IsStatic && met.GetParameters ().Length > 0) {
candidates.Add (met);
props.Add (prop);
}
}
type = type.BaseType;
}
MethodMirror idx = OverloadResolve ((SoftEvaluationContext) ctx, targetType, null, null, types, candidates, true);
int i = candidates.IndexOf (idx);
MethodMirror getter = props[i].GetGetMethod (true);
if (getter == null)
return null;
return new PropertyValueReference (ctx, props[i], target, null, getter, values);
}
static bool InGeneratedClosureOrIteratorType (EvaluationContext ctx)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
if (cx.Frame.Method.IsStatic)
return false;
TypeMirror 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
//
return tm.Name[0] == '<' &&
// mcs is of the form <${NAME}>.c__{KIND}${NUMBER}
(tm.Name.IndexOf (">c__", StringComparison.Ordinal) > 0 ||
// csc is of form <${NAME}>d__${NUMBER}
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 "<>f__ref"
// csc is "CS$<>"
return field.Name.StartsWith ("CS$<>", StringComparison.Ordinal) ||
field.Name.StartsWith ("<>f__ref", 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)
{
return local.Name != null && local.Name.StartsWith ("CS$", StringComparison.Ordinal);
}
static string GetHoistedIteratorLocalName (FieldInfoMirror field)
{
//mcs captured args, of form <$>name
if (field.Name.StartsWith ("<$>", StringComparison.Ordinal)) {
return field.Name.Substring (3);
}
// csc, mcs locals of form <name>__0
if (field.Name.StartsWith ("<", StringComparison.Ordinal)) {
int i = field.Name.IndexOf ('>');
if (i > 1) {
return field.Name.Substring (1, i - 1);
}
}
return null;
}
IEnumerable<ValueReference> GetHoistedLocalVariables (SoftEvaluationContext cx, ValueReference vthis)
{
if (vthis == null)
return new ValueReference [0];
object val = vthis.Value;
if (IsNull (cx, val))
return new ValueReference [0];
TypeMirror tm = (TypeMirror) vthis.Type;
bool isIterator = IsGeneratedType (tm);
var list = new List<ValueReference> ();
TypeMirror type = (TypeMirror) vthis.Type;
foreach (FieldInfoMirror field in type.GetFields ()) {
if (IsHoistedThisReference (field))
continue;
if (IsClosureReferenceField (field)) {
list.AddRange (GetHoistedLocalVariables (cx, new FieldValueReference (cx, field, val, type)));
continue;
}
if (field.Name.StartsWith ("<", StringComparison.Ordinal)) {
if (isIterator) {
var name = GetHoistedIteratorLocalName (field);
if (!string.IsNullOrEmpty (name)) {
list.Add (new FieldValueReference (cx, field, val, type, name, ObjectValueFlags.Variable));
}
}
} else if (!field.Name.Contains ("$")) {
list.Add (new FieldValueReference (cx, field, val, type, field.Name, ObjectValueFlags.Variable));
}
}
return list;
}
ValueReference GetHoistedThisReference (SoftEvaluationContext cx)
{
try {
Value val = cx.Frame.GetThis ();
TypeMirror type = (TypeMirror) GetValueType (cx, val);
return GetHoistedThisReference (cx, type, val);
} catch (AbsentInformationException) {
}
return null;
}
ValueReference GetHoistedThisReference (SoftEvaluationContext cx, TypeMirror type, object val)
{
foreach (FieldInfoMirror field in type.GetFields ()) {
if (IsHoistedThisReference (field))
return new FieldValueReference (cx, field, val, type, "this", ObjectValueFlags.Literal);
if (IsClosureReferenceField (field)) {
var fieldRef = new FieldValueReference (cx, field, val, type);
var thisRef = GetHoistedThisReference (cx, field.FieldType, fieldRef.Value);
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)
{
SoftEvaluationContext 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)
{
SoftEvaluationContext 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)
{
IList<LocalVariable> locals;
try {
locals = cx.Frame.GetVisibleVariables ();
} catch (AbsentInformationException) {
yield break;
}
foreach (LocalVariable local in locals) {
if (local.IsArg)
continue;
if (IsClosureReferenceLocal (local) && IsGeneratedType (local.Type)) {
foreach (var gv in GetHoistedLocalVariables (cx, new VariableValueReference (cx, local.Name, local))) {
yield return gv;
}
} else if (!IsGeneratedTemporaryLocal (local)) {
yield return new VariableValueReference (cx, GetLocalName (cx, local), local);
}
}
}
public override bool HasMember (EvaluationContext ctx, object type, string memberName, BindingFlags bindingFlags)
{
TypeMirror tm = (TypeMirror) type;
while (tm != null) {
FieldInfoMirror field = FindByName (tm.GetFields (), f => f.Name, memberName, ctx.CaseSensitive);
if (field != null)
return true;
PropertyInfoMirror prop = FindByName (tm.GetProperties (), p => p.Name, memberName, ctx.CaseSensitive);
if (prop != null) {
MethodMirror 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)
{
TypeMirror type = t as TypeMirror;
while (type != null) {
FieldInfoMirror field = FindByName (type.GetFields (), f => f.Name, name, ctx.CaseSensitive);
if (field != null && (field.IsStatic || co != null))
return new FieldValueReference (ctx, field, co, type);
PropertyInfoMirror 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.
MethodMirror getter = prop.GetGetMethod (true);
if (getter == null)
return null;
return new PropertyValueReference (ctx, prop, co, type, getter, null);
}
type = type.BaseType;
}
return null;
}
static bool IsCompilerGenerated (FieldInfoMirror field)
{
CustomAttributeDataMirror[] attrs = field.GetCustomAttributes (true);
var cga = GetAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute> (attrs);
return cga != null;
}
static bool IsStatic (PropertyInfoMirror prop)
{
MethodMirror met = prop.GetGetMethod (true) ?? prop.GetSetMethod (true);
return met.IsStatic;
}
static T FindByName<T> (IEnumerable<T> elems, Func<T,string> getName, string name, bool caseSensitive)
{
T best = default(T);
foreach (T t in elems) {
string n = getName (t);
if (n == name)
return t;
if (!caseSensitive && n.Equals (name, StringComparison.CurrentCultureIgnoreCase))
best = t;
}
return best;
}
protected override IEnumerable<ValueReference> GetMembers (EvaluationContext ctx, object t, object co, BindingFlags bindingFlags)
{
Dictionary<string, PropertyInfoMirror> subProps = new Dictionary<string, PropertyInfoMirror> ();
TypeMirror 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 (PropertyInfoMirror prop in realType.GetProperties (bindingFlags | BindingFlags.DeclaredOnly)) {
MethodMirror 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;
}
while (type != null) {
foreach (FieldInfoMirror field in type.GetFields ()) {
if (field.IsStatic && ((bindingFlags & BindingFlags.Static) == 0))
continue;
if (!field.IsStatic && ((bindingFlags & BindingFlags.Instance) == 0))
continue;
if (field.IsPublic && ((bindingFlags & BindingFlags.Public) == 0))
continue;
if (!field.IsPublic && ((bindingFlags & BindingFlags.NonPublic) == 0))
continue;
yield return new FieldValueReference (ctx, field, co, type);
}
foreach (PropertyInfoMirror prop in type.GetProperties (bindingFlags)) {
MethodMirror getter = prop.GetGetMethod (true);
if (getter == null || getter.GetParameters ().Length != 0 || getter.IsAbstract)
continue;
if (getter.IsStatic && ((bindingFlags & BindingFlags.Static) == 0))
continue;
if (!getter.IsStatic && ((bindingFlags & BindingFlags.Instance) == 0))
continue;
if (getter.IsPublic && ((bindingFlags & BindingFlags.Public) == 0))
continue;
if (!getter.IsPublic && ((bindingFlags & BindingFlags.NonPublic) == 0))
continue;
// If a property is overriden, return the override instead of the base property
PropertyInfoMirror overridden;
if (getter.IsVirtual && subProps.TryGetValue (prop.Name, out overridden)) {
getter = overridden.GetGetMethod (true);
if (getter == null)
continue;
yield return new PropertyValueReference (ctx, overridden, co, overridden.DeclaringType, getter, null);
} else {
yield return new PropertyValueReference (ctx, prop, co, type, getter, null);
}
}
if ((bindingFlags & BindingFlags.DeclaredOnly) != 0)
break;
type = type.BaseType;
}
}
public override void GetNamespaceContents (EvaluationContext ctx, string namspace, out string[] childNamespaces, out string[] childTypes)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
HashSet<string> types = new HashSet<string> ();
HashSet<string> namespaces = new HashSet<string> ();
string namspacePrefix = namspace.Length > 0 ? namspace + "." : "";
foreach (TypeMirror type in cx.Session.GetAllTypes ()) {
if (type.Namespace == namspace || type.Namespace.StartsWith (namspacePrefix, StringComparison.InvariantCulture)) {
namespaces.Add (type.Namespace);
types.Add (type.FullName);
}
}
childNamespaces = new string [namespaces.Count];
namespaces.CopyTo (childNamespaces);
childTypes = new string [types.Count];
types.CopyTo (childTypes);
}
protected override IEnumerable<ValueReference> OnGetParameters (EvaluationContext ctx)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
LocalVariable[] locals;
try {
locals = cx.Frame.Method.GetLocals ();
} catch (AbsentInformationException) {
yield break;
}
foreach (LocalVariable var in locals) {
if (var.IsArg) {
string name = !string.IsNullOrEmpty (var.Name) ? var.Name : "arg" + var.Index;
yield return new VariableValueReference (ctx, name, var);
}
}
}
protected override ValueReference OnGetThisReference (EvaluationContext ctx)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
if (InGeneratedClosureOrIteratorType (cx))
return GetHoistedThisReference (cx);
return GetThisReference (cx);
}
ValueReference GetThisReference (SoftEvaluationContext cx)
{
try {
if (cx.Frame.Method.IsStatic)
return null;
Value val = cx.Frame.GetThis ();
return LiteralValueReference.CreateTargetObjectLiteral (cx, "this", val);
} catch (AbsentInformationException) {
return null;
}
}
public override ValueReference GetCurrentException (EvaluationContext ctx)
{
try {
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
ObjectMirror exc = cx.Session.GetExceptionObject (cx.Thread);
if (exc != null)
return LiteralValueReference.CreateTargetObjectLiteral (ctx, ctx.Options.CurrentExceptionTag, exc);
return null;
} catch (AbsentInformationException) {
return null;
}
}
public override bool IsGenericType (EvaluationContext ctx, object type)
{
return type != null && ((TypeMirror) type).IsGenericType;
}
public override object[] GetTypeArgs (EvaluationContext ctx, object type)
{
TypeMirror tm = (TypeMirror) type;
if (tm.VirtualMachine.Version.AtLeast (2, 15))
return tm.GetGenericArguments ();
// fall back to parsing them from the from the FullName
List<string> names = new List<string> ();
string s = tm.FullName;
int i = s.IndexOf ('`');
if (i != -1) {
i = s.IndexOf ('[', i);
if (i == -1)
return new object [0];
int si = ++i;
int nt = 0;
for (; i < s.Length && (nt > 0 || s[i] != ']'); i++) {
if (s[i] == '[')
nt++;
else if (s[i] == ']')
nt--;
else if (s[i] == ',' && nt == 0) {
names.Add (s.Substring (si, i - si));
si = i + 1;
}
}
names.Add (s.Substring (si, i - si));
object[] types = new object [names.Count];
for (int n=0; n<names.Count; n++) {
string tn = names [n];
if (tn.StartsWith ("[", StringComparison.Ordinal))
tn = tn.Substring (1, tn.Length - 2);
types [n] = GetType (ctx, tn);
if (types [n] == null)
return new object [0];
}
return types;
}
return new object [0];
}
public override object GetType (EvaluationContext ctx, string name, object[] typeArgs)
{
SoftEvaluationContext cx = (SoftEvaluationContext) ctx;
int i = name.IndexOf (',');
if (i != -1) {
// Find first comma outside brackets
int nest = 0;
for (int n=0; n<name.Length; n++) {
char c = name [n];
if (c == '[')
nest++;
else if (c == ']')
nest--;
else if (c == ',' && nest == 0) {
name = name.Substring (0, n).Trim ();
break;
}
}
}
if (typeArgs != null && typeArgs.Length > 0){
string args = "";
foreach (object t in typeArgs) {
if (args.Length > 0)
args += ",";
string tn;
if (t is TypeMirror) {
TypeMirror atm = (TypeMirror) t;
tn = atm.FullName + "," + atm.Assembly.GetName ();
} else {
Type atm = (Type) t;
tn = atm.FullName + "," + atm.Assembly.GetName ();
}
if (tn.IndexOf (',') != -1)
tn = "[" + tn + "]";
args += tn;
}
name += "[" +args + "]";
}
TypeMirror tm = cx.Session.GetType (name);
if (tm != null)
return tm;
foreach (AssemblyMirror asm in cx.Thread.Domain.GetAssemblies ()) {
tm = asm.GetType (name, false, false);
if (tm != null)
return tm;
}
return null;
}
public override object GetParentType (EvaluationContext ctx, object type)
{
TypeMirror tm = type as TypeMirror;
if (tm != null) {
int plus = tm.FullName.LastIndexOf ('+');
return plus != -1 ? GetType (ctx, tm.FullName.Substring (0, plus)) : null;
}
return ((Type) type).DeclaringType;
}
public override IEnumerable<object> GetNestedTypes (EvaluationContext ctx, object type)
{
TypeMirror t = (TypeMirror) type;
foreach (TypeMirror nt in t.GetNestedTypes ())
yield return nt;
}
public override string GetTypeName (EvaluationContext ctx, object type)
{
TypeMirror tm = type as TypeMirror;
if (tm != null) {
if (IsGeneratedType (tm)) {
// Return the name of the container-type.
return tm.FullName.Substring (0, tm.FullName.LastIndexOf ('+'));
}
return tm.FullName;
}
return ((Type)type).FullName;
}
public override object GetValueType (EvaluationContext ctx, object val)
{
if (val == null)
return typeof (Object);
if (val is ArrayMirror)
return ((ArrayMirror)val).Type;
if (val is ObjectMirror)
return ((ObjectMirror)val).Type;
if (val is EnumMirror)
return ((EnumMirror)val).Type;
if (val is StructMirror)
return ((StructMirror)val).Type;
if (val is PointerValue)
return ((PointerValue) val).Type;
if (val is PrimitiveValue) {
PrimitiveValue pv = (PrimitiveValue) val;
if (pv.Value == null)
return typeof(Object);
return pv.Value.GetType ();
}
throw new NotSupportedException ();
}
public override object GetBaseType (EvaluationContext ctx, object type)
{
if (type is TypeMirror)
return ((TypeMirror)type).BaseType;
return null;
}
public override bool HasMethod (EvaluationContext gctx, object targetType, string methodName, object[] genericTypeArgs, object[] argTypes, BindingFlags flags)
{
SoftEvaluationContext ctx = (SoftEvaluationContext) gctx;
TypeMirror[] typeArgs = null;
TypeMirror[] types = null;
if (genericTypeArgs != null) {
typeArgs = new TypeMirror [genericTypeArgs.Length];
for (int n = 0; n < genericTypeArgs.Length; n++) {
if (genericTypeArgs[n] is TypeMirror)
typeArgs[n] = (TypeMirror) genericTypeArgs[n];
else
typeArgs[n] = (TypeMirror) GetType (ctx, ((Type) genericTypeArgs[n]).FullName);
}
}
if (argTypes != null) {
types = new TypeMirror [argTypes.Length];
for (int n = 0; n < argTypes.Length; n++) {
if (argTypes[n] is TypeMirror)
types[n] = (TypeMirror) argTypes[n];
else
types[n] = (TypeMirror) GetType (ctx, ((Type) argTypes[n]).FullName);
}
}
MethodMirror method = OverloadResolve (ctx, (TypeMirror) targetType, methodName, typeArgs, types, (flags & BindingFlags.Instance) != 0, (flags & BindingFlags.Static) != 0, false);
return method != null;
}
public override bool IsExternalType (EvaluationContext ctx, object type)
{
TypeMirror tm = type as TypeMirror;
if (tm != null)
return ((SoftEvaluationContext) ctx).Session.IsExternalCode (tm);
return true;
}
public override bool IsString (EvaluationContext ctx, object val)
{
return val is StringMirror;
}
public override bool IsArray (EvaluationContext ctx, object val)
{
return val is ArrayMirror;
}
public override bool IsValueType (object type)
{
TypeMirror t = type as TypeMirror;
return t != null && t.IsValueType;
}
public override bool IsClass (object type)
{
TypeMirror t = type as TypeMirror;
return t != null && (t.IsClass || t.IsValueType) && !t.IsPrimitive;
}
public override bool IsNull (EvaluationContext ctx, object val)
{
return val == null || ((val is PrimitiveValue) && ((PrimitiveValue)val).Value == null) || ((val is PointerValue) && ((PointerValue)val).Address == 0);
}
public override bool IsPrimitive (EvaluationContext ctx, object val)
{
return val is PrimitiveValue || val is StringMirror || ((val is StructMirror) && ((StructMirror)val).Type.IsPrimitive) || val is PointerValue;
}
public override bool IsPointer (EvaluationContext ctx, object val)
{
return val is PointerValue;
}
public override bool IsEnum (EvaluationContext ctx, object val)
{
return val is EnumMirror;
}
protected override TypeDisplayData OnGetTypeDisplayData (EvaluationContext gctx, object type)
{
SoftEvaluationContext ctx = (SoftEvaluationContext) gctx;
bool isCompilerGenerated = false;
string nameString = null;
string typeString = null;
string valueString = null;
string proxyType = null;
Dictionary<string, DebuggerBrowsableState> memberData = null;
try {
TypeMirror t = (TypeMirror) type;
foreach (CustomAttributeDataMirror attr in t.GetCustomAttributes (true)) {
string attName = attr.Constructor.DeclaringType.FullName;
if (attName == "System.Diagnostics.DebuggerDisplayAttribute") {
DebuggerDisplayAttribute at = BuildAttribute<DebuggerDisplayAttribute> (attr);
nameString = at.Name;
typeString = at.Type;
valueString = at.Value;
}
else if (attName == "System.Diagnostics.DebuggerTypeProxyAttribute") {
DebuggerTypeProxyAttribute at = BuildAttribute<DebuggerTypeProxyAttribute> (attr);
proxyType = at.ProxyTypeName;
if (!string.IsNullOrEmpty (proxyType))
ForceLoadType (ctx, proxyType);
}
else if (attName == "System.Runtime.CompilerServices.CompilerGeneratedAttribute")
isCompilerGenerated = true;
}
foreach (FieldInfoMirror fi in t.GetFields ()) {
CustomAttributeDataMirror[] attrs = fi.GetCustomAttributes (true);
DebuggerBrowsableAttribute att = GetAttribute <DebuggerBrowsableAttribute> (attrs);
if (att == null) {
var cga = GetAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute> (attrs);
if (cga != null)
att = new DebuggerBrowsableAttribute (DebuggerBrowsableState.Never);
}
if (att != null) {
if (memberData == null)
memberData = new Dictionary<string, DebuggerBrowsableState> ();
memberData [fi.Name] = att.State;
}
}
foreach (PropertyInfoMirror pi in t.GetProperties ()) {
DebuggerBrowsableAttribute att = GetAttribute <DebuggerBrowsableAttribute> (pi.GetCustomAttributes (true));
if (att != null) {
if (memberData == null)
memberData = new Dictionary<string, DebuggerBrowsableState> ();
memberData [pi.Name] = att.State;
}
}
} catch (Exception ex) {
ctx.Session.WriteDebuggerOutput (true, ex.ToString ());
}
return new TypeDisplayData (proxyType, valueString, typeString, nameString, isCompilerGenerated, memberData);
}
static T GetAttribute<T> (CustomAttributeDataMirror[] attrs)
{
foreach (CustomAttributeDataMirror attr in attrs) {
if (attr.Constructor.DeclaringType.FullName == typeof(T).FullName)
return BuildAttribute<T> (attr);
}
return default(T);
}
public override bool IsTypeLoaded (EvaluationContext gctx, string typeName)
{
SoftEvaluationContext ctx = (SoftEvaluationContext) gctx;
return ctx.Session.GetType (typeName) != null;
}
public override bool IsTypeLoaded (EvaluationContext ctx, object type)
{
TypeMirror tm = (TypeMirror) type;
if (tm.VirtualMachine.Version.AtLeast (2, 23))
return tm.IsInitialized;
return IsTypeLoaded (ctx, tm.FullName);
}
public override bool ForceLoadType (EvaluationContext gctx, object type)
{
SoftEvaluationContext ctx = (SoftEvaluationContext) gctx;
TypeMirror tm = (TypeMirror) type;
if (!tm.VirtualMachine.Version.AtLeast (2, 23))
return IsTypeLoaded (gctx, tm.FullName);
if (tm.IsInitialized)
return true;
if (!tm.Attributes.HasFlag (TypeAttributes.BeforeFieldInit))
return false;
MethodMirror cctor = OverloadResolve (ctx, tm, ".cctor", null, new TypeMirror[0], false, true, false);
if (cctor == null)
return true;
try {
tm.InvokeMethod (ctx.Thread, cctor, new Value[0], InvokeOptions.DisableBreakpoints | InvokeOptions.SingleThreaded);
} catch {
return false;
} finally {
ctx.Session.StackVersion++;
}
return true;
}
static T BuildAttribute<T> (CustomAttributeDataMirror attr)
{
List<object> args = new List<object> ();
foreach (CustomAttributeTypedArgumentMirror arg in attr.ConstructorArguments) {
object val = arg.Value;
if (val is TypeMirror) {
// The debugger attributes that take a type as parameter of the constructor have
// a corresponding constructor overload that takes a type name. We'll use that
// constructor because we can't load target types in the debugger process.
// So what we do here is convert the Type to a String.
TypeMirror tm = (TypeMirror) val;
val = tm.FullName + ", " + tm.Assembly.ManifestModule.Name;
} else if (val is EnumMirror) {
EnumMirror em = (EnumMirror) val;
val = em.Value;
}
args.Add (val);
}
Type type = typeof(T);
object at = Activator.CreateInstance (type, args.ToArray ());
foreach (CustomAttributeNamedArgumentMirror arg in attr.NamedArguments) {
object val = arg.TypedValue.Value;
string postFix = "";
if (arg.TypedValue.ArgumentType == typeof(Type))
postFix = "TypeName";
if (arg.Field != null)
type.GetField (arg.Field.Name + postFix).SetValue (at, val);
else if (arg.Property != null)
type.GetProperty (arg.Property.Name + postFix).SetValue (at, val, null);
}
return (T) at;
}
TypeMirror ToTypeMirror (EvaluationContext ctx, object type)
{
TypeMirror t = type as TypeMirror;
if (t != null)
return t;
return (TypeMirror) GetType (ctx, ((Type)type).FullName);
}
public override object RuntimeInvoke (EvaluationContext ctx, object targetType, object target, string methodName, object[] argTypes, object[] argValues)
{
return RuntimeInvoke (ctx, targetType, target, methodName, new object [0], argTypes, argValues);
}
public override object RuntimeInvoke (EvaluationContext gctx, object targetType, object target, string methodName, object[] genericTypeArgs, object[] argTypes, object[] argValues)
{
SoftEvaluationContext ctx = (SoftEvaluationContext) gctx;
TypeMirror type = ToTypeMirror (ctx, targetType);
ctx.AssertTargetInvokeAllowed ();
TypeMirror[] genericTypes = new TypeMirror [genericTypeArgs != null ? genericTypeArgs.Length : 0];
for (int n = 0; n < genericTypes.Length; n++)
genericTypes[n] = ToTypeMirror (ctx, genericTypeArgs[n]);
TypeMirror[] types = new TypeMirror [argTypes.Length];
for (int n = 0; n < argTypes.Length; n++)
types[n] = ToTypeMirror (ctx, argTypes[n]);
MethodMirror method = OverloadResolve (ctx, type, methodName, genericTypes, types, target != null, target == null, true);
ParameterInfoMirror[] mparams = method.GetParameters ();
Value[] values = new Value [argValues.Length];
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) {
bool throwCastException = true;
if (method.VirtualMachine.Version.AtLeast (2, 15)) {
var args = param_type.GetGenericArguments ();
if (args.Length == genericTypes.Length) {
var real_type = ctx.Adapter.GetType (ctx, param_type.GetGenericTypeDefinition ().FullName, genericTypes);
values[n] = (Value) TryCast (ctx, (Value) argValues[n], real_type);
if (!(values[n] == null && argValues[n] != null && !ctx.Adapter.IsNull (ctx, argValues[n])))
throwCastException = false;
}
}
if (throwCastException) {
string fromType = !IsGeneratedType (types[n]) ? ctx.Adapter.GetDisplayTypeName (ctx, types[n]) : types[n].FullName;
string toType = ctx.Adapter.GetDisplayTypeName (ctx, param_type);
throw new EvaluatorException ("Argument {0}: Cannot implicitly convert `{1}' to `{2}'", n, fromType, toType);
}
} else {
values[n] = (Value) argValues[n];
}
}
return ctx.RuntimeInvoke (method, target ?? targetType, values);
}
public static MethodMirror OverloadResolve (SoftEvaluationContext ctx, TypeMirror type, string methodName, TypeMirror[] genericTypeArgs, TypeMirror[] argTypes, bool allowInstance, bool allowStatic, bool throwIfNotFound)
{
List<MethodMirror> candidates = new List<MethodMirror> ();
var cache = ctx.Session.OverloadResolveCache;
TypeMirror currentType = type;
while (currentType != null) {
MethodMirror[] methods = null;
if (ctx.CaseSensitive) {
lock (cache) {
cache.TryGetValue (Tuple.Create (currentType, methodName), out methods);
}
}
if (methods == null) {
if (currentType.VirtualMachine.Version.AtLeast (2, 7))
methods = currentType.GetMethodsByNameFlags (methodName, BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Static, !ctx.CaseSensitive);
else
methods = currentType.GetMethods ();
if (ctx.CaseSensitive) {
lock (cache) {
cache [Tuple.Create (currentType, methodName)] = methods;
}
}
}
foreach (MethodMirror method in methods) {
if (method.Name == methodName || (!ctx.CaseSensitive && method.Name.Equals (methodName, StringComparison.CurrentCultureIgnoreCase))) {
MethodMirror actualMethod;
if (genericTypeArgs != null && genericTypeArgs.Length > 0 && method.VirtualMachine.Version.AtLeast (2, 24) && method.IsGenericMethod) {
actualMethod = method.GetGenericMethodDefinition ().MakeGenericMethod (genericTypeArgs);
} else {
actualMethod = method;
}
ParameterInfoMirror[] parms = actualMethod.GetParameters ();
if (argTypes == null || parms.Length == argTypes.Length && ((actualMethod.IsStatic && allowStatic) || (!actualMethod.IsStatic && allowInstance)))
candidates.Add (actualMethod);
}
}
if (argTypes == null && candidates.Count > 0)
break; // when argtypes is null, we are just looking for *any* match (not a specific match)
if (methodName == ".ctor")
break; // Can't create objects using constructor from base classes
// Make sure that we always pull in at least System.Object methods (this is mostly needed for cases where 'type' was an interface)
if (currentType.BaseType == null && currentType.FullName != "System.Object")
currentType = ctx.Session.GetType ("System.Object");
else
currentType = currentType.BaseType;
}
return OverloadResolve (ctx, type, methodName, genericTypeArgs, argTypes, candidates, throwIfNotFound);
}
static bool IsApplicable (SoftEvaluationContext ctx, MethodMirror method, TypeMirror[] genericTypeArgs, TypeMirror[] types, out string error, out int matchCount)
{
ParameterInfoMirror[] mparams = method.GetParameters ();
matchCount = 0;
for (int i = 0; i < types.Length; i++) {
TypeMirror param_type = mparams[i].ParameterType;
if (param_type.FullName == types[i].FullName) {
matchCount++;
continue;
}
if (param_type.IsAssignableFrom (types[i]))
continue;
if (param_type.IsGenericType) {
if (genericTypeArgs != null && method.VirtualMachine.Version.AtLeast (2, 12)) {
// FIXME: how can we make this more definitive?
if (param_type.GetGenericArguments ().Length == genericTypeArgs.Length)
continue;
} else {
// no way to check... assume it'll work?
continue;
}
}
string fromType = !IsGeneratedType (types[i]) ? ctx.Adapter.GetDisplayTypeName (ctx, types[i]) : types[i].FullName;
string toType = ctx.Adapter.GetDisplayTypeName (ctx, param_type);
error = String.Format ("Argument {0}: Cannot implicitly convert `{1}' to `{2}'", i, fromType, toType);
return false;
}
error = null;
return true;
}
static MethodMirror OverloadResolve (SoftEvaluationContext ctx, TypeMirror type, string methodName, TypeMirror[] genericTypeArgs, TypeMirror[] argTypes, List<MethodMirror> candidates, bool throwIfNotFound)
{
if (candidates.Count == 0) {
if (throwIfNotFound) {
string typeName = ctx.Adapter.GetDisplayTypeName (ctx, type);
if (methodName == null)
throw new EvaluatorException ("Indexer not found in type `{0}'.", typeName);
if (genericTypeArgs != null && genericTypeArgs.Length > 0) {
var types = string.Join (", ", genericTypeArgs.Select (t => ctx.Adapter.GetDisplayTypeName (ctx, t)));
throw new EvaluatorException ("Method `{0}<{1}>' not found in type `{2}'.", methodName, types, typeName);
}
throw new EvaluatorException ("Method `{0}' not found in type `{1}'.", methodName, typeName);
}
return null;
}
if (argTypes == null) {
// This is just a probe to see if the type contains *any* methods of the given name
return candidates[0];
}
if (candidates.Count == 1) {
string error;
int matchCount;
if (IsApplicable (ctx, candidates[0], genericTypeArgs, argTypes, out error, out matchCount))
return candidates[0];
if (throwIfNotFound)
throw new EvaluatorException ("Invalid arguments for method `{0}': {1}", methodName, error);
return null;
}
// Ok, now we need to find an exact match.
MethodMirror match = null;
int bestCount = -1;
bool repeatedBestCount = false;
foreach (MethodMirror method in candidates) {
string error;
int matchCount;
if (!IsApplicable (ctx, method, genericTypeArgs, argTypes, out error, out matchCount))
continue;
if (matchCount == bestCount) {
repeatedBestCount = true;
} else if (matchCount > bestCount) {
match = method;
bestCount = matchCount;
repeatedBestCount = false;
}
}
if (match == null) {
if (!throwIfNotFound)
return null;
if (methodName != null)
throw new EvaluatorException ("Invalid arguments for method `{0}'.", methodName);
throw new EvaluatorException ("Invalid arguments for indexer.");
}
if (repeatedBestCount) {
// If there is an ambiguous match, just pick the first match. If the user was expecting
// something else, he can provide more specific arguments
/* if (!throwIfNotFound)
return null;
if (methodName != null)
throw new EvaluatorException ("Ambiguous method `{0}'; need to use full name", methodName);
else
throw new EvaluatorException ("Ambiguous arguments for indexer.", methodName);
*/ }
return match;
}
public override object TargetObjectToObject (EvaluationContext gctx, object obj)
{
if (obj is StringMirror) {
StringMirror mirror = (StringMirror) obj;
string str;
if (gctx.Options.EllipsizeStrings) {
if (mirror.VirtualMachine.Version.AtLeast (2, 10)) {
int length = mirror.Length;
if (length > gctx.Options.EllipsizedLength)
str = new string (mirror.GetChars (0, gctx.Options.EllipsizedLength)) + EvaluationOptions.Ellipsis;
else
str = mirror.Value;
} else {
str = mirror.Value;
if (str.Length > gctx.Options.EllipsizedLength)
str = str.Substring (0, gctx.Options.EllipsizedLength) + EvaluationOptions.Ellipsis;
}
} else {
str = mirror.Value;
}
return str;
} else if (obj is PrimitiveValue) {
return ((PrimitiveValue)obj).Value;
} else if (obj is PointerValue) {
return new IntPtr (((PointerValue)obj).Address);
} else if (obj is StructMirror) {
StructMirror sm = (StructMirror) obj;
if (sm.Type.IsPrimitive) {
// Boxed primitive
if (sm.Type.FullName == "System.IntPtr")
return new IntPtr ((long)((PrimitiveValue)sm.Fields[0]).Value);
if (sm.Fields.Length > 0 && (sm.Fields[0] is PrimitiveValue))
return ((PrimitiveValue)sm.Fields[0]).Value;
} else if (sm.Type.FullName == "System.Decimal") {
SoftEvaluationContext ctx = (SoftEvaluationContext) gctx;
MethodMirror method = OverloadResolve (ctx, sm.Type, "GetBits", null, new TypeMirror[1] { sm.Type }, false, true, false);
if (method != null) {
ArrayMirror array;
try {
array = sm.Type.InvokeMethod (ctx.Thread, method, new Value[1] { sm }, InvokeOptions.DisableBreakpoints | InvokeOptions.SingleThreaded) as ArrayMirror;
} catch {
array = null;
} finally {
ctx.Session.StackVersion++;
}
if (array != null) {
int[] bits = new int [4];
for (int i = 0; i < 4; i++)
bits[i] = (int) TargetObjectToObject (gctx, array[i]);
return new decimal (bits);
}
}
}
}
return base.TargetObjectToObject (gctx, obj);
}
}
class MethodCall: AsyncOperation
{
SoftEvaluationContext ctx;
MethodMirror function;
object obj;
Value[] args;
Value result;
IAsyncResult handle;
Exception exception;
ST.ManualResetEvent shutdownEvent = new ST.ManualResetEvent (false);
const InvokeOptions options = InvokeOptions.DisableBreakpoints | InvokeOptions.SingleThreaded;
public MethodCall (SoftEvaluationContext ctx, MethodMirror function, object obj, Value[] args)
{
this.ctx = ctx;
this.function = function;
this.obj = obj;
this.args = args;
}
public override string Description {
get {
return function.DeclaringType.FullName + "." + function.Name;
}
}
public override void Invoke ()
{
try {
if (obj is ObjectMirror)
handle = ((ObjectMirror)obj).BeginInvokeMethod (ctx.Thread, function, args, options, null, null);
else if (obj is TypeMirror)
handle = ((TypeMirror)obj).BeginInvokeMethod (ctx.Thread, function, args, options, null, null);
else if (obj is StructMirror)
handle = ((StructMirror)obj).BeginInvokeMethod (ctx.Thread, function, args, options, null, null);
else if (obj is PrimitiveValue)
handle = ((PrimitiveValue)obj).BeginInvokeMethod (ctx.Thread, function, args, options, null, null);
else
throw new ArgumentException ("Soft debugger method calls cannot be invoked on objects of type " + obj.GetType ().Name);
} catch (InvocationException ex) {
ctx.Session.StackVersion++;
exception = ex;
} catch (Exception ex) {
ctx.Session.StackVersion++;
LoggingService.LogError ("Error in soft debugger method call thread on " + GetInfo (), ex);
exception = ex;
}
}
public override void Abort ()
{
if (handle is IInvokeAsyncResult) {
var info = GetInfo ();
LoggingService.LogMessage ("Aborting invocation of " + info);
((IInvokeAsyncResult) handle).Abort ();
// Don't wait for the abort to finish. The engine will do it.
} else {
throw new NotSupportedException ();
}
}
public override void Shutdown ()
{
shutdownEvent.Set ();
}
void EndInvoke ()
{
try {
if (obj is ObjectMirror)
result = ((ObjectMirror)obj).EndInvokeMethod (handle);
else if (obj is TypeMirror)
result = ((TypeMirror)obj).EndInvokeMethod (handle);
else if (obj is StructMirror)
result = ((StructMirror)obj).EndInvokeMethod (handle);
else
result = ((PrimitiveValue)obj).EndInvokeMethod (handle);
} catch (InvocationException ex) {
if (!Aborting && ex.Exception != null) {
string ename = ctx.Adapter.GetValueTypeName (ctx, ex.Exception);
ValueReference vref = ctx.Adapter.GetMember (ctx, null, ex.Exception, "Message");
if (vref != null) {
exception = new Exception (ename + ": " + (string)vref.ObjectValue);
return;
} else {
exception = new Exception (ename);
return;
}
}
exception = ex;
} catch (Exception ex) {
LoggingService.LogError ("Error in soft debugger method call thread on " + GetInfo (), ex);
exception = ex;
} finally {
ctx.Session.StackVersion++;
}
}
string GetInfo ()
{
try {
TypeMirror type = null;
if (obj is ObjectMirror)
type = ((ObjectMirror)obj).Type;
else if (obj is TypeMirror)
type = (TypeMirror)obj;
else if (obj is StructMirror)
type = ((StructMirror)obj).Type;
return string.Format ("method {0} on object {1}",
function == null? "[null]" : function.FullName,
type == null? "[null]" : type.FullName);
} catch (Exception ex) {
LoggingService.LogError ("Error getting info for SDB MethodCall", ex);
return "";
}
}
public override bool WaitForCompleted (int timeout)
{
if (handle == null)
return true;
int res = ST.WaitHandle.WaitAny (new ST.WaitHandle[] { handle.AsyncWaitHandle, shutdownEvent }, timeout);
if (res == 0) {
EndInvoke ();
return true;
}
// Return true if shut down.
return res == 1;
}
public Value ReturnValue {
get {
if (exception != null)
throw new EvaluatorException (exception.Message);
return result;
}
}
}
}
|