Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 1a636b2ae706831ca8f7b55b196af0fc28dbfd37 (plain) (blame)
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
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
/*******************************************************************************
 * Copyright (c) 2006, 2016 Wind River Systems and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *     Ericsson 		  - Modified for handling of multiple execution contexts
 *     Axel Mueller       - Bug 306555 - Add support for cast to type / view as array (IExpressions2)
 *     Jens Elmenthaler (Verigy) - Added Full GDB pretty-printing support (bug 302121)
 *     Marc Khouzam (Ericsson) - Added support for expression aliases for return values of functions (bug 341731)
 *     Abeer Bagul (Tensilica) - Extra partition created for arrays of length 20000 or greater (Bug 443687)
 *******************************************************************************/
package org.eclipse.cdt.dsf.mi.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.cdt.core.IAddress;
import org.eclipse.cdt.dsf.concurrent.DataRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.ImmediateExecutor;
import org.eclipse.cdt.dsf.concurrent.ImmediateRequestMonitor;
import org.eclipse.cdt.dsf.concurrent.RequestMonitor;
import org.eclipse.cdt.dsf.datamodel.AbstractDMContext;
import org.eclipse.cdt.dsf.datamodel.AbstractDMEvent;
import org.eclipse.cdt.dsf.datamodel.DMContexts;
import org.eclipse.cdt.dsf.datamodel.IDMContext;
import org.eclipse.cdt.dsf.debug.service.ICachingService;
import org.eclipse.cdt.dsf.debug.service.IExpressions;
import org.eclipse.cdt.dsf.debug.service.IExpressions2;
import org.eclipse.cdt.dsf.debug.service.IExpressions3;
import org.eclipse.cdt.dsf.debug.service.IFormattedValues;
import org.eclipse.cdt.dsf.debug.service.IMemory.IMemoryChangedEvent;
import org.eclipse.cdt.dsf.debug.service.IMemory.IMemoryDMContext;
import org.eclipse.cdt.dsf.debug.service.IMemorySpaces;
import org.eclipse.cdt.dsf.debug.service.IMemorySpaces.DecodeResult;
import org.eclipse.cdt.dsf.debug.service.IRegisters.IRegisterDMContext;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IContainerSuspendedDMEvent;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IExecutionDMContext;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IExitedDMEvent;
import org.eclipse.cdt.dsf.debug.service.IRunControl.IResumedDMEvent;
import org.eclipse.cdt.dsf.debug.service.IRunControl.ISuspendedDMEvent;
import org.eclipse.cdt.dsf.debug.service.IRunControl.StateChangeReason;
import org.eclipse.cdt.dsf.debug.service.IStack.IFrameDMContext;
import org.eclipse.cdt.dsf.debug.service.command.CommandCache;
import org.eclipse.cdt.dsf.debug.service.command.ICommandControlService;
import org.eclipse.cdt.dsf.gdb.GDBTypeParser.GDBType;
import org.eclipse.cdt.dsf.gdb.internal.GdbPlugin;
import org.eclipse.cdt.dsf.gdb.service.IGDBTraceControl.ITraceRecordSelectedChangedDMEvent;
import org.eclipse.cdt.dsf.mi.service.command.CommandFactory;
import org.eclipse.cdt.dsf.mi.service.command.commands.ExprMetaGetAttributes;
import org.eclipse.cdt.dsf.mi.service.command.commands.ExprMetaGetChildCount;
import org.eclipse.cdt.dsf.mi.service.command.commands.ExprMetaGetChildren;
import org.eclipse.cdt.dsf.mi.service.command.commands.ExprMetaGetValue;
import org.eclipse.cdt.dsf.mi.service.command.commands.ExprMetaGetVar;
import org.eclipse.cdt.dsf.mi.service.command.events.IMIDMEvent;
import org.eclipse.cdt.dsf.mi.service.command.events.MIFunctionFinishedEvent;
import org.eclipse.cdt.dsf.mi.service.command.events.MIStoppedEvent;
import org.eclipse.cdt.dsf.mi.service.command.output.ExprMetaGetAttributesInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.ExprMetaGetChildCountInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.ExprMetaGetChildrenInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.ExprMetaGetValueInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.ExprMetaGetVarInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.MIDataEvaluateExpressionInfo;
import org.eclipse.cdt.dsf.mi.service.command.output.MIFrame;
import org.eclipse.cdt.dsf.service.AbstractDsfService;
import org.eclipse.cdt.dsf.service.DsfServiceEventHandler;
import org.eclipse.cdt.dsf.service.DsfServicesTracker;
import org.eclipse.cdt.dsf.service.DsfSession;
import org.eclipse.cdt.utils.Addr32;
import org.eclipse.cdt.utils.Addr64;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.osgi.framework.BundleContext;

/**
 * This class implements a debugger expression evaluator as a DSF service. The
 * primary interface that clients of this class should use is IExpressions.
 *
 * This class used to be name ExpressionService in the 1.1 release.
 *
 * @since 2.0
 */
public class MIExpressions extends AbstractDsfService implements IMIExpressions, ICachingService {

	private static final int PARTITION_LENGTH = 100;

	/**
	 * A format that gives more details about an expression and supports pretty-printing
	 * provided by the backend.
	 *
	 * @since 3.0
	 */
	public static final String DETAILS_FORMAT = "Details"; //$NON-NLS-1$

	/* The order given here is the order that will be used by DSF in the Details Pane */
	private static final String[] FORMATS_SUPPORTED = new String[] { DETAILS_FORMAT, IFormattedValues.NATURAL_FORMAT,
			IFormattedValues.DECIMAL_FORMAT, IFormattedValues.HEX_FORMAT, IFormattedValues.BINARY_FORMAT,
			IFormattedValues.OCTAL_FORMAT };

	/**
	 * This class represents the two expressions that characterize an Expression Context.
	 */
	public static class ExpressionInfo {
		private final String fullExpression;
		private final String relativeExpression;
		private boolean isDynamic = false;
		private ExpressionInfo parent;
		private int indexInParent = -1;
		private int childCountLimit = IMIExpressions.CHILD_COUNT_LIMIT_UNSPECIFIED;

		public ExpressionInfo(String full, String relative) {
			fullExpression = full;
			relativeExpression = relative;
		}

		/**
		 * @since 4.0
		 */
		public ExpressionInfo(String full, String relative, boolean isDynamic, ExpressionInfo parent,
				int indexInParent) {
			fullExpression = full;
			relativeExpression = relative;
			this.isDynamic = isDynamic;
			this.parent = parent;
			this.indexInParent = indexInParent;
		}

		public String getFullExpr() {
			return fullExpression;
		}

		public String getRelExpr() {
			return relativeExpression;
		}

		@Override
		public boolean equals(Object other) {
			if (other instanceof ExpressionInfo) {
				if (fullExpression == null ? ((ExpressionInfo) other).fullExpression == null
						: fullExpression.equals(((ExpressionInfo) other).fullExpression)) {
					if (relativeExpression == null ? ((ExpressionInfo) other).relativeExpression == null
							: relativeExpression.equals(((ExpressionInfo) other).relativeExpression)) {
						// The other members don't play any role for equality.
						return true;
					}
				}
			}
			return false;
		}

		@Override
		public int hashCode() {
			return (fullExpression == null ? 0 : fullExpression.hashCode())
					^ (relativeExpression == null ? 0 : relativeExpression.hashCode());
			// The other members don't play any role for equality.
		}

		@Override
		public String toString() {
			return "[" + fullExpression + ", " + relativeExpression + ", isDynamic=" + isDynamic + "]"; //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ //$NON-NLS-4$
		}

		/**
		 * @return The parent expression info, if existing.
		 * @since 4.0
		 */
		public ExpressionInfo getParent() {
			return parent;
		}

		/**
		 * @return The index in the child array of the parent. Only valid if
		 *         {@link #getParent()} returns not null.
		 * @since 4.0
		 */
		public int getIndexInParentExpression() {
			return indexInParent;
		}

		/**
		 * @return Whether the corresponding variable object is dynamic,
		 *         i.e. it's value and children are provided by a pretty printer.
		 * @since 4.0
		 */
		public boolean isDynamic() {
			return isDynamic;
		}

		/**
		 * @return Whether the expression info has any ancestor that is dynamic.
		 * @since 4.0
		 */
		public boolean hasDynamicAncestor() {
			for (ExpressionInfo parent = getParent(); parent != null; parent = parent.getParent()) {
				if (parent.isDynamic()) {
					return true;
				}
			}

			return false;
		}

		/**
		 * @param isDynamic
		 *            Whether the value and children of this expression is
		 *            currently provided by a pretty printer or not.
		 * @since 4.0
		 */
		public void setDynamic(boolean isDynamic) {
			this.isDynamic = isDynamic;
		}

		/**
		 * @param parent The new parent expression info.
		 * @since 4.0
		 */
		public void setParent(ExpressionInfo parent) {
			this.parent = parent;
		}

		/**
		 * @param index The index in the children array of the parent.
		 * @since 4.0
		 */
		public void setIndexInParent(int index) {
			this.indexInParent = index;
		}

		/**
		 * @return The current limit on the number of children to be fetched.
		 * @since 4.0
		 */
		public int getChildCountLimit() {
			return childCountLimit;
		}

		/**
		 * @param newLimit
		 *            The new limit on the number of children to be fetched.
		 * @since 4.0
		 */
		public void setChildCountLimit(int newLimit) {
			this.childCountLimit = newLimit;
		}

		/**
		 * @return if this expression is part of the memory space or not.
		 *         If it not part of the memory space, it won't have an address.
		 * @since 4.3
		 */
		public boolean inMemory() {
			// Registers and convenience variables which both start with $
			// are not part of memory.  We care about the top-most parent
			// as it is the only one that can be a register or convenience var.
			if (getParent() == null) {
				if (getRelExpr().startsWith("$")) { //$NON-NLS-1$
					return false;
				}
				return true;
			}

			return getParent().inMemory();
		}
	}

	/**
	 * This class represents an expression.
	 * @noextend This class is not intended to be subclassed by clients.
	 * @since 4.3
	 */
	public static class MIExpressionDMC extends AbstractDMContext implements IExpressionDMContext {
		/**
		 * This field holds an expression to be evaluated.
		 */
		private ExpressionInfo exprInfo;

		/**
		 * ExpressionDMC Constructor for expression to be evaluated in context of
		 * a stack frame.
		 *
		 * @param sessionId
		 *            The session ID in which this context is created.
		 * @param expression
		 *            The expression to be described by this ExpressionDMC
		 * @param relExpr
		 *            The relative expression if this expression was created as a child
		 * @param frameCtx
		 *            The parent stack frame context for this ExpressionDMC.
		 */
		public MIExpressionDMC(String sessionId, String expression, String relExpr, IFrameDMContext frameCtx) {
			this(sessionId, expression, relExpr, (IDMContext) frameCtx);
		}

		/**
		 * ExpressionDMC Constructor for expression to be evaluated in context of
		 * an thread.
		 *
		 * @param sessionId
		 *            The session ID in which this context is created.
		 * @param expression
		 *            The expression to be described by this ExpressionDMC
		 * @param relExpr
		 *            The relative expression if this expression was created as a child
		 * @param execCtx
		 *            The parent thread context for this ExpressionDMC.
		 */
		public MIExpressionDMC(String sessionId, String expression, String relExpr, IMIExecutionDMContext execCtx) {
			this(sessionId, expression, relExpr, (IDMContext) execCtx);
		}

		/**
		 * ExpressionDMC Constructor for expression to be evaluated in context of
		 * a memory space.
		 *
		 * @param sessionId
		 *            The session ID in which this context is created.
		 * @param expression
		 *            The expression to be described by this ExpressionDMC
		 * @param relExpr
		 *            The relative expression if this expression was created as a child
		 * @param memoryCtx
		 *            The parent memory space context for this ExpressionDMC.
		 */
		public MIExpressionDMC(String sessionId, String expression, String relExpr, IMemoryDMContext memoryCtx) {
			this(sessionId, expression, relExpr, (IDMContext) memoryCtx);
		}

		private MIExpressionDMC(String sessionId, String expr, String relExpr, IDMContext parent) {
			this(sessionId, new ExpressionInfo(expr, relExpr), parent);
		}

		/**
		 * ExpressionDMC Constructor for expression to be evaluated in context
		 * of a stack frame.
		 *
		 * @param sessionId
		 *            The session ID in which this context is created.
		 * @param info
		 *            The expression info that this expression is to use.
		 * @param frameCtx
		 *            The parent stack frame context for this ExpressionDMC.
		 *
		 * @since 4.0
		 */
		public MIExpressionDMC(String sessionId, ExpressionInfo info, IFrameDMContext frameCtx) {
			this(sessionId, info, (IDMContext) frameCtx);
		}

		/**
		 * @since 4.3
		 */
		public MIExpressionDMC(String sessionId, ExpressionInfo info, IDMContext parent) {
			super(sessionId, new IDMContext[] { parent });
			exprInfo = info;
		}

		/**
		 * @return True if the two objects are equal, false otherwise.
		 */
		@Override
		public boolean equals(Object other) {
			return super.baseEquals(other) && exprInfo.equals(((MIExpressionDMC) other).exprInfo);
		}

		/**
		 *
		 * @return The hash code of this ExpressionDMC object.
		 */
		@Override
		public int hashCode() {
			return super.baseHashCode() + exprInfo.hashCode();
		}

		/**
		 *
		 * @return A string representation of this ExpressionDMC (including the
		 *         expression to which it is bound).
		 */
		@Override
		public String toString() {
			return baseToString() + ".expr" + exprInfo.toString(); //$NON-NLS-1$
		}

		/**
		 * @return The full expression string represented by this ExpressionDMC
		 */
		@Override
		public String getExpression() {
			return exprInfo.getFullExpr();
		}

		/**
		 * @return The relative expression string represented by this ExpressionDMC
		 */
		public String getRelativeExpression() {
			return exprInfo.getRelExpr();
		}

		/**
		 * @return Get the expression info for this context.
		 * @since 4.0
		 */
		public ExpressionInfo getExpressionInfo() {
			return exprInfo;
		}

		/**
		 * @param info
		 *
		 * @since 4.0
		 */
		public void setExpressionInfo(ExpressionInfo info) {
			assert (this.exprInfo.getFullExpr().equals(info.getFullExpr()));
			assert (this.exprInfo.getRelExpr().equals(info.getRelExpr()));

			this.exprInfo = info;
		}
	}

	protected static class InvalidContextExpressionDMC extends AbstractDMContext implements IExpressionDMContext {
		private final String expression;

		public InvalidContextExpressionDMC(String sessionId, String expr, IDMContext parent) {
			super(sessionId, new IDMContext[] { parent });
			expression = expr;
		}

		@Override
		public boolean equals(Object other) {
			return super.baseEquals(other)
					&& (expression == null ? ((InvalidContextExpressionDMC) other).getExpression() == null
							: expression.equals(((InvalidContextExpressionDMC) other).getExpression()));
		}

		@Override
		public int hashCode() {
			return expression == null ? super.baseHashCode() : super.baseHashCode() ^ expression.hashCode();
		}

		@Override
		public String toString() {
			return baseToString() + ".invalid_expr[" + expression + "]"; //$NON-NLS-1$ //$NON-NLS-2$
		}

		@Override
		public String getExpression() {
			return expression;
		}
	}

	/**
	 * @since 4.1
	 */
	protected static class IndexedPartitionDMC extends MIExpressionDMC implements IIndexedPartitionDMContext {

		final private MIExpressionDMC fParentExpression;
		private final int fIndex;
		private final int fLength;

		/**
		 * @deprecated This method does not keep track of casted expressions.
		 * It has been replaced by the constructor that takes an MIExpressionDMC
		 * as a parameter.
		 */
		@Deprecated
		public IndexedPartitionDMC(String sessionId, ExpressionInfo parentInfo, IFrameDMContext frameCtx, int index,
				int length) {
			this(new MIExpressionDMC(sessionId, parentInfo, frameCtx), frameCtx, index, length);
		}

		/**
		 * @since 4.2
		 */
		public IndexedPartitionDMC(MIExpressionDMC parentExpr, int index, int length) {
			this(parentExpr, getParentDmc(parentExpr), index, length);
		}

		/**
		 * @param parentExpr The expression of the array.  This can be a casted expression.
		 *                   This is not the parent that will be used in the context hierarchy, as we chose
		 *                   not to stack up partitions.
		 * @param parentDmc The frame or thread context that will be used as a parent in the context hierarchy.
		 */
		private IndexedPartitionDMC(MIExpressionDMC parentExpr, IDMContext parentDmc, int index, int length) {
			super(parentExpr.getSessionId(), createExpressionInfo(parentExpr.getExpressionInfo(), index, length),
					parentDmc);
			fIndex = index;
			fLength = length;
			fParentExpression = parentExpr;
		}

		/**
		 * Find the frame context that will be the parent of this partition in the context hierarchy.
		 * Not to be confused with the original parent array that contains the partition.  That parent
		 * can be obtained using getParentExpressionContext()
		 */
		private static IDMContext getParentDmc(MIExpressionDMC parentExpr) {
			IFrameDMContext frameDmc = DMContexts.getAncestorOfType(parentExpr, IFrameDMContext.class);
			if (frameDmc != null) {
				return frameDmc;
			}

			IMIExecutionDMContext execCtx = DMContexts.getAncestorOfType(parentExpr, IMIExecutionDMContext.class);
			if (execCtx != null) {
				// If we have a thread context but not a frame context, we give the user
				// the expression as per the top-most frame of the specified thread.
				// To do this, we create our own frame context.
				DsfServicesTracker tracker = new DsfServicesTracker(GdbPlugin.getBundleContext(),
						parentExpr.getSessionId());
				MIStack stackService = tracker.getService(MIStack.class);
				tracker.dispose();

				if (stackService != null) {
					return stackService.createFrameDMContext(execCtx, 0);
				}
			}

			return parentExpr;
		}

		public ExpressionInfo getParentInfo() {
			return fParentExpression.getExpressionInfo();
		}

		/* (non-Javadoc)
		 * @see org.eclipse.cdt.dsf.debug.service.IExpressions4.IIndexedPartitionDMContext#getParentExpression()
		 */
		@Override
		public String getParentExpression() {
			return getParentExpressionContext().getExpression();
		}

		/**
		 * Get the context of the parent array.  This can be used to know if the
		 * parent array is a casted expression.
		 * @since 4.2
		 */
		public MIExpressionDMC getParentExpressionContext() {
			return fParentExpression;
		}

		@Override
		public int getIndex() {
			return fIndex;
		}

		@Override
		public int getLength() {
			return fLength;
		}

		@Override
		public boolean equals(Object other) {
			return super.baseEquals(other)
					&& ((IndexedPartitionDMC) other).getParentExpressionContext().equals(getParentExpressionContext())
					&& ((IndexedPartitionDMC) other).getIndex() == getIndex()
					&& ((IndexedPartitionDMC) other).getLength() == getLength();
		}

		@Override
		public int hashCode() {
			return super.baseHashCode() + 17 * getIndex() + 31 * getLength();
		}

		@Override
		public String toString() {
			return String.format("%s.expr[%s][%d-%d]", baseToString(), getParentExpression(), getIndex(), //$NON-NLS-1$
					getIndex() + getLength() - 1);
		}

		private static ExpressionInfo createExpressionInfo(ExpressionInfo parentInfo, int index, int length) {
			String expression = String.format("*((%s)+%d)@%d", //$NON-NLS-1$
					parentInfo.getFullExpr(), Integer.valueOf(index), Integer.valueOf(length));
			return new ExpressionInfo(expression, expression);
		}
	}

	/**
	 * Contains the address of an expression as well as the size of its type.
	 */
	protected static class ExpressionDMAddress implements IExpressionDMAddress {
		IAddress fAddr;
		int fSize;
		String fMemSpace = ""; //$NON-NLS-1$

		public ExpressionDMAddress(IAddress addr, int size) {
			fAddr = addr;
			fSize = size;
		}

		public ExpressionDMAddress(String addrStr, int size) {
			fSize = size;
			// We must count the "0x" and that
			// is why we compare with 10 characters
			// instead of 8
			if (addrStr.length() <= 10) {
				fAddr = new Addr32(addrStr);
			} else {
				fAddr = new Addr64(addrStr);
			}
		}

		/**
		 * @since 5.0
		 */
		public ExpressionDMAddress(String addrStr, int size, String memSpace) {
			this(addrStr, size);
			fMemSpace = memSpace;
		}

		@Override
		public IAddress getAddress() {
			return fAddr;
		}

		@Override
		public int getSize() {
			return fSize;
		}

		/**
		 * @since 5.0
		 */
		@Override
		public String getMemorySpaceID() {
			return fMemSpace;
		}

		@Override
		public boolean equals(Object other) {
			if (other instanceof ExpressionDMAddress) {
				ExpressionDMAddress otherAddr = (ExpressionDMAddress) other;
				boolean sameAddr = fAddr == null ? otherAddr.getAddress() == null
						: fAddr.equals(otherAddr.getAddress());
				boolean sameMemSpace = fMemSpace == null ? otherAddr.getMemorySpaceID() == null
						: fMemSpace.equals(otherAddr.getMemorySpaceID());
				return (fSize == otherAddr.getSize()) && sameAddr && sameMemSpace;
			}
			return false;
		}

		@Override
		public int hashCode() {
			return (fAddr == null ? 0 : fAddr.hashCode()) + fSize;
		}

		@Override
		public String toString() {
			return (fAddr == null ? "null" : "(" + fAddr.toHexAddressString()) + ", " + fSize + ")"; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
		}
	}

	/**
	 * If an expressions doesn't have an address, or it cannot be determined,
	 * use this class.
	 * @since 4.0
	 */
	protected class InvalidDMAddress implements IExpressionDMLocation {

		@Override
		public IAddress getAddress() {
			return IExpressions.IExpressionDMLocation.INVALID_ADDRESS;
		}

		@Override
		public int getSize() {
			return 0;
		}

		@Override
		public String getLocation() {
			return ""; //$NON-NLS-1$
		}
	}

	/**
	 * This class represents the static data referenced by an instance of ExpressionDMC,
	 * such as its type and number of children; it does not contain the value or format
	 * of the expression.
	 */
	protected static class ExpressionDMData implements IExpressionDMDataExtension {
		// This is the relative expression, such as the name of a field within a structure,
		// in contrast to the fully-qualified expression contained in the ExpressionDMC,
		// which refers to the full name, including parent structure.
		private final String relativeExpression;
		private final String exprType;

		/**
		 * A hint at the number of children.
		 * In the case of C++ complex structures, this number will not be the
		 * actual number of children.  This is because GDB considers
		 * 'private/protected/public' as an actual level of children, but
		 * we do not.  This number is meant to be used to know if the expression
		 * has children at all.
		 */
		private final int numChildrenHint;

		private final boolean editable;
		private final BasicType fBasicType;

		/**
		 * ExpressionDMData constructor.
		 */
		public ExpressionDMData(String expr, String type, int num, boolean edit) {
			this(expr, type, num, edit, null);
		}

		/**
		 * ExpressionDMData constructor.
		 * @since 3.0
		 */
		public ExpressionDMData(String expr, String type, int num, boolean edit, BasicType basicType) {
			relativeExpression = expr;
			exprType = type;
			numChildrenHint = num;
			editable = edit;
			fBasicType = basicType;
		}

		@Override
		public BasicType getBasicType() {
			return fBasicType;
		}

		@Override
		public String getEncoding() {
			return null;
		}

		@Override
		public Map<String, Integer> getEnumerations() {
			return new HashMap<String, Integer>();
		}

		@Override
		public String getName() {
			return relativeExpression;
		}

		@Override
		public IRegisterDMContext getRegister() {
			return null;
		}

		// See class VariableVMNode for an example of usage of this method
		public String getStringValue() {
			return null;
		}

		@Override
		public String getTypeId() {
			return null;
		}

		@Override
		public String getTypeName() {
			return exprType;
		}

		/**
		 * This method only returns a 'hint' to the number of children.
		 * In the case of C++ complex structures, this number will not be the
		 * actual number of children.  This is because GDB considers
		 * 'private/protected/public' as an actual level of children, but
		 * we do not.
		 *
		 * This method can be used reliably to know if the expression
		 * does have children or not.  However, for this particular use,
		 * the new {@link IExpressionDMDataExtension#hasChildren()} method should be used instead.
		 *
		 * To get the correct number of children of an expression, a call
		 * to {@link IExpressions#getSubExpressionCount} should be used.
		 *
		 * @deprecated
		 */
		@Deprecated
		public int getNumChildren() {
			return numChildrenHint;
		}

		public boolean isEditable() {
			return editable;
		}

		/**
		 * @since 4.0
		 */
		@Override
		public boolean hasChildren() {
			return numChildrenHint > 0;
		}

		@Override
		public boolean equals(Object other) {
			if (other instanceof ExpressionDMData) {
				ExpressionDMData otherData = (ExpressionDMData) other;
				return (numChildrenHint == otherData.numChildrenHint)
						&& (getTypeName() == null ? otherData.getTypeName() == null
								: getTypeName().equals(otherData.getTypeName()))
						&& (getName() == null ? otherData.getName() == null : getName().equals(otherData.getName()));
			}
			return false;
		}

		@Override
		public int hashCode() {
			return relativeExpression == null ? 0
					: relativeExpression.hashCode() + exprType == null ? 0 : exprType.hashCode() + numChildrenHint;
		}

		@Override
		public String toString() {
			return "relExpr=" + relativeExpression + ", type=" + exprType + ", numchildren=" + numChildrenHint; //$NON-NLS-1$ //$NON-NLS-2$//$NON-NLS-3$
		}
	}

	/**
	 * Event generated every time an expression is changed by the ExpressionService.
	 *
	 * A client wishing to receive such events has to register as a service
	 * event listener and implement the corresponding eventDispatched method.
	 *
	 * E.g.:
	 *
	 *    getSession().addServiceEventListener(listenerObject, null);
	 *
	 *    @DsfServiceEventHandler
	 *    public void eventDispatched(ExpressionChangedEvent e) {
	 *       IExpressionDMContext context = e.getDMContext();
	 *       // do something...
	 *    }
	 */
	protected static class ExpressionChangedEvent extends AbstractDMEvent<IExpressionDMContext>
			implements IExpressionChangedDMEvent {

		public ExpressionChangedEvent(IExpressionDMContext context) {
			super(context);
		}
	}

	/**
	 * Keeps track of aliases for return values of methods.
	 */
	private class ReturnValueAliasing {
		/**
		 *  Map of expression to alias.  The expression is the name of the convenience variable
		 *  storing the return value, e.g., $1 -> "foo() returned"
		 *  This map allows to quickly find the alias to be used for return value variables.
		 */
		private Map<String, String> fExpressionAliasesMap = new HashMap<String, String>();
		/**
		 * Map of thread to aliases expression list.  This map allows to know which aliases are related
		 * to a thread of execution.  This is important to allow us to delete aliases when a
		 * thread exits.  Note that we need a list because we keep all previous aliases until
		 * the thread exits.
		 */
		private Map<IMIExecutionDMContext, List<String>> fThreadToAliasedExpressionsMap = new HashMap<IMIExecutionDMContext, List<String>>();
		/**
		 * Map of thread to the name of the method the thread last stopped in.
		 * This allows us to create the alias based on the method the thread was in
		 * before it returned out of the method.
		 */
		private Map<IMIExecutionDMContext, String> fThreadToTopMethodName = new HashMap<IMIExecutionDMContext, String>();

		/**
		 * Create an alias for expr with respect to threadDmc.
		 * The alias is created based on where threadDmc was previously stopped.
		 */
		public void createAlias(IMIExecutionDMContext threadDmc, String expr) {
			String alias = expr;
			String methodName = fThreadToTopMethodName.get(threadDmc);
			if (methodName != null) {
				alias = String.format(Messages.MIExpressions_ReturnValueAlias, methodName + "()"); //$NON-NLS-1$
			}

			fExpressionAliasesMap.put(expr, alias);

			List<String> aliasedExprList = fThreadToAliasedExpressionsMap.get(threadDmc);
			if (aliasedExprList == null) {
				aliasedExprList = new ArrayList<String>();
				fThreadToAliasedExpressionsMap.put(threadDmc, aliasedExprList);
			}
			aliasedExprList.add(expr);
		}

		/**
		 * Clear all information related to a particular thread of execution.
		 */
		public void clearThread(IMIExecutionDMContext threadDmc) {
			fThreadToTopMethodName.remove(threadDmc);
			clearAliases(threadDmc);
		}

		/**
		 * Clear all aliased expressions related to a particular thread of execution.
		 * It is good to keep the aliases around as long as the thread is alive;
		 * even if we won't show the return value automatically, the user
		 * could add the expression in the expression view, and the alias
		 * would then be used.
		 */
		public void clearAliases(IMIExecutionDMContext threadDmc) {
			List<String> aliasedExprList = fThreadToAliasedExpressionsMap.remove(threadDmc);
			if (aliasedExprList != null) {
				for (String expr : aliasedExprList) {
					fExpressionAliasesMap.remove(expr);
				}
			}
		}

		/**
		 * Update the method name of the last location where threadDmc was stopped.
		 */
		public void updateStoppedLocation(IMIExecutionDMContext threadDmc, String methodName) {
			fThreadToTopMethodName.put(threadDmc, methodName);
		}

		/**
		 * @return The alias for 'expr' if there is one.  null if there
		 *         is no alias for that expression.
		 */
		public String getAlias(String expr) {
			String alias = fExpressionAliasesMap.get(expr);
			if (alias == null) {
				// Check if the expression contains the string that must be aliased.
				// E.g., $1[0], *$2
				// If it does, just replace that string within the expression to
				// create the full alias
				for (Entry<String, String> entry : fExpressionAliasesMap.entrySet()) {
					int index = expr.indexOf(entry.getKey());
					if (index != -1) {
						// Found the string! Now replace it with our alias.
						// We put it between () to make things clearer to the user.
						// Note that there can only be one string contained
						// in the expression, so once we found it, we are done.
						alias = expr.substring(0, index) + "(" + entry.getValue() + ")" + //$NON-NLS-1$ //$NON-NLS-2$
								expr.substring(index + entry.getKey().length());
						break;
					}
				}
			}
			return alias;
		}
	}

	/** Structure to keep track of aliases for method return values. */
	private ReturnValueAliasing fReturnValueAliases = new ReturnValueAliasing();

	/**
	 * @since 4.3
	 */
	protected CommandCache fExpressionCache;

	private CommandFactory fCommandFactory;
	private MIVariableManager varManager;

	/**
	 * Indicates that we are currently visualizing trace data.
	 * In this case, some errors should not be reported.
	 */
	private boolean fTraceVisualization;
	private IMemorySpaces fMemorySpaceService;

	public MIExpressions(DsfSession session) {
		super(session);
	}

	/**
	 * This method initializes this service.
	 *
	 * @param requestMonitor
	 *            The request monitor indicating the operation is finished
	 */
	@Override
	public void initialize(final RequestMonitor requestMonitor) {
		super.initialize(new ImmediateRequestMonitor(requestMonitor) {
			@Override
			protected void handleSuccess() {
				doInitialize(requestMonitor);
			}
		});
	}

	/**
	 * This method initializes this service after our superclass's initialize()
	 * method succeeds.
	 *
	 * @param requestMonitor
	 *            The call-back object to notify when this service's
	 *            initialization is done.
	 */
	private void doInitialize(RequestMonitor requestMonitor) {

		// Register to receive service events for this session.
		getSession().addServiceEventListener(this, null);

		// Register this service, but only if we don't already have an
		// IExpression service present.  This allows another expression
		// service to be used, while delegating calls to this service.
		if (getServicesTracker().getService(IExpressions.class) == null) {
			register(new String[] { IExpressions.class.getName(), IExpressions2.class.getName(),
					IExpressions3.class.getName(), IMIExpressions.class.getName(), MIExpressions.class.getName() },
					new Hashtable<String, String>());
		}

		// Create the expressionService-specific CommandControl which is our
		// variable object manager.
		// It will deal with the meta-commands, before sending real MI commands
		// to the back-end, through the MICommandControl service
		// It must be created after the ExpressionService is registered
		// since it will need to find it.
		varManager = createMIVariableManager();

		// Create the meta command cache which will use the variable manager
		// to actually send MI commands to the back-end
		fExpressionCache = new CommandCache(getSession(), varManager);
		ICommandControlService commandControl = getServicesTracker().getService(ICommandControlService.class);
		fExpressionCache.setContextAvailable(commandControl.getContext(), true);

		fCommandFactory = getServicesTracker().getService(IMICommandControl.class).getCommandFactory();

		fMemorySpaceService = getServicesTracker().getService(IMemorySpaces.class);

		requestMonitor.done();
	}

	/**
	 * Creates the MI variable manager to be used by this expression service.
	 * Overriding classes may override to provide a custom services tracker.
	 *
	 * @since 3.0
	 */
	protected MIVariableManager createMIVariableManager() {
		return new MIVariableManager(getSession(), getServicesTracker());
	}

	/**
	 * This method shuts down this service. It unregisters the service, stops
	 * receiving service events, and calls the superclass shutdown() method to
	 * finish the shutdown process.
	 */
	@Override
	public void shutdown(RequestMonitor requestMonitor) {
		unregister();
		varManager.dispose();
		getSession().removeServiceEventListener(this);
		super.shutdown(requestMonitor);
	}

	/**
	 * @return The bundle context of the plug-in to which this service belongs.
	 */
	@Override
	protected BundleContext getBundleContext() {
		return GdbPlugin.getBundleContext();
	}

	/**
	 * Create an expression context with the same full and relative expression
	 */
	@Override
	public IExpressionDMContext createExpression(IDMContext ctx, String expression) {
		return createExpression(ctx, expression, expression);
	}

	/**
	 * Create an expression context.
	 */
	public IExpressionDMContext createExpression(IDMContext ctx, String expression, String relExpr) {
		return createExpression(ctx, new ExpressionInfo(expression, relExpr));
	}

	/**
	 * Create an expression context from a given expression info.
	 * @since 4.0
	 */
	private IExpressionDMContext createExpression(IDMContext ctx, ExpressionInfo info) {
		String expression = info.getFullExpr();
		IFrameDMContext frameDmc = DMContexts.getAncestorOfType(ctx, IFrameDMContext.class);
		if (frameDmc != null) {
			return new MIExpressionDMC(getSession().getId(), info, frameDmc);
		}

		IMIExecutionDMContext execCtx = DMContexts.getAncestorOfType(ctx, IMIExecutionDMContext.class);
		if (execCtx != null) {
			// If we have a thread context but not a frame context, we give the user
			// the expression as per the top-most frame of the specified thread.
			// To do this, we create our own frame context.
			MIStack stackService = getServicesTracker().getService(MIStack.class);
			if (stackService != null) {
				frameDmc = stackService.createFrameDMContext(execCtx, 0);
				return new MIExpressionDMC(getSession().getId(), info, frameDmc);
			}

			return new InvalidContextExpressionDMC(getSession().getId(), expression, execCtx);
		}

		IMemoryDMContext memoryCtx = DMContexts.getAncestorOfType(ctx, IMemoryDMContext.class);
		if (memoryCtx != null) {
			return new MIExpressionDMC(getSession().getId(), info, memoryCtx);
		}

		// Don't care about the relative expression at this point
		return new InvalidContextExpressionDMC(getSession().getId(), expression, ctx);
	}

	/**
	 * @see IFormattedValues.getFormattedValueContext(IFormattedDataDMContext, String)
	 *
	 * @param dmc
	 *            The context describing the data for which we want to create
	 *            a Formatted context.
	 * @param formatId
	 *            The format that will be used to create the Formatted context
	 *
	 * @return A FormattedValueDMContext that can be used to obtain the value
	 *         of an expression in a specific format.
	 */

	@Override
	public FormattedValueDMContext getFormattedValueContext(IFormattedDataDMContext dmc, String formatId) {
		return new FormattedValueDMContext(this, dmc, formatId);
	}

	/**
	 * @see IFormattedValues.getAvailableFormats(IFormattedDataDMContext, DataRequestMonitor)
	 *
	 * @param dmc
	 *            The context describing the data for which we want to know
	 *            which formats are available.
	 * @param rm
	 *            The data request monitor for this asynchronous operation.
	 *
	 */

	@Override
	public void getAvailableFormats(IFormattedDataDMContext dmc, final DataRequestMonitor<String[]> rm) {
		rm.setData(FORMATS_SUPPORTED);
		rm.done();
	}

	/**
	 * Obtains the static data of an expression represented
	 * by an ExpressionDMC object (<tt>dmc</tt>).
	 *
	 * @param dmc
	 *            The ExpressionDMC for the expression to be evaluated.
	 * @param rm
	 *            The data request monitor that will contain the requested data
	 */
	@Override
	public void getExpressionData(final IExpressionDMContext dmc, final DataRequestMonitor<IExpressionDMData> rm) {
		if (dmc instanceof MIExpressionDMC) {
			fExpressionCache.execute(new ExprMetaGetVar(dmc),
					new DataRequestMonitor<ExprMetaGetVarInfo>(getExecutor(), rm) {

						@Override
						protected void handleSuccess() {
							IExpressionDMData.BasicType basicType = getBasicType(getData());

							String relativeExpr = getData().getExpr();
							String alias = fReturnValueAliases.getAlias(relativeExpr);
							if (alias != null) {
								relativeExpr = alias;
							}
							rm.setData(new ExpressionDMData(relativeExpr, getData().getType(),
									getData().getNumChildren(), getData().getEditable(), basicType));
							rm.done();
						}
					});
		} else if (dmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	/**
	 * @since 4.7
	 */
	protected IExpressionDMData.BasicType getBasicType(ExprMetaGetVarInfo varInfo) {
		IExpressionDMData.BasicType basicType = null;

		GDBType gdbType = varInfo.getGDBType();

		if (gdbType != null) {
			switch (gdbType.getType()) {
			case GDBType.ARRAY:
				basicType = IExpressionDMData.BasicType.array;
				break;
			case GDBType.FUNCTION:
				basicType = IExpressionDMData.BasicType.function;
				break;
			case GDBType.POINTER:
			case GDBType.REFERENCE:
				basicType = IExpressionDMData.BasicType.pointer;
				break;
			case GDBType.GENERIC:
			default:
				// The interesting question is not hasChildren,
				// but canHaveChildren. E.g. an empty
				// collection still is a composite.
				if (varInfo.hasChildren() || varInfo.getCollectionHint()) {
					basicType = IExpressionDMData.BasicType.composite;
				} else {
					basicType = IExpressionDMData.BasicType.basic;
				}
				break;
			}
		}
		return basicType;
	}

	/**
	 * Obtains the address of an expression and the size of its type.
	 *
	 * @param dmc
	 *            The ExpressionDMC for the expression.
	 * @param rm
	 *            The data request monitor that will contain the requested data
	 */
	@Override
	public void getExpressionAddressData(final IExpressionDMContext dmc,
			final DataRequestMonitor<IExpressionDMAddress> rm) {

		if (dmc instanceof MIExpressionDMC) {
			MIExpressionDMC miDMC = (MIExpressionDMC) dmc;
			if (miDMC.getExpressionInfo().hasDynamicAncestor() || !miDMC.getExpressionInfo().inMemory()) {
				// For children of dynamic varobjs, there is no full expression that gdb
				// could evaluate in order to provide address and size.
				// Also, if an expression is not in memory, such as a register
				// or a GDB convenience variable, there is no address to return
				rm.setData(new InvalidDMAddress());
				rm.done();
				return;
			}
		}

		// First create an address expression and a size expression
		// to be used in back-end calls
		final IExpressionDMContext addressDmc = createExpression(dmc, "&(" + dmc.getExpression() + ")");//$NON-NLS-1$//$NON-NLS-2$
		final IExpressionDMContext sizeDmc = createExpression(dmc, "sizeof(" + dmc.getExpression() + ")"); //$NON-NLS-1$//$NON-NLS-2$

		if (addressDmc instanceof InvalidContextExpressionDMC || sizeDmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			fExpressionCache.execute(fCommandFactory.createMIDataEvaluateExpression(addressDmc),
					new DataRequestMonitor<MIDataEvaluateExpressionInfo>(getExecutor(), rm) {
						@Override
						protected void handleSuccess() {
							String tmpAddrStr = getData().getValue();

							DecodeResult memSpaceParsed = null;
							if (fMemorySpaceService != null) {
								try {
									memSpaceParsed = fMemorySpaceService.decodeAddress(tmpAddrStr);
								} catch (CoreException e1) {
									// No memory space id found
								}
							}

							String tMemSpace = ""; //$NON-NLS-1$
							if (memSpaceParsed != null) {
								tmpAddrStr = memSpaceParsed.getExpression();
								tMemSpace = memSpaceParsed.getMemorySpaceId();
							}

							final String memSpaceId = tMemSpace;

							// Deal with addresses of contents of a char* which is in
							// the form of "0x12345678 \"This is a string\""
							int split = tmpAddrStr.indexOf(' ');
							if (split != -1)
								tmpAddrStr = tmpAddrStr.substring(0, split);
							final String addrStr = tmpAddrStr;

							fExpressionCache.execute(fCommandFactory.createMIDataEvaluateExpression(sizeDmc),
									new DataRequestMonitor<MIDataEvaluateExpressionInfo>(getExecutor(), rm) {
										@Override
										protected void handleSuccess() {
											try {
												int size = Integer.parseInt(getData().getValue());
												rm.setData(new ExpressionDMAddress(addrStr, size, memSpaceId));
											} catch (NumberFormatException e) {
												rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID,
														INVALID_HANDLE, "Unexpected size format from backend: " //$NON-NLS-1$
																+ getData().getValue(),
														null));
											}
											rm.done();
										}
									});
						}
					});
		}
	}

	/**
	 * Obtains the value of an expression in a specific format.
	 *
	 * @param dmc
	 *            The context for the format of the value requested and
	 *            for the expression to be evaluated.  The expression context
	 *            should be a parent of the FormattedValueDMContext.
	 * @param rm
	 *            The data request monitor that will contain the requested data
	 */
	@Override
	public void getFormattedExpressionValue(final FormattedValueDMContext dmc,
			final DataRequestMonitor<FormattedValueDMData> rm) {
		// We need to make sure the FormattedValueDMContext also holds an ExpressionContext,
		// or else this method cannot do its work.
		// Note that we look for MIExpressionDMC and not IExpressionDMC, because
		// looking for IExpressionDMC could yield InvalidContextExpressionDMC which is still
		// not what we need.
		MIExpressionDMC exprDmc = DMContexts.getAncestorOfType(dmc, MIExpressionDMC.class);
		if (exprDmc == null) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			if (DETAILS_FORMAT.equals(dmc.getFormatID())) {
				if (exprDmc.getExpressionInfo().hasDynamicAncestor()) {
					// -data-evaluate-expression does not work for children of
					// dynamic varobjs, since there is no full expression
					// that gdb could evaluate.
					rm.setData(
							new FormattedValueDMData(Messages.MIExpressions_NotAvailableBecauseChildOfDynamicVarobj));
					rm.done();
				} else {
					// This format is obtained through a different GDB command.
					// It yields more details than the variableObject output.
					// Starting with GDB 7.0, this format automatically supports pretty-printing, as long as
					// GDB has been configured to support it.
					fExpressionCache.execute(fCommandFactory.createMIDataEvaluateExpression(exprDmc),
							new DataRequestMonitor<MIDataEvaluateExpressionInfo>(getExecutor(), rm) {
								@Override
								protected void handleSuccess() {
									rm.setData(new FormattedValueDMData(getData().getValue()));
									rm.done();
								}

								@Override
								protected void handleError() {
									if (fTraceVisualization) {
										rm.setData(new FormattedValueDMData("")); //$NON-NLS-1$
										rm.done();
									} else {
										super.handleError();
									}
								}
							});
				}
			} else {
				fExpressionCache.execute(new ExprMetaGetValue(dmc),
						new DataRequestMonitor<ExprMetaGetValueInfo>(getExecutor(), rm) {
							@Override
							protected void handleSuccess() {
								rm.setData(new FormattedValueDMData(getData().getValue()));
								rm.done();
							}
						});
			}
		}
	}

	/* Not implemented
	 *
	 * (non-Javadoc)
	 * @see org.eclipse.cdt.dsf.debug.service.IExpressions#getBaseExpressions(org.eclipse.cdt.dsf.debug.service.IExpressions.IExpressionDMContext, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor)
	 */
	@Override
	public void getBaseExpressions(IExpressionDMContext exprContext, DataRequestMonitor<IExpressionDMContext[]> rm) {
		rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, NOT_SUPPORTED, "Not supported", null)); //$NON-NLS-1$
		rm.done();
	}

	/**
	 * Retrieves the children expressions of the specified expression
	 *
	 * @param dmc
	 *            The context for the expression for which the children
	 *            should be retrieved.
	 * @param rm
	 *            The data request monitor that will contain the requested data
	 */
	@Override
	public void getSubExpressions(IExpressionDMContext dmc, DataRequestMonitor<IExpressionDMContext[]> rm) {
		getSubExpressions(dmc, -1, -1, rm);
	}

	/**
	 * Retrieves a range of children expressions of the specified expression
	 *
	 * @param exprCtx
	 *            The context for the expression for which the children
	 *            should be retrieved.
	 * @param startIndex
	 *            The starting index within the list of all children of the parent
	 *            expression.  Must be a positive integer.
	 * @param length
	 *            The length or number of elements of the range requested.
	 *            Must be a positive integer.
	 * @param rm
	 *            The data request monitor that will contain the requested data
	 */
	@Override
	public void getSubExpressions(final IExpressionDMContext exprCtx, final int startIndex, final int length,
			final DataRequestMonitor<IExpressionDMContext[]> rm) {

		if (exprCtx instanceof IndexedPartitionDMC) {
			getIndexedPartitionChildren((IndexedPartitionDMC) exprCtx, startIndex, length, rm);
		} else if (exprCtx instanceof MIExpressionDMC) {
			getRealSubExpressionCount(exprCtx, IMIExpressions.CHILD_COUNT_LIMIT_UNSPECIFIED,
					new DataRequestMonitor<Integer>(getExecutor(), rm) {
						/* (non-Javadoc)
						 * @see org.eclipse.cdt.dsf.concurrent.RequestMonitor#handleSuccess()
						 */
						@Override
						protected void handleSuccess() {
							final int realNumChildren = getData().intValue();
							if (realNumChildren == 0) {
								rm.setData(new IExpressionDMContext[0]);
								rm.done();
								return;
							}

							if (realNumChildren <= getArrayPartitionLength()) {
								getRealSubExpressions(exprCtx, startIndex, length, rm);
							} else {
								getExpressionData(exprCtx,
										new DataRequestMonitor<IExpressionDMData>(ImmediateExecutor.getInstance(), rm) {

											@Override
											protected void handleSuccess() {
												if (IExpressionDMData.BasicType.array
														.equals(getData().getBasicType())) {
													rm.setData(getTopLevelIndexedPartitions((MIExpressionDMC) exprCtx,
															realNumChildren, startIndex, length));
													rm.done();
												} else {
													getRealSubExpressions(exprCtx, startIndex, length, rm);
												}
											}
										});
							}
						}
					});
		} else if (exprCtx instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	/**
	 * @since 4.0
	 */
	@Override
	public void safeToAskForAllSubExpressions(IExpressionDMContext dmc, final DataRequestMonitor<Boolean> rm) {
		if (dmc instanceof MIExpressionDMC) {
			fExpressionCache.execute(new ExprMetaGetVar(dmc),
					new DataRequestMonitor<ExprMetaGetVarInfo>(getExecutor(), rm) {
						@Override
						protected void handleSuccess() {
							boolean safe = getData().isSafeToAskForAllChildren();

							rm.setData(safe);
							rm.done();
						}
					});
		} else if (dmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	/**
	 * @since 4.0
	 */
	@Override
	public void getSubExpressionCount(final IExpressionDMContext dmc, final int numChildLimit,
			final DataRequestMonitor<Integer> rm) {

		if (dmc instanceof MIExpressionDMC) {
			if (dmc instanceof IndexedPartitionDMC) {
				int length = ((IndexedPartitionDMC) dmc).getLength();
				rm.setData(computeNumberOfChildren(length));
				rm.done();
			} else {
				getRealSubExpressionCount(dmc, numChildLimit, new DataRequestMonitor<Integer>(getExecutor(), rm) {

					@Override
					protected void handleSuccess() {
						final int realNum = getData().intValue();
						if (realNum <= getArrayPartitionLength()) {
							rm.setData(Integer.valueOf(realNum));
							rm.done();
						} else {
							getExpressionData(dmc,
									new DataRequestMonitor<IExpressionDMData>(ImmediateExecutor.getInstance(), rm) {

										@Override
										protected void handleSuccess() {
											if (IExpressionDMData.BasicType.array.equals(getData().getBasicType())) {
												rm.setData(computeNumberOfChildren(realNum));
											} else {
												rm.setData(Integer.valueOf(realNum));
											}
											rm.done();
										}
									});
						}
					}
				});
			}
		} else if (dmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	/**
	 * Retrieves the count of children expressions of the specified expression
	 *
	 * @param dmc
	 *            The context for the expression for which the children count
	 *            should be retrieved.
	 * @param rm
	 *            The data request monitor that will contain the requested data
	 */
	@Override
	public void getSubExpressionCount(IExpressionDMContext dmc, final DataRequestMonitor<Integer> rm) {
		getSubExpressionCount(dmc, IMIExpressions.CHILD_COUNT_LIMIT_UNSPECIFIED, rm);
	}

	/**
	 * This method indicates if an expression can be written to.
	 *
	 * @param dmc The data model context representing an expression.
	 *
	 * @param rm Data Request monitor containing True if this expression's value can be edited.  False otherwise.
	 */

	@Override
	public void canWriteExpression(IExpressionDMContext dmc, final DataRequestMonitor<Boolean> rm) {
		if (dmc instanceof MIExpressionDMC) {
			fExpressionCache.execute(new ExprMetaGetAttributes(dmc),
					new DataRequestMonitor<ExprMetaGetAttributesInfo>(getExecutor(), rm) {
						@Override
						protected void handleSuccess() {
							rm.setData(getData().getEditable());
							rm.done();
						}
					});
		} else if (dmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	/**
	 * Changes the value of the specified expression based on the new value and format.
	 *
	 * @param dmc
	 *            The context for the expression for which the value
	 *            should be changed.
	 * @param expressionValue
	 *            The new value for the specified expression
	 * @param formatId
	 *            The format in which the value is specified
	 * @param rm
	 *            The request monitor that will indicate the completion of the operation
	 */
	@Override
	public void writeExpression(final IExpressionDMContext dmc, String expressionValue, String formatId,
			final RequestMonitor rm) {

		if (dmc instanceof MIExpressionDMC) {
			// This command must not be cached, since it changes the state of the back-end.
			// We must send it directly to the variable manager
			varManager.writeValue(dmc, expressionValue, formatId, new RequestMonitor(getExecutor(), rm) {
				@Override
				protected void handleSuccess() {
					// A value has changed, we should remove any references to that
					// value in our cache.  Since we don't have such granularity,
					// we must clear the entire cache.
					// We cannot use the context to do a more-specific reset, because
					// the same global variable can be set with different contexts
					fExpressionCache.reset();

					// Issue event that the expression has changed
					getSession().dispatchEvent(new ExpressionChangedEvent(dmc), getProperties());

					rm.done();
				}
			});
		} else if (dmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	@DsfServiceEventHandler
	public void eventDispatched(IResumedDMEvent e) {
		fExpressionCache.setContextAvailable(e.getDMContext(), false);
		if (e.getReason() != StateChangeReason.STEP) {
			fExpressionCache.reset();
		}
	}

	@DsfServiceEventHandler
	public void eventDispatched(ISuspendedDMEvent e) {
		fExpressionCache.setContextAvailable(e.getDMContext(), true);
		fExpressionCache.reset();

		handleReturnValueAliasing(e);
	}

	private void handleReturnValueAliasing(ISuspendedDMEvent e) {
		// Process MIStoppedEvent from within the ISuspendedDMEvent
		// to avoid any race conditions where the actual MIStoppedEvent
		// can arrive faster that a preceding IResumedDMEvent
		if (e instanceof IMIDMEvent) {
			Object miEvent = ((IMIDMEvent) e).getMIEvent();
			if (miEvent instanceof MIStoppedEvent) {
				IMIExecutionDMContext stoppedEventThread = null;
				if (e instanceof IContainerSuspendedDMEvent) {
					// All-stop mode
					IExecutionDMContext[] triggerContexts = ((IContainerSuspendedDMEvent) e).getTriggeringContexts();
					if (triggerContexts.length != 0 && triggerContexts[0] instanceof IMIExecutionDMContext) {
						stoppedEventThread = (IMIExecutionDMContext) triggerContexts[0];
					}
				} else {
					// Non-stop mode
					IDMContext dmc = e.getDMContext();
					if (dmc instanceof IMIExecutionDMContext) {
						stoppedEventThread = (IMIExecutionDMContext) dmc;
					}
				}

				if (stoppedEventThread != null) {
					if (miEvent instanceof MIFunctionFinishedEvent) {
						// When getting an MIFunctionFinishedEvent we must set
						// a proper alias for the convenience variable
						String resultVar = ((MIFunctionFinishedEvent) miEvent).getGDBResultVar();
						if (resultVar != null && !resultVar.isEmpty()) {
							fReturnValueAliases.createAlias(stoppedEventThread, resultVar);
						}
					}

					// Keep track of the latest method the thread is stopped in.
					// Must do this after creating any alias, or else we will overwrite
					// the previous function name, which we need for the alias
					MIFrame frame = ((MIStoppedEvent) miEvent).getFrame();
					if (frame != null) {
						fReturnValueAliases.updateStoppedLocation(stoppedEventThread, frame.getFunction());
					}
				}
			}
		}
	}

	@DsfServiceEventHandler
	public void eventDispatched(IMemoryChangedEvent e) {
		fExpressionCache.reset();
		// MIVariableManager separately traps this event
	}

	/** @since 3.0 */
	@DsfServiceEventHandler
	public void eventDispatched(ITraceRecordSelectedChangedDMEvent e) {
		if (e.isVisualizationModeEnabled()) {
			fTraceVisualization = true;
		} else {
			fTraceVisualization = false;
		}
	}

	/**
	 * @nooverride This method is not intended to be re-implemented or extended by clients.
	 * @noreference This method is not intended to be referenced by clients.
	 */
	@DsfServiceEventHandler
	public void eventDispatched(IExitedDMEvent e) {
		IDMContext ctx = e.getDMContext();
		if (ctx instanceof IMIExecutionDMContext) {
			// When a thread exits, clear the alias structure for that
			// thread to avoid leaks
			fReturnValueAliases.clearThread((IMIExecutionDMContext) ctx);
		}
	}

	/**
	 * {@inheritDoc}
	 * @since 1.1
	 */
	@Override
	public void flushCache(IDMContext context) {
		fExpressionCache.reset(context);
		// We must also mark all variable objects as out-of-date
		// to refresh them as well
		varManager.markAllOutOfDate();
	}

	/**
	 * A casted or array-displayed expression.
	 * @since 3.0
	 */
	protected class CastedExpressionDMC extends MIExpressionDMC implements ICastedExpressionDMContext {

		private final CastInfo fCastInfo;

		public CastedExpressionDMC(MIExpressionDMC exprDMC, String castExpression, CastInfo castInfo) {
			super(getSession().getId(), castExpression, exprDMC.getRelativeExpression(), exprDMC);
			fCastInfo = castInfo;
		}

		/* (non-Javadoc)
		 * @see org.eclipse.cdt.dsf.debug.service.IExpressions2.ICastedExpressionDMContext#getCastInfo()
		 */
		@Override
		public CastInfo getCastInfo() {
			return fCastInfo;
		}

		/**
		 * @return True if the two objects are equal, false otherwise.
		 */
		@Override
		public boolean equals(Object other) {
			return super.equals(other) && fCastInfo.equals(((CastedExpressionDMC) other).fCastInfo);
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.dsf.debug.service.IExpressions2#createCastedExpression(org.eclipse.cdt.dsf.datamodel.IDMContext, java.lang.String, org.eclipse.cdt.dsf.debug.service.IExpressions2.ICastedExpressionDMContext)
	 */
	/** @since 3.0 */
	@Override
	public ICastedExpressionDMContext createCastedExpression(IExpressionDMContext exprDMC, CastInfo castInfo) {
		if (exprDMC instanceof MIExpressionDMC && castInfo != null) {
			String castType = castInfo.getTypeString();
			String castExpression = exprDMC.getExpression();
			int castingLength = castInfo.getArrayCount();
			int castingIndex = castInfo.getArrayStartIndex();

			// cast to type
			if (castType != null && !castType.isEmpty()) {
				StringBuilder buffer = new StringBuilder();
				buffer.append('(').append(castType).append(')');
				buffer.append('(').append(castExpression).append(')');
				castExpression = buffer.toString();
			}

			// cast to array (can be in addition to cast to type)
			if (castingLength > 0) {
				StringBuilder buffer = new StringBuilder();
				buffer.append("*("); //$NON-NLS-1$
				buffer.append('(').append(castExpression).append(')');
				buffer.append('+').append(castingIndex).append(')');
				buffer.append('@').append(castingLength);
				castExpression = buffer.toString();
			}

			// Surround the entire casted expression with parenthesis in case we are
			// dealing with an array.  Arrays must be parenthesized before they are
			// subscripted.  Note that we can be casting to an array or displaying
			// as an array, so we must do this all the time.
			castExpression = String.format("(%s)", castExpression); //$NON-NLS-1$

			return new CastedExpressionDMC((MIExpressionDMC) exprDMC, castExpression, castInfo);
		} else {
			assert false;
			return null;
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.dsf.debug.service.IExpressions3#getExpressionDataExtension(org.eclipse.cdt.dsf.debug.service.IExpressions.IExpressionDMContext, org.eclipse.cdt.dsf.concurrent.DataRequestMonitor)
	 */
	/** @since 4.0 */
	@Override
	public void getExpressionDataExtension(IExpressionDMContext dmc,
			final DataRequestMonitor<IExpressionDMDataExtension> rm) {
		getExpressionData(dmc, new DataRequestMonitor<IExpressionDMData>(getExecutor(), rm) {
			@Override
			protected void handleSuccess() {
				rm.setData((IExpressionDMDataExtension) getData());
				super.handleSuccess();
			}
		});
	}

	private IndexedPartitionDMC[] getTopLevelIndexedPartitions(MIExpressionDMC exprCtx, int realNumChildren,
			int startIndex, int length) {

		int numChildren = computeNumberOfChildren(realNumChildren);
		if (startIndex >= numChildren)
			return new IndexedPartitionDMC[0];
		int startIndex1 = (startIndex < 0) ? 0 : startIndex;
		int length1 = (length < 0) ? numChildren - startIndex1 : Math.min(length, numChildren - startIndex1);

		IndexedPartitionDMC[] children = new IndexedPartitionDMC[numChildren];
		int index = 0;
		// If the parent array is a casted expression it could have a different
		// start index.  We want the partition to start at the right index, not always 0
		//		if (exprCtx instanceof ICastedExpressionDMContext) {
		//			index = ((ICastedExpressionDMContext)exprCtx).getCastInfo().getArrayStartIndex();
		//		}
		for (int i = 0; i < children.length; ++i) {
			int partLength = computePartitionLength(realNumChildren, i);
			children[i] = createIndexedPartition(exprCtx, index, partLength);
			index += partLength;
		}
		return Arrays.copyOfRange(children, startIndex1, startIndex1 + length1);
	}

	private void getIndexedPartitionChildren(final IndexedPartitionDMC partDmc, final int startIndex, final int length,
			final DataRequestMonitor<IExpressionDMContext[]> rm) {

		final int startIndex1 = (startIndex < 0) ? 0 : startIndex;
		final int length1 = (length < 0) ? Integer.MAX_VALUE : length;

		final int partStartIndex = partDmc.getIndex();
		final int partLength = partDmc.getLength();
		if (partLength > getArrayPartitionLength()) {
			// create subpartitions
			int numChildren = computeNumberOfChildren(partLength);

			if (startIndex1 >= numChildren) {
				rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, REQUEST_FAILED,
						"Invalid range for evaluating sub expressions.", null)); //$NON-NLS-1$
				rm.done();
				return;
			}

			int numPart = Math.min(numChildren, length1);
			IndexedPartitionDMC[] children = new IndexedPartitionDMC[numPart];
			int index = partStartIndex;
			for (int i = 0; i < startIndex1; ++i)
				index += computePartitionLength(partLength, i);
			for (int i = 0; i < children.length; ++i) {
				int childPartLength = computePartitionLength(partLength, i + startIndex1);
				children[i] = createIndexedPartition(partDmc.getParentExpressionContext(), index, childPartLength);
				index += childPartLength;
			}
			rm.setData(children);
			rm.done();
		} else {
			// this is the last partition level, create "real" children
			if (startIndex1 > partLength) {
				rm.setData(new IExpressionDMContext[0]);
				rm.done();
			} else {
				getRealSubExpressions(partDmc.getParentExpressionContext(), partStartIndex + startIndex1,
						Math.min(length1, partLength - startIndex1), rm);
			}
		}
	}

	void getRealSubExpressions(final IExpressionDMContext exprCtx, int startIndex, int length,
			final DataRequestMonitor<IExpressionDMContext[]> rm) {

		ExprMetaGetChildren getChildren = (startIndex < 0 || length < 0) ? new ExprMetaGetChildren(exprCtx)
				: new ExprMetaGetChildren(exprCtx, startIndex + length);
		final int startIndex1 = (startIndex < 0) ? 0 : startIndex;
		final int length1 = (length < 0) ? Integer.MAX_VALUE : length;
		fExpressionCache.execute(getChildren, new DataRequestMonitor<ExprMetaGetChildrenInfo>(getExecutor(), rm) {
			@Override
			protected void handleSuccess() {
				ExpressionInfo[] childrenExpr = getData().getChildrenExpressions();

				if (startIndex1 >= childrenExpr.length) {
					rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, REQUEST_FAILED,
							"Invalid range for evaluating sub expressions.", null)); //$NON-NLS-1$
					rm.done();
					return;
				}

				int numChildren = childrenExpr.length - startIndex1;
				numChildren = Math.min(length1, numChildren);
				IExpressionDMContext[] childrenArray = new IExpressionDMContext[numChildren];
				for (int i = 0; i < numChildren; i++) {
					childrenArray[i] = createExpression(exprCtx.getParents()[0], childrenExpr[startIndex1 + i]);
				}
				rm.setData(childrenArray);
				rm.done();
			}
		});
	}

	/**
	 * Returns the number of "real" children if it is less or equal to the partition size,
	 * otherwise returns the number of partitions.
	 */
	private int computeNumberOfChildren(int realNumberOfChildren) {
		int childNum = realNumberOfChildren;
		int partLength = getArrayPartitionLength();
		int maxPartitionLength = 1;
		while (childNum > partLength) {
			childNum /= partLength;
			maxPartitionLength *= partLength;
		}
		if (childNum * maxPartitionLength < realNumberOfChildren)
			++childNum;
		return childNum;
	}

	private int computePartitionLength(int realNumberOfChildren, int index) {
		int childNum = realNumberOfChildren;
		int depth = 0;
		int partLength = getArrayPartitionLength();
		int length = partLength;
		while (childNum > partLength) {
			childNum /= partLength;
			if (depth > 0)
				length *= partLength;
			++depth;
		}
		int diff = realNumberOfChildren - length * index;
		return (diff > length) ? length : diff;
	}

	private IndexedPartitionDMC createIndexedPartition(MIExpressionDMC parentExpr, int index, int length) {
		return new IndexedPartitionDMC(parentExpr, index, length);
	}

	private void getRealSubExpressionCount(IExpressionDMContext dmc, int numChildLimit,
			final DataRequestMonitor<Integer> rm) {
		if (dmc instanceof MIExpressionDMC) {
			fExpressionCache.execute(new ExprMetaGetChildCount(dmc, numChildLimit),
					new DataRequestMonitor<ExprMetaGetChildCountInfo>(getExecutor(), rm) {
						@Override
						protected void handleSuccess() {
							rm.setData(getData().getChildNum());
							rm.done();
						}
					});
		} else if (dmc instanceof InvalidContextExpressionDMC) {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INVALID_HANDLE,
					"Invalid context for evaluating expressions.", null)); //$NON-NLS-1$
			rm.done();
		} else {
			rm.setStatus(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, INTERNAL_ERROR, "Invalid expression context.", //$NON-NLS-1$
					null));
			rm.done();
		}
	}

	private int getArrayPartitionLength() {
		// Replace this in case we or the platform decide to add a user preference.
		// See org.eclipse.debug.internal.ui.model.elements.VariableContentProvider.
		return PARTITION_LENGTH;
	}
}

Back to the top