summaryrefslogtreecommitdiff
path: root/src/debug/daccess/dacimpl.h
blob: aaeeeae9e61d958d878b8ea5c4e954647a35f818 (plain)
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
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//*****************************************************************************
// File: dacimpl.h
// 

//
// Central header file for external data access implementation.
//
//*****************************************************************************


#ifndef __DACIMPL_H__
#define __DACIMPL_H__

#if defined(_TARGET_ARM_) || defined(FEATURE_CORESYSTEM) // @ARMTODO: STL breaks the build with current VC headers
//---------------------------------------------------------------------------------------
// Setting DAC_HASHTABLE tells the DAC to use the hand rolled hashtable for
// storing code:DAC_INSTANCE .  Otherwise, the DAC uses the STL hash_map to.

#define DAC_HASHTABLE
#endif // _TARGET_ARM_|| FEATURE_CORESYSTEM

#ifndef DAC_HASHTABLE
#pragma push_macro("return")
#undef return
#include <hash_map>
#pragma pop_macro("return")
#endif //DAC_HASHTABLE
extern CRITICAL_SECTION g_dacCritSec;

// Convert between CLRDATA_ADDRESS and TADDR.
// Note that CLRDATA_ADDRESS is sign-extended (for compat with Windbg and OS conventions).  Converting
// from pointer-size values to CLRDATA_ADDRESS should ALWAYS use this TO_CDADDR macro to avoid bugs when
// dealing with 3/4GB 32-bit address spaces.  You must not rely on the compiler's implicit conversion
// from ULONG32 to ULONG64 - it is incorrect.  Ideally we'd use some compiler tricks or static analysis
// to help detect such errors (they are nefarious since 3/4GB addresses aren't well tested) .
//
// Note: We're in the process of switching the implementation over to CORDB_ADDRESS instead, which is also 
// 64 bits, but 0-extended.  This means that conversions between TADDR and CORDB_ADDRESS are simple and natural,
// but as long as we have some legacy code, conversions involving CLRDATA_ADDRESS are a pain.  Eventually we
// should eliminate CLRDATA_ADDRESS entirely from the implementation, but that will require moving SOS off of
// the old DAC stuff etc.
// 
// Here are the possible conversions:
// TADDR -> CLRDATA_ADDRESS:         TO_CDADDR
// CORDB_ADDRESS -> CLRDATA_ADDRESS: TO_CDADDR
// CLRDATA_ADDRESS -> TADDR:         CLRDATA_ADDRESS_TO_TADDR
// CORDB_ADDRESS -> TADDR:           CORDB_ADDRESS_TO_TADDR
// TADDR -> CORDB_ADDRESS:           implicit
// CLRDATA_ADDRESS -> CORDB_ADDRESS: CLRDATA_ADDRESS_TO_TADDR
// 
#define TO_CDADDR(taddr) ((CLRDATA_ADDRESS)(LONG_PTR)(taddr))

// Convert a CLRDATA_ADDRESS (64-bit unsigned sign-extended target address) to a TADDR
inline TADDR CLRDATA_ADDRESS_TO_TADDR(CLRDATA_ADDRESS cdAddr)
{
    SUPPORTS_DAC;
#ifndef _WIN64
    static_assert_no_msg(sizeof(TADDR)==sizeof(UINT));
    INT64 iSignedAddr = (INT64)cdAddr;
    if (iSignedAddr > INT_MAX || iSignedAddr < INT_MIN)
    {
        _ASSERTE_MSG(false, "CLRDATA_ADDRESS out of range for this platform");
        DacError(E_INVALIDARG);
    }
#endif
    return (TADDR)cdAddr;
}

// No throw, Convert a CLRDATA_ADDRESS (64-bit unsigned sign-extended target address) to a TADDR
// Use this in places where we know windbg may pass in bad addresses
inline HRESULT TRY_CLRDATA_ADDRESS_TO_TADDR(CLRDATA_ADDRESS cdAddr, TADDR* pOutTaddr)
{
    SUPPORTS_DAC;
#ifndef _WIN64
    static_assert_no_msg(sizeof(TADDR)==sizeof(UINT));
    INT64 iSignedAddr = (INT64)cdAddr;
    if (iSignedAddr > INT_MAX || iSignedAddr < INT_MIN)
    {
        *pOutTaddr = 0;
        return E_INVALIDARG;
    }
#endif
    *pOutTaddr = (TADDR)cdAddr;
    return S_OK;
}

// Convert a CORDB_ADDRESS (64-bit unsigned 0-extended target address) to a TADDR 
inline TADDR CORDB_ADDRESS_TO_TADDR(CORDB_ADDRESS cdbAddr)
{
    SUPPORTS_DAC;
#ifndef _WIN64
    static_assert_no_msg(sizeof(TADDR)==sizeof(UINT));
    if (cdbAddr > UINT_MAX)
    {
        _ASSERTE_MSG(false, "CORDB_ADDRESS out of range for this platform");
        DacError(E_INVALIDARG);
    }
#endif
    return (TADDR)cdbAddr;
}

// TO_TADDR is the old way of converting CLRDATA_ADDRESSes to TADDRs.  Unfortunately,
// this has been used in many places to also cast pointers (void* etc.) to TADDR, and
// so we can't actually require the argument to be a valid CLRDATA_ADDRESS.  New code
// should use CLRDATA_ADDRESS_TO_TADDR instead.
#define TO_TADDR(cdaddr) ((TADDR)(cdaddr))

#define TO_CDENUM(ptr) ((CLRDATA_ENUM)(ULONG_PTR)(ptr))
#define FROM_CDENUM(type, cdenum) ((type*)(ULONG_PTR)(cdenum))

#define SIMPFRAME_ALL \
    (CLRDATA_SIMPFRAME_UNRECOGNIZED | \
     CLRDATA_SIMPFRAME_MANAGED_METHOD | \
     CLRDATA_SIMPFRAME_RUNTIME_MANAGED_CODE | \
     CLRDATA_SIMPFRAME_RUNTIME_UNMANAGED_CODE)

enum DAC_USAGE_TYPE
{
    DAC_DPTR,
    DAC_VPTR,
    DAC_STRA,
    DAC_STRW,
};

// mscordacwks's module handle 
extern HINSTANCE g_thisModule;

class ReflectionModule;

struct DAC_MD_IMPORT
{
    DAC_MD_IMPORT* next;       // list link field
    TADDR peFile;              // a TADDR for a PEFile* or a ReflectionModule*
    IMDInternalImport* impl;   // Associated metadata interface
    bool isAlternate;          // for NGEN images set to true if the metadata corresponds to the IL image

    DAC_MD_IMPORT(TADDR peFile_, 
        IMDInternalImport* impl_, 
        bool isAlt_ = false, 
        DAC_MD_IMPORT* next_ = NULL)
        : next(next_)
        , peFile(peFile_)
        , impl(impl_)
        , isAlternate(isAlt_)
    {
        SUPPORTS_DAC_HOST_ONLY;
    }
};


// This class maintains a cache of IMDInternalImport* and their corresponding
// source (a PEFile* or a ReflectionModule*), as a singly-linked list of 
// DAC_MD_IMPORT nodes.  The cache is flushed whenever the process state changes
// by calling its Flush() member function.
class MDImportsCache
{
public:

    MDImportsCache()
        : m_head(NULL)
    {}

    ~MDImportsCache()
    { 
        Flush(); 
    }

    FORCEINLINE 
    IMDInternalImport* Get(TADDR key) const
    {
        SUPPORTS_DAC;
        for (DAC_MD_IMPORT* importList = m_head; importList; importList = importList->next)
        {
            if (importList->peFile == key)
            {
                return importList->impl;
            }
        }
        return NULL;
    }

    FORCEINLINE 
    DAC_MD_IMPORT* Add(TADDR peFile, IMDInternalImport* impl, bool isAlt)
    {
        SUPPORTS_DAC;
        DAC_MD_IMPORT* importList = new (nothrow) DAC_MD_IMPORT(peFile, impl, isAlt, m_head);
        if (!importList)
        {
            return NULL;
        }

        m_head = importList;
        return importList;
    }

    void Flush()
    {
        DAC_MD_IMPORT* importList;

        while (m_head)
        {
            importList = m_head;
            m_head = importList->next;
            importList->impl->Release();
            delete importList;
        }
    }

private:

    DAC_MD_IMPORT* m_head;  // the beginning of the list of cached MD imports

};

struct METH_EXTENTS
{
    ULONG32 numExtents;
    ULONG32 curExtent;
    // Currently only one is needed.
    CLRDATA_ADDRESS_RANGE extents[1];
};

HRESULT ConvertUtf8(__in LPCUTF8 utf8,
                    ULONG32 bufLen,
                    ULONG32* nameLen,
                    __out_ecount_part_opt(bufLen, *nameLen) PWSTR buffer);
HRESULT AllocUtf8(__in_opt LPCWSTR wstr,
                  ULONG32 srcChars,
                  __deref_out LPUTF8* utf8);

HRESULT GetFullClassNameFromMetadata(IMDInternalImport* mdImport,
                                     mdTypeDef classToken,
                                     ULONG32 bufferChars,
                                     __inout_ecount(bufferChars) LPUTF8 buffer);
HRESULT GetFullMethodNameFromMetadata(IMDInternalImport* mdImport,
                                      mdMethodDef methodToken,
                                      ULONG32 bufferChars,
                                      __inout_ecount(bufferChars) LPUTF8 buffer);

enum SplitSyntax
{
    SPLIT_METHOD,
    SPLIT_TYPE,
    SPLIT_FIELD,
    SPLIT_NO_NAME,
};

HRESULT SplitFullName(__in_z __in PCWSTR fullName,
                      SplitSyntax syntax,
                      ULONG32 memberDots,
                      __deref_out_opt LPUTF8* namespaceName,
                      __deref_out_opt LPUTF8* typeName,
                      __deref_out_opt LPUTF8* memberName,
                      __deref_out_opt LPUTF8* params);

int CompareUtf8(__in LPCUTF8 str1, __in LPCUTF8 str2, __in ULONG32 nameFlags);

#define INH_STATIC \
    (CLRDATA_VALUE_ALL_KINDS | \
     CLRDATA_VALUE_IS_INHERITED | CLRDATA_VALUE_FROM_STATIC)

HRESULT InitFieldIter(DeepFieldDescIterator* fieldIter,
                      TypeHandle typeHandle,
                      bool canHaveFields,
                      ULONG32 flags,
                      IXCLRDataTypeInstance* fromType);

ULONG32 GetTypeFieldValueFlags(TypeHandle typeHandle,
                               FieldDesc* fieldDesc,
                               ULONG32 otherFlags,
                               bool isDeref);

//----------------------------------------------------------------------------
//
// MetaEnum.
//
//----------------------------------------------------------------------------

class MetaEnum
{
public:
    MetaEnum(void)
        : m_domainIter(FALSE)
    {
        Clear();
        m_appDomain = NULL;
    }
    ~MetaEnum(void)
    {
        End();
    }

    void Clear(void)
    {
        m_mdImport = NULL;
        m_kind = 0;
        m_lastToken = mdTokenNil;
    }

    HRESULT Start(IMDInternalImport* mdImport, ULONG32 kind,
                  mdToken container);
    void End(void);

    HRESULT NextToken(mdToken* token,
                      __deref_opt_out_opt LPCUTF8* namespaceName,
                      __deref_opt_out_opt LPCUTF8* name);
    HRESULT NextDomainToken(AppDomain** appDomain,
                            mdToken* token);
    HRESULT NextTokenByName(__in_opt LPCUTF8 namespaceName,
                            __in_opt LPCUTF8 name,
                            ULONG32 nameFlags,
                            mdToken* token);
    HRESULT NextDomainTokenByName(__in_opt LPCUTF8 namespaceName,
                                  __in_opt LPCUTF8 name,
                                  ULONG32 nameFlags,
                                  AppDomain** appDomain, mdToken* token);

    static HRESULT CdNextToken(CLRDATA_ENUM* handle,
                               mdToken* token)
    {
        MetaEnum* iter = FROM_CDENUM(MetaEnum, *handle);
        if (!iter)
        {
            return S_FALSE;
        }

        return iter->NextToken(token, NULL, NULL);
    }
    static HRESULT CdNextDomainToken(CLRDATA_ENUM* handle,
                                     AppDomain** appDomain,
                                     mdToken* token)
    {
        MetaEnum* iter = FROM_CDENUM(MetaEnum, *handle);
        if (!iter)
        {
            return S_FALSE;
        }

        return iter->NextDomainToken(appDomain, token);
    }
    static HRESULT CdEnd(CLRDATA_ENUM handle)
    {
        MetaEnum* iter = FROM_CDENUM(MetaEnum, handle);
        if (iter)
        {
            delete iter;
            return S_OK;
        }
        else
        {
            return E_INVALIDARG;
        }
    }

    IMDInternalImport* m_mdImport;
    ULONG32 m_kind;
    HENUMInternal m_enum;
    AppDomain* m_appDomain;
    AppDomainIterator m_domainIter;
    mdToken m_lastToken;

    static HRESULT New(Module* mod,
                       ULONG32 kind,
                       mdToken container,
                       IXCLRDataAppDomain* pubAppDomain,
                       MetaEnum** metaEnum,
                       CLRDATA_ENUM* handle);
};

//----------------------------------------------------------------------------
//
// SplitName.
//
//----------------------------------------------------------------------------

class SplitName
{
public:
    // Type of name and splitting being done in this instance.
    SplitSyntax m_syntax;
    ULONG32 m_nameFlags;
    ULONG32 m_memberDots;

    // Split fields.
    LPUTF8 m_namespaceName;
    LPUTF8 m_typeName;
    mdTypeDef m_typeToken;
    LPUTF8 m_memberName;
    mdMethodDef m_memberToken;
    LPUTF8 m_params;
    // XXX Microsoft - Translated signature.

    // Arbitrary extra data.
    Thread* m_tlsThread;
    Module* m_module;
    MetaEnum m_metaEnum;
    DeepFieldDescIterator m_fieldEnum;
    ULONG64 m_objBase;
    FieldDesc* m_lastField;

    SplitName(SplitSyntax syntax, ULONG32 nameFlags,
              ULONG32 memberDots);
    ~SplitName(void)
    {
        Delete();
    }

    void Delete(void);
    void Clear(void);

    HRESULT SplitString(__in_opt PCWSTR fullName);

    bool FindType(IMDInternalImport* mdInternal);
    bool FindMethod(IMDInternalImport* mdInternal);
    bool FindField(IMDInternalImport* mdInternal);

    int Compare(LPCUTF8 str1, LPCUTF8 str2)
    {
        return CompareUtf8(str1, str2, m_nameFlags);
    }

    static HRESULT AllocAndSplitString(__in_opt PCWSTR fullName,
                                       SplitSyntax syntax,
                                       ULONG32 nameFlags,
                                       ULONG32 memberDots,
                                       SplitName** split);

    static HRESULT CdStartMethod(__in_opt PCWSTR fullName,
                                 ULONG32 nameFlags,
                                 Module* mod,
                                 mdTypeDef typeToken,
                                 AppDomain* appDomain,
                                 IXCLRDataAppDomain* pubAppDomain,
                                 SplitName** split,
                                 CLRDATA_ENUM* handle);
    static HRESULT CdNextMethod(CLRDATA_ENUM* handle,
                                mdMethodDef* token);
    static HRESULT CdNextDomainMethod(CLRDATA_ENUM* handle,
                                      AppDomain** appDomain,
                                      mdMethodDef* token);

    static HRESULT CdStartField(__in_opt PCWSTR fullName,
                                ULONG32 nameFlags,
                                ULONG32 fieldFlags,
                                IXCLRDataTypeInstance* fromTypeInst,
                                TypeHandle typeHandle,
                                Module* mod,
                                mdTypeDef typeToken,
                                ULONG64 objBase,
                                Thread* tlsThread,
                                IXCLRDataTask* pubTlsThread,
                                AppDomain* appDomain,
                                IXCLRDataAppDomain* pubAppDomain,
                                SplitName** split,
                                CLRDATA_ENUM* handle);
    static HRESULT CdNextField(ClrDataAccess* dac,
                               CLRDATA_ENUM* handle,
                               IXCLRDataTypeDefinition** fieldType,
                               ULONG32* fieldFlags,
                               IXCLRDataValue** value,
                               ULONG32 nameBufRetLen,
                               ULONG32* nameLenRet,
                               __out_ecount_part_opt(nameBufRetLen, *nameLenRet) WCHAR nameBufRet[  ],
                               IXCLRDataModule** tokenScopeRet,
                               mdFieldDef* tokenRet);
    static HRESULT CdNextDomainField(ClrDataAccess* dac,
                                     CLRDATA_ENUM* handle,
                                     IXCLRDataValue** value);

    static HRESULT CdStartType(__in_opt PCWSTR fullName,
                               ULONG32 nameFlags,
                               Module* mod,
                               AppDomain* appDomain,
                               IXCLRDataAppDomain* pubAppDomain,
                               SplitName** split,
                               CLRDATA_ENUM* handle);
    static HRESULT CdNextType(CLRDATA_ENUM* handle,
                              mdTypeDef* token);
    static HRESULT CdNextDomainType(CLRDATA_ENUM* handle,
                                    AppDomain** appDomain,
                                    mdTypeDef* token);

    static HRESULT CdEnd(CLRDATA_ENUM handle)
    {
        SplitName* split = FROM_CDENUM(SplitName, handle);
        if (split)
        {
            delete split;
            return S_OK;
        }
        else
        {
            return E_INVALIDARG;
        }
    }
};

//----------------------------------------------------------------------------
//
// ProcessModIter.
//
//----------------------------------------------------------------------------

struct ProcessModIter
{
    AppDomainIterator m_domainIter;
    bool m_nextDomain;
    AppDomain::AssemblyIterator m_assemIter;
    bool m_iterShared;
#ifdef FEATURE_LOADER_OPTIMIZATION    
    SharedDomain::SharedAssemblyIterator m_sharedIter;
#endif
    Assembly* m_curAssem;
    Assembly::ModuleIterator m_modIter;

    ProcessModIter(void)
        : m_domainIter(FALSE)
    {
        SUPPORTS_DAC;
        m_nextDomain = true;
        m_iterShared = false;
        m_curAssem = NULL;
    }
    
    Assembly * NextAssem()
    {
        SUPPORTS_DAC;
        while (!m_iterShared)
        {
            if (m_nextDomain)
            {
                if (!m_domainIter.Next())
                {
                    m_iterShared = true;
                    break;
                }

                m_nextDomain = false;
                
                m_assemIter = m_domainIter.GetDomain()->IterateAssembliesEx((AssemblyIterationFlags)(
                    kIncludeLoaded | kIncludeExecution));
            }

            CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly;
            if (!m_assemIter.Next(pDomainAssembly.This()))
            {
                m_nextDomain = true;
                continue;
            }
            
            // Note: DAC doesn't need to keep the assembly alive - see code:CollectibleAssemblyHolder#CAH_DAC
            CollectibleAssemblyHolder<Assembly *> pAssembly = pDomainAssembly->GetLoadedAssembly();
            if (!pAssembly->IsDomainNeutral())
            {
                // We've found a domain-specific assembly, so this is a unique element in the Assembly 
                // iteration.
                return pAssembly;
            }

            // Found a shared assembly, which may be duplicated
            // across app domains.  Ignore it now and let
            // it get picked up in the shared iteration where
            // it'll only occur once.
        }
#ifdef FEATURE_LOADER_OPTIMIZATION
        if (!m_sharedIter.Next())
        {
            return NULL;
        }
        return m_sharedIter.GetAssembly();
#else
        return NULL;
#endif
    }

    Module* NextModule(void)
    {
        SUPPORTS_DAC;
        for (;;)
        {
            if (!m_curAssem)
            {
                m_curAssem = NextAssem();
                if (!m_curAssem)
                {
                    return NULL;
                }

                m_modIter = m_curAssem->IterateModules();
            }

            if (!m_modIter.Next())
            {
                m_curAssem = NULL;
                continue;
            }

            return m_modIter.GetModule();
        }
    }
};

//----------------------------------------------------------------------------
//
// DacInstanceManager.
//
//----------------------------------------------------------------------------

// The data for an access may have special alignment needs and
// the cache must provide similar semantics.
#define DAC_INSTANCE_ALIGN 16

#define DAC_INSTANCE_SIG 0xdac1

// The instance manager allocates large blocks and then
// suballocates those for particular instances.
struct DAC_INSTANCE_BLOCK
{
    DAC_INSTANCE_BLOCK* next;
    ULONG32 bytesUsed;
    ULONG32 bytesFree;
};

#define DAC_INSTANCE_BLOCK_ALLOCATION 0x40000

// Sufficient memory is allocated to guarantee storage of the
// instance header plus room for alignment padding.
// Once the aligned pointer is found, this structure is prepended to
// the aligned pointer and therefore doesn't affect the alignment
// of the actual instance data.
struct DAC_INSTANCE
{
    DAC_INSTANCE* next;
    TADDR addr;
    ULONG32 size;
    // Identifying marker to give a simple
    // check for host->taddr validity.
    ULONG32 sig:16;
    // DPTR or VPTR.  See code:DAC_USAGE_TYPE
    ULONG32 usage:2;
    
    // Marker that can be used to prevent reporting this memory to the callback 
    // object (via ICLRDataEnumMemoryRegionsCallback:EnumMemoryRegion)
    // more than once. This bit is checked only by the DacEnumHost?PtrMem
    // macros, so consistent use of those macros ensures that the memory is 
    // reported at most once
    ULONG32 enumMem:1;

    // Marker to prevent metadata gets reported to mini-dump
    ULONG32 noReport:1;
    
    // Marker to determine if EnumMemoryRegions has been called on 
    // a method descriptor
    ULONG32 MDEnumed:1;

#ifdef _WIN64
    // Keep DAC_INSTANCE a multiple of DAC_INSTANCE_ALIGN
    // bytes in size.
    ULONG32 pad[2];
#endif
};

struct DAC_INSTANCE_PUSH
{
    DAC_INSTANCE_PUSH* next;
    DAC_INSTANCE_BLOCK* blocks;
    ULONG64 blockMemUsage;
    ULONG32 numInst;
    ULONG64 instMemUsage;
};
    
// The runtime will want the best access locality possible,
// so it's likely that many instances will be clustered.
// The hash function needs to spread near addresses across
// hash entries, so hash on the low bits of the target address.
// Not all the way down to the LSB, though, as there generally
// won't be individual accesses at the byte level.  Assume that
// most accesses will be natural-word aligned.
#define DAC_INSTANCE_HASH_BITS 10
#define DAC_INSTANCE_HASH_SHIFT 2

#define DAC_INSTANCE_HASH(addr) \
    (((ULONG32)(ULONG_PTR)(addr) >> DAC_INSTANCE_HASH_SHIFT) & \
     ((1 << DAC_INSTANCE_HASH_BITS) - 1))
#define DAC_INSTANCE_HASH_SIZE (1 << DAC_INSTANCE_HASH_BITS)


struct DumpMemoryReportStatics
{
    TSIZE_T    m_cbStack;              // number of bytes that we report directly for stack walk
    TSIZE_T    m_cbNgen;               // number of bytes that we report directly for ngen images
    TSIZE_T    m_cbModuleList;         // number of bytes that we report for module list directly
    TSIZE_T    m_cbClrStatics;         // number of bytes that we report for CLR statics
    TSIZE_T    m_cbClrHeapStatics;     // number of bytes that we report for CLR heap statics
    TSIZE_T    m_cbImplicity;          // number of bytes that we report implicitly
};


class DacInstanceManager
{
public:
    DacInstanceManager(void);
    ~DacInstanceManager(void);

    DAC_INSTANCE* Add(DAC_INSTANCE* inst);

    DAC_INSTANCE* Alloc(TADDR addr, ULONG32 size, DAC_USAGE_TYPE usage);
    void ReturnAlloc(DAC_INSTANCE* inst);
    DAC_INSTANCE* Find(TADDR addr);
    HRESULT Write(DAC_INSTANCE* inst, bool throwEx);
    void Supersede(DAC_INSTANCE* inst);
    void Flush(void);
    void Flush(bool fSaveBlock);
    void ClearEnumMemMarker(void);

    void AddSuperseded(DAC_INSTANCE* inst)
    {
        SUPPORTS_DAC;
        inst->next = m_superseded;
        m_superseded = inst;
    }

    UINT DumpAllInstances(ICLRDataEnumMemoryRegionsCallback *pCallBack);

private:

    DAC_INSTANCE_BLOCK* FindInstanceBlock(DAC_INSTANCE* inst);
    void FreeAllBlocks(bool fSaveBlock);
    
    void InitEmpty(void)
    {
        m_blocks = NULL;
        // m_unusedBlock is not NULLed here; it can contain one block we will use after
        // a flush is complete.
        m_blockMemUsage = 0;
        m_numInst = 0;
        m_instMemUsage = 0;
#ifdef DAC_HASHTABLE
        ZeroMemory(m_hash, sizeof(m_hash));
#endif
        m_superseded = NULL;
        m_instPushed = NULL;
    }

#if defined(DAC_HASHTABLE)

    typedef struct _HashInstanceKey {
        TADDR addr;
        DAC_INSTANCE* instance;
    } HashInstanceKey;

    typedef struct _HashInstanceKeyBlock {
        // Blocks are chained in reverse order of allocation so that the most recently allocated
        // block is searched first.
        _HashInstanceKeyBlock* next;

        // Entries to a block are added from the max index on down so that recently added
        // entries are at the start of the block.
        DWORD firstElement;
        HashInstanceKey instanceKeys[] ;
    } HashInstanceKeyBlock;

// The hashing function does a good job of distributing the entries across buckets. To handle a
// SO on x86, we have under 250 entries in a bucket. A 4K block size allows 511 entries on x86 and
// about half that on x64. On x64, the number of entries added to the hash table is significantly 
// smaller than on x86 (and the max recursion depth for default stack sizes is also far less), so
// 4K is generally adequate.

#define HASH_INSTANCE_BLOCK_ALLOC_SIZE (4 * 1024)
#define HASH_INSTANCE_BLOCK_NUM_ELEMENTS ((HASH_INSTANCE_BLOCK_ALLOC_SIZE - offsetof(_HashInstanceKeyBlock, instanceKeys))/sizeof(HashInstanceKey))
#endif // #if defined(DAC_HASHTABLE)

    DAC_INSTANCE_BLOCK* m_blocks;
    DAC_INSTANCE_BLOCK* m_unusedBlock;
    ULONG64 m_blockMemUsage;
    ULONG32 m_numInst;
    ULONG64 m_instMemUsage;

#if defined(DAC_HASHTABLE)
    HashInstanceKeyBlock* m_hash[DAC_INSTANCE_HASH_SIZE];
#else //DAC_HASHTABLE

    // We're going to use the STL hash_map for our instance hash.  
    // This has the benefit of scaling to different workloads appropriately (as opposed to having a 
    // fixed number of buckets).

    class DacHashCompare : public std::hash_compare<TADDR>       
    {
    public:
        // Custom hash function
        // The default hash function uses a pseudo-randomizing function to get a random 
        // distribution.  In our case, we'd actually like a more even distribution to get
        // better access locality (see comments for DAC_INSTANCE_HASH_BITS).  
        //
        // Also, when enumerating the hash during dump generation, clustering nearby addresses
        // together can have a significant positive impact on the performance of the minidump
        // library (at least the un-optimized version 6.5 linked into our dw20.exe - on Vista+
        // we use the OS's version 6.7+ with radically improved perf characteristics).  Having
        // a random distribution is actually the worst-case because it means most blocks won't
        // be merged until near the end, and a large number of intermediate blocks will have to
        // be searched with each call.
        //
        // The default pseudo-randomizing function also requires a call to ldiv which shows up as
        // a 3%-5% perf hit in most perf-sensitive scenarios, so this should also always be
        // faster.
        inline size_t operator()(const TADDR& keyval) const
        {
            return (unsigned)(keyval >>DAC_INSTANCE_HASH_SHIFT);
        }

        // Explicitly bring in the two-argument comparison function from the base class (just less-than)
        // This is necessary because once we override one form of operator() above, we don't automatically
        // get the others by C++ inheritance rules.
    using std::hash_compare<TADDR>::operator();

#ifdef NIDUMP_CUSTOMIZED_DAC_HASH   // not set
        //this particular number is supposed to be roughly the same amount of
        //memory as the old code (buckets * number of entries in the old
        //blocks.)
        //disabled for now.  May tweak implementation later.  It turns out that
        //having a large number of initial buckets is excellent for nidump, but it 
        // is terrible for most other scenarios due to the cost of clearing them at
        // every Flush.  Once there is a better perf suite, we can tweak these values more.
        static const size_t min_buckets = DAC_INSTANCE_HASH_SIZE * 256;
#endif

    };
    typedef stdext::hash_map<TADDR, DAC_INSTANCE*, DacHashCompare > DacInstanceHash;
    typedef DacInstanceHash::value_type DacInstanceHashValue;
    typedef DacInstanceHash::iterator DacInstanceHashIterator;
    DacInstanceHash m_hash;
#endif //DAC_HASHTABLE

    DAC_INSTANCE* m_superseded;
    DAC_INSTANCE_PUSH* m_instPushed;
};


#ifdef FEATURE_MINIMETADATA_IN_TRIAGEDUMPS

class DacStreamManager;

#endif // FEATURE_MINIMETADATA_IN_TRIAGEDUMPS


//----------------------------------------------------------------------------
//
// ClrDataAccess.
//
//----------------------------------------------------------------------------

class ClrDataAccess
    : public IXCLRDataProcess2,
      public ICLRDataEnumMemoryRegions,
      public ISOSDacInterface,
      public ISOSDacInterface2
{
public:
    ClrDataAccess(ICorDebugDataTarget * pTarget, ICLRDataTarget * pLegacyTarget=0);
    ~ClrDataAccess(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataProcess.
    //

    virtual HRESULT STDMETHODCALLTYPE Flush( void);

    virtual HRESULT STDMETHODCALLTYPE StartEnumTasks(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumTask(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataTask **task);

    virtual HRESULT STDMETHODCALLTYPE EndEnumTasks(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetTaskByOSThreadID(
        /* [in] */ ULONG32 OSThreadID,
        /* [out] */ IXCLRDataTask **task);

    virtual HRESULT STDMETHODCALLTYPE GetTaskByUniqueID(
        /* [in] */ ULONG64 uniqueID,
        /* [out] */ IXCLRDataTask **task);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataProcess *process);

    virtual HRESULT STDMETHODCALLTYPE GetManagedObject(
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE GetDesiredExecutionState(
        /* [out] */ ULONG32 *state);

    virtual HRESULT STDMETHODCALLTYPE SetDesiredExecutionState(
        /* [in] */ ULONG32 state);

    virtual HRESULT STDMETHODCALLTYPE GetAddressType(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [out] */ CLRDataAddressType* type);

    virtual HRESULT STDMETHODCALLTYPE GetRuntimeNameByAddress(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_opt(bufLen) WCHAR nameBuf[  ],
        /* [out] */ CLRDATA_ADDRESS* displacement);

    virtual HRESULT STDMETHODCALLTYPE StartEnumAppDomains(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumAppDomain(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataAppDomain **appDomain);

    virtual HRESULT STDMETHODCALLTYPE EndEnumAppDomains(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetAppDomainByUniqueID(
        /* [in] */ ULONG64 uniqueID,
        /* [out] */ IXCLRDataAppDomain **appDomain);

    virtual HRESULT STDMETHODCALLTYPE StartEnumAssemblies(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumAssembly(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataAssembly **assembly);

    virtual HRESULT STDMETHODCALLTYPE EndEnumAssemblies(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumModules(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumModule(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE EndEnumModules(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetModuleByAddress(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [out] */ IXCLRDataModule** mod);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodDefinitionsByAddress(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodDefinitionByAddress(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodDefinition **method);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodDefinitionsByAddress(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodInstancesByAddress(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodInstanceByAddress(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodInstance **method);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodInstancesByAddress(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetDataByAddress(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [in] */ IXCLRDataTask* tlsTask,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataValue **value,
        /* [out] */ CLRDATA_ADDRESS *displacement);

    virtual HRESULT STDMETHODCALLTYPE GetExceptionStateByExceptionRecord(
        /* [in] */ EXCEPTION_RECORD64 *record,
        /* [out] */ IXCLRDataExceptionState **exception);

    virtual HRESULT STDMETHODCALLTYPE TranslateExceptionRecordToNotification(
        /* [in] */ EXCEPTION_RECORD64 *record,
        /* [in] */ IXCLRDataExceptionNotification *notify);

    virtual HRESULT STDMETHODCALLTYPE CreateMemoryValue(
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [in] */ IXCLRDataTask* tlsTask,
        /* [in] */ IXCLRDataTypeInstance* type,
        /* [in] */ CLRDATA_ADDRESS addr,
        /* [out] */ IXCLRDataValue** value);

    virtual HRESULT STDMETHODCALLTYPE SetAllTypeNotifications(
        /* [in] */ IXCLRDataModule* mod,
        /* [in] */ ULONG32 flags);

    virtual HRESULT STDMETHODCALLTYPE SetAllCodeNotifications(
        /* [in] */ IXCLRDataModule* mod,
        /* [in] */ ULONG32 flags);

    virtual HRESULT STDMETHODCALLTYPE GetTypeNotifications(
        /* [in] */ ULONG32 numTokens,
        /* [in, size_is(numTokens)] */ IXCLRDataModule* mods[],
        /* [in] */ IXCLRDataModule* singleMod,
        /* [in, size_is(numTokens)] */ mdTypeDef tokens[],
        /* [out, size_is(numTokens)] */ ULONG32 flags[]);

    virtual HRESULT STDMETHODCALLTYPE SetTypeNotifications(
        /* [in] */ ULONG32 numTokens,
        /* [in, size_is(numTokens)] */ IXCLRDataModule* mods[],
        /* [in] */ IXCLRDataModule* singleMod,
        /* [in, size_is(numTokens)] */ mdTypeDef tokens[],
        /* [in, size_is(numTokens)] */ ULONG32 flags[],
        /* [in] */ ULONG32 singleFlags);

    virtual HRESULT STDMETHODCALLTYPE GetCodeNotifications(
        /* [in] */ ULONG32 numTokens,
        /* [in, size_is(numTokens)] */ IXCLRDataModule* mods[],
        /* [in] */ IXCLRDataModule* singleMod,
        /* [in, size_is(numTokens)] */ mdMethodDef tokens[],
        /* [out, size_is(numTokens)] */ ULONG32 flags[]);

    virtual HRESULT STDMETHODCALLTYPE SetCodeNotifications(
        /* [in] */ ULONG32 numTokens,
        /* [in, size_is(numTokens)] */ IXCLRDataModule* mods[],
        /* [in] */ IXCLRDataModule* singleMod,
        /* [in, size_is(numTokens)] */ mdMethodDef tokens[],
        /* [in, size_is(numTokens)] */ ULONG32 flags[],
        /* [in] */ ULONG32 singleFlags);

    virtual HRESULT STDMETHODCALLTYPE GetOtherNotificationFlags(
        /* [out] */ ULONG32* flags);

    virtual HRESULT STDMETHODCALLTYPE SetOtherNotificationFlags(
        /* [in] */ ULONG32 flags);

    virtual HRESULT STDMETHODCALLTYPE FollowStub(
        /* [in] */ ULONG32 inFlags,
        /* [in] */ CLRDATA_ADDRESS inAddr,
        /* [in] */ CLRDATA_FOLLOW_STUB_BUFFER* inBuffer,
        /* [out] */ CLRDATA_ADDRESS* outAddr,
        /* [out] */ CLRDATA_FOLLOW_STUB_BUFFER* outBuffer,
        /* [out] */ ULONG32* outFlags);

    virtual HRESULT STDMETHODCALLTYPE FollowStub2(
        /* [in] */ IXCLRDataTask* task,
        /* [in] */ ULONG32 inFlags,
        /* [in] */ CLRDATA_ADDRESS inAddr,
        /* [in] */ CLRDATA_FOLLOW_STUB_BUFFER* inBuffer,
        /* [out] */ CLRDATA_ADDRESS* outAddr,
        /* [out] */ CLRDATA_FOLLOW_STUB_BUFFER* outBuffer,
        /* [out] */ ULONG32* outFlags);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);


    //
    // IXCLRDataProcess2.
    //
    STDMETHOD(GetGcNotification)(/* [out] */ GcEvtArgs* gcEvtArgs);
    STDMETHOD(SetGcNotification)(/* [in] */ GcEvtArgs gcEvtArgs);

    //
    // ICLRDataEnumMemoryRegions.
    //
    virtual HRESULT STDMETHODCALLTYPE EnumMemoryRegions(
        /* [in] */ ICLRDataEnumMemoryRegionsCallback *callback,
        /* [in] */ ULONG32 miniDumpFlags,
        /* [in] */ CLRDataEnumMemoryFlags clrFlags);


    // ISOSDacInterface
    virtual HRESULT STDMETHODCALLTYPE GetThreadStoreData(struct DacpThreadStoreData *data);
    virtual HRESULT STDMETHODCALLTYPE GetAppDomainStoreData(struct DacpAppDomainStoreData *data);
    virtual HRESULT STDMETHODCALLTYPE GetAppDomainList(unsigned int count, CLRDATA_ADDRESS values[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetAppDomainData(CLRDATA_ADDRESS addr, struct DacpAppDomainData *data);
    virtual HRESULT STDMETHODCALLTYPE GetAppDomainName(CLRDATA_ADDRESS addr, unsigned int count, __out_z __inout_ecount(count) wchar_t *name, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetAssemblyList(CLRDATA_ADDRESS appDomain, int count, CLRDATA_ADDRESS values[], int *fetched);
    virtual HRESULT STDMETHODCALLTYPE GetAssemblyData(CLRDATA_ADDRESS baseDomainPtr, CLRDATA_ADDRESS assembly, struct DacpAssemblyData *data);
    virtual HRESULT STDMETHODCALLTYPE GetAssemblyName(CLRDATA_ADDRESS assembly, unsigned int count, __out_z __inout_ecount(count) wchar_t *name, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetThreadData(CLRDATA_ADDRESS thread, struct DacpThreadData *data);
    virtual HRESULT STDMETHODCALLTYPE GetThreadFromThinlockID(UINT thinLockId, CLRDATA_ADDRESS *pThread);
    virtual HRESULT STDMETHODCALLTYPE GetStackLimits(CLRDATA_ADDRESS threadPtr, CLRDATA_ADDRESS *lower, CLRDATA_ADDRESS *upper, CLRDATA_ADDRESS *fp);
    virtual HRESULT STDMETHODCALLTYPE GetDomainFromContext(CLRDATA_ADDRESS context, CLRDATA_ADDRESS *domain);

    virtual HRESULT STDMETHODCALLTYPE GetMethodDescData(CLRDATA_ADDRESS methodDesc, CLRDATA_ADDRESS ip, struct DacpMethodDescData *data, ULONG cRevertedRejitVersions, DacpReJitData * rgRevertedRejitData, ULONG * pcNeededRevertedRejitData);
    virtual HRESULT STDMETHODCALLTYPE GetMethodDescPtrFromIP(CLRDATA_ADDRESS ip, CLRDATA_ADDRESS * ppMD);
    virtual HRESULT STDMETHODCALLTYPE GetMethodDescName(CLRDATA_ADDRESS methodDesc, unsigned int count, __out_z __inout_ecount(count) wchar_t *name, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetMethodDescPtrFromFrame(CLRDATA_ADDRESS frameAddr, CLRDATA_ADDRESS * ppMD);
    virtual HRESULT STDMETHODCALLTYPE GetCodeHeaderData(CLRDATA_ADDRESS ip, struct DacpCodeHeaderData *data);
    virtual HRESULT STDMETHODCALLTYPE GetThreadpoolData(struct DacpThreadpoolData *data);
    virtual HRESULT STDMETHODCALLTYPE GetWorkRequestData(CLRDATA_ADDRESS addrWorkRequest, struct DacpWorkRequestData *data);
    virtual HRESULT STDMETHODCALLTYPE GetObjectData(CLRDATA_ADDRESS objAddr, struct DacpObjectData *data);
    virtual HRESULT STDMETHODCALLTYPE GetObjectStringData(CLRDATA_ADDRESS obj, unsigned int count, __out_z __inout_ecount(count) wchar_t *stringData, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetObjectClassName(CLRDATA_ADDRESS obj, unsigned int count, __out_z __inout_ecount(count) wchar_t *className, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetMethodTableName(CLRDATA_ADDRESS mt, unsigned int count, __out_z __inout_ecount(count) wchar_t *mtName, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetMethodTableData(CLRDATA_ADDRESS mt, struct DacpMethodTableData *data);
    virtual HRESULT STDMETHODCALLTYPE GetMethodTableFieldData(CLRDATA_ADDRESS mt, struct DacpMethodTableFieldData *data);
    virtual HRESULT STDMETHODCALLTYPE GetMethodTableTransparencyData(CLRDATA_ADDRESS mt, struct DacpMethodTableTransparencyData *data);
    virtual HRESULT STDMETHODCALLTYPE GetMethodTableForEEClass(CLRDATA_ADDRESS eeClass, CLRDATA_ADDRESS *value);
    virtual HRESULT STDMETHODCALLTYPE GetFieldDescData(CLRDATA_ADDRESS fieldDesc, struct DacpFieldDescData *data);
    virtual HRESULT STDMETHODCALLTYPE GetFrameName(CLRDATA_ADDRESS vtable, unsigned int count, __out_z __inout_ecount(count) wchar_t *frameName, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetModule(CLRDATA_ADDRESS addr, IXCLRDataModule **mod);
    virtual HRESULT STDMETHODCALLTYPE GetModuleData(CLRDATA_ADDRESS moduleAddr, struct DacpModuleData *data);
    virtual HRESULT STDMETHODCALLTYPE TraverseModuleMap(ModuleMapType mmt, CLRDATA_ADDRESS moduleAddr, MODULEMAPTRAVERSE pCallback, LPVOID token);
    virtual HRESULT STDMETHODCALLTYPE GetMethodDescFromToken(CLRDATA_ADDRESS moduleAddr, mdToken token, CLRDATA_ADDRESS *methodDesc);
    virtual HRESULT STDMETHODCALLTYPE GetPEFileBase(CLRDATA_ADDRESS addr, CLRDATA_ADDRESS *base);
    virtual HRESULT STDMETHODCALLTYPE GetPEFileName(CLRDATA_ADDRESS addr, unsigned int count, __out_z __inout_ecount(count) wchar_t *fileName, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetAssemblyModuleList(CLRDATA_ADDRESS assembly, unsigned int count, CLRDATA_ADDRESS modules[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetGCHeapData(struct DacpGcHeapData *data);
    virtual HRESULT STDMETHODCALLTYPE GetGCHeapList(unsigned int count, CLRDATA_ADDRESS heaps[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetGCHeapDetails(CLRDATA_ADDRESS heap, struct DacpGcHeapDetails *details);
    virtual HRESULT STDMETHODCALLTYPE GetGCHeapStaticData(struct DacpGcHeapDetails *data);
    virtual HRESULT STDMETHODCALLTYPE GetHeapSegmentData(CLRDATA_ADDRESS seg, struct DacpHeapSegmentData *data);
    virtual HRESULT STDMETHODCALLTYPE GetDomainLocalModuleData(CLRDATA_ADDRESS addr, struct DacpDomainLocalModuleData *data);
    virtual HRESULT STDMETHODCALLTYPE GetDomainLocalModuleDataFromAppDomain(CLRDATA_ADDRESS appDomainAddr, int moduleID, struct DacpDomainLocalModuleData *data);
    virtual HRESULT STDMETHODCALLTYPE GetDomainLocalModuleDataFromModule(CLRDATA_ADDRESS moduleAddr, struct DacpDomainLocalModuleData *data);
    virtual HRESULT STDMETHODCALLTYPE GetSyncBlockData(unsigned int number, struct DacpSyncBlockData *data);
    virtual HRESULT STDMETHODCALLTYPE GetSyncBlockCleanupData(CLRDATA_ADDRESS addr, struct DacpSyncBlockCleanupData *data);
    virtual HRESULT STDMETHODCALLTYPE TraverseRCWCleanupList(CLRDATA_ADDRESS cleanupListPtr, VISITRCWFORCLEANUP pCallback, LPVOID token);
    virtual HRESULT STDMETHODCALLTYPE TraverseEHInfo(CLRDATA_ADDRESS ip, DUMPEHINFO pCallback, LPVOID token);
    virtual HRESULT STDMETHODCALLTYPE GetStressLogAddress(CLRDATA_ADDRESS *stressLog);
    virtual HRESULT STDMETHODCALLTYPE GetJitManagerList(unsigned int count, struct DacpJitManagerInfo managers[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetJitHelperFunctionName(CLRDATA_ADDRESS ip, unsigned int count, __out_z __inout_ecount(count) char *name, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetJumpThunkTarget(T_CONTEXT *ctx, CLRDATA_ADDRESS *targetIP, CLRDATA_ADDRESS *targetMD);
    virtual HRESULT STDMETHODCALLTYPE TraverseLoaderHeap(CLRDATA_ADDRESS loaderHeapAddr, VISITHEAP pCallback);
    virtual HRESULT STDMETHODCALLTYPE GetCodeHeapList(CLRDATA_ADDRESS jitManager, unsigned int count, struct DacpJitCodeHeapInfo codeHeaps[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetMethodTableSlot(CLRDATA_ADDRESS mt, unsigned int slot, CLRDATA_ADDRESS *value);
    virtual HRESULT STDMETHODCALLTYPE TraverseVirtCallStubHeap(CLRDATA_ADDRESS pAppDomain, VCSHeapType heaptype, VISITHEAP pCallback);
    virtual HRESULT STDMETHODCALLTYPE GetNestedExceptionData(CLRDATA_ADDRESS exception, CLRDATA_ADDRESS *exceptionObject, CLRDATA_ADDRESS *nextNestedException);
    virtual HRESULT STDMETHODCALLTYPE GetUsefulGlobals(struct DacpUsefulGlobalsData *data);
    virtual HRESULT STDMETHODCALLTYPE GetILForModule(CLRDATA_ADDRESS moduleAddr, DWORD rva, CLRDATA_ADDRESS *il);
    virtual HRESULT STDMETHODCALLTYPE GetClrWatsonBuckets(CLRDATA_ADDRESS thread, void *pGenericModeBlock);
    virtual HRESULT STDMETHODCALLTYPE GetOOMData(CLRDATA_ADDRESS oomAddr, struct DacpOomData *data);
    virtual HRESULT STDMETHODCALLTYPE GetOOMStaticData(struct DacpOomData *data);
    virtual HRESULT STDMETHODCALLTYPE GetHeapAnalyzeData(CLRDATA_ADDRESS addr,struct  DacpGcHeapAnalyzeData *data);
    virtual HRESULT STDMETHODCALLTYPE GetHeapAnalyzeStaticData(struct DacpGcHeapAnalyzeData *data);
    virtual HRESULT STDMETHODCALLTYPE GetMethodDescTransparencyData(CLRDATA_ADDRESS methodDesc, struct DacpMethodDescTransparencyData *data);
    virtual HRESULT STDMETHODCALLTYPE GetHillClimbingLogEntry(CLRDATA_ADDRESS addr, struct DacpHillClimbingLogEntry *data);
    virtual HRESULT STDMETHODCALLTYPE GetThreadLocalModuleData(CLRDATA_ADDRESS thread, unsigned int index, struct DacpThreadLocalModuleData *data);
    virtual HRESULT STDMETHODCALLTYPE GetRCWData(CLRDATA_ADDRESS addr, struct DacpRCWData *data);
    virtual HRESULT STDMETHODCALLTYPE GetRCWInterfaces(CLRDATA_ADDRESS rcw, unsigned int count, struct DacpCOMInterfacePointerData interfaces[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetCCWData(CLRDATA_ADDRESS ccw, struct DacpCCWData *data);
    virtual HRESULT STDMETHODCALLTYPE GetCCWInterfaces(CLRDATA_ADDRESS ccw, unsigned int count, struct DacpCOMInterfacePointerData interfaces[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetTLSIndex(ULONG *pIndex);
    virtual HRESULT STDMETHODCALLTYPE GetDacModuleHandle(HMODULE *phModule);
    
    virtual HRESULT STDMETHODCALLTYPE GetFailedAssemblyList(CLRDATA_ADDRESS appDomain, int count, CLRDATA_ADDRESS values[], unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetPrivateBinPaths(CLRDATA_ADDRESS appDomain, int count, __out_z __inout_ecount(count) wchar_t *paths, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetAssemblyLocation(CLRDATA_ADDRESS assembly, int count, __out_z __inout_ecount(count) wchar_t *location, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetAppDomainConfigFile(CLRDATA_ADDRESS appDomain, int count, __out_z __inout_ecount(count) wchar_t *configFile, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetApplicationBase(CLRDATA_ADDRESS appDomain, int count, __out_z __inout_ecount(count) wchar_t *base, unsigned int *pNeeded);
    
    virtual HRESULT STDMETHODCALLTYPE GetFailedAssemblyData(CLRDATA_ADDRESS assembly, unsigned int *pContext, HRESULT *pResult);
    virtual HRESULT STDMETHODCALLTYPE GetFailedAssemblyLocation(CLRDATA_ADDRESS assembly, unsigned int count, __out_z __inout_ecount(count) wchar_t *location, unsigned int *pNeeded);
    virtual HRESULT STDMETHODCALLTYPE GetFailedAssemblyDisplayName(CLRDATA_ADDRESS assembly, unsigned int count, __out_z __inout_ecount(count) wchar_t *name, unsigned int *pNeeded);
    
    virtual HRESULT STDMETHODCALLTYPE GetStackReferences(DWORD osThreadID, ISOSStackRefEnum **ppEnum);
    virtual HRESULT STDMETHODCALLTYPE GetRegisterName(int regNum, unsigned int count, __out_z __inout_ecount(count) wchar_t *buffer, unsigned int *pNeeded);
    
    virtual HRESULT STDMETHODCALLTYPE GetHandleEnum(ISOSHandleEnum **ppHandleEnum);
    virtual HRESULT STDMETHODCALLTYPE GetHandleEnumForTypes(unsigned int types[], unsigned int count, ISOSHandleEnum **ppHandleEnum);
    virtual HRESULT STDMETHODCALLTYPE GetHandleEnumForGC(unsigned int gen, ISOSHandleEnum **ppHandleEnum);
    
    virtual HRESULT STDMETHODCALLTYPE GetThreadAllocData(CLRDATA_ADDRESS thread, struct DacpAllocData *data);
    virtual HRESULT STDMETHODCALLTYPE GetHeapAllocData(unsigned int count, struct DacpGenerationAllocData *data, unsigned int *pNeeded);

    // ISOSDacInterface2
    virtual HRESULT STDMETHODCALLTYPE GetObjectExceptionData(CLRDATA_ADDRESS objAddr, struct DacpExceptionObjectData *data);
    virtual HRESULT STDMETHODCALLTYPE IsRCWDCOMProxy(CLRDATA_ADDRESS rcwAddr, BOOL* isDCOMProxy);

    //
    // ClrDataAccess.
    //

    HRESULT Initialize(void);

    BOOL IsExceptionFromManagedCode(EXCEPTION_RECORD * pExceptionRecord);
#ifndef FEATURE_PAL
    HRESULT GetWatsonBuckets(DWORD dwThreadId, GenericModeBlock * pGM);
#endif // FEATURE_PAL


    Thread* FindClrThreadByTaskId(ULONG64 taskId);
    HRESULT IsPossibleCodeAddress(IN TADDR address);

    PCSTR GetJitHelperName(IN TADDR address,
                           IN bool dynamicHelpersOnly = false);
    HRESULT GetFullMethodName(IN MethodDesc* methodDesc,
                              IN ULONG32 symbolChars,
                              IN ULONG32* symbolLen,
                              __out_ecount_part_opt(symbolChars, *symbolLen) LPWSTR symbol);
    HRESULT RawGetMethodName(/* [in] */ CLRDATA_ADDRESS address,
                             /* [in] */ ULONG32 flags,
                             /* [in] */ ULONG32 bufLen,
                             /* [out] */ ULONG32 *nameLen,
                             /* [size_is][out] */ __out_ecount_opt(bufLen) WCHAR nameBuf[  ],
                             /* [out] */ CLRDATA_ADDRESS* displacement);

    HRESULT FollowStubStep(
        /* [in] */ Thread* thread,
        /* [in] */ ULONG32 inFlags,
        /* [in] */ TADDR inAddr,
        /* [in] */ union STUB_BUF* inBuffer,
        /* [out] */ TADDR* outAddr,
        /* [out] */ union STUB_BUF* outBuffer,
        /* [out] */ ULONG32* outFlags);

    DebuggerJitInfo* GetDebuggerJitInfo(MethodDesc* methodDesc,
                                        TADDR addr)
    {
        if (g_pDebugger)
        {
            return g_pDebugger->GetJitInfo(methodDesc, (PBYTE)addr, NULL);
        }

        return NULL;
    }

    HRESULT GetMethodExtents(MethodDesc* methodDesc,
                             METH_EXTENTS** extents);
    HRESULT GetMethodVarInfo(MethodDesc* methodDesc,
                             TADDR address,
                             ULONG32* numVarInfo,
                             ICorDebugInfo::NativeVarInfo** varInfo,
                             ULONG32* codeOffset);

    // If the method has multiple copies of code (because of EnC or code-pitching),
    // this returns the info corresponding to address.
    // If 'address' and 'codeOffset' are both non-NULL, *codeOffset gets set to
    // the offset of 'address' from the start of the method.
    HRESULT GetMethodNativeMap(MethodDesc* methodDesc,
                               TADDR address,
                               ULONG32* numMap,
                               DebuggerILToNativeMap** map,
                               bool* mapAllocated,
                               CLRDATA_ADDRESS* codeStart,
                               ULONG32* codeOffset);

    // Get the MethodDesc for a function
    MethodDesc * FindLoadedMethodRefOrDef(Module* pModule, mdToken memberRef);
    
#ifndef FEATURE_PAL
    HRESULT GetClrWatsonBucketsWorker(Thread * pThread, GenericModeBlock * pGM);
#endif // FEATURE_PAL

    HRESULT ServerGCHeapDetails(CLRDATA_ADDRESS heapAddr,
                                DacpGcHeapDetails *detailsData);
    HRESULT GetServerAllocData(unsigned int count, struct DacpGenerationAllocData *data, unsigned int *pNeeded);
    HRESULT ServerOomData(CLRDATA_ADDRESS addr, DacpOomData *oomData);
    HRESULT ServerGCHeapAnalyzeData(CLRDATA_ADDRESS heapAddr, 
                                DacpGcHeapAnalyzeData *analyzeData);

    //
    // Memory enumeration.
    //

    HRESULT EnumMemoryRegionsWrapper(CLRDataEnumMemoryFlags flags);

    // skinny minidump functions
    HRESULT EnumMemoryRegionsWorkerSkinny(CLRDataEnumMemoryFlags flags);
    // triage minidump functions
    HRESULT EnumMemoryRegionsWorkerMicroTriage(CLRDataEnumMemoryFlags flags);
    HRESULT EnumMemoryRegionsWorkerHeap(CLRDataEnumMemoryFlags flags);
    
    HRESULT EnumMemWalkStackHelper(CLRDataEnumMemoryFlags flags, IXCLRDataStackWalk  *pStackWalk, Thread * pThread);
    HRESULT DumpManagedObject(CLRDataEnumMemoryFlags flags, OBJECTREF objRef);
    HRESULT DumpManagedExcepObject(CLRDataEnumMemoryFlags flags, OBJECTREF objRef);
    HRESULT DumpManagedStackTraceStringObject(CLRDataEnumMemoryFlags flags, STRINGREF orefStackTrace);
#ifdef FEATURE_COMINTEROP
    HRESULT DumpStowedExceptionObject(CLRDataEnumMemoryFlags flags, CLRDATA_ADDRESS ccwPtr);
    HRESULT EnumMemStowedException(CLRDataEnumMemoryFlags flags);
#endif

    HRESULT EnumMemWriteDataSegment();
    
    // Custom Dump    
    HRESULT EnumMemoryRegionsWorkerCustom();

    // helper function for dump code
    void EnumWksGlobalMemoryRegions(CLRDataEnumMemoryFlags flags);
    void EnumSvrGlobalMemoryRegions(CLRDataEnumMemoryFlags flags);

    HRESULT EnumMemCollectImages();
    HRESULT EnumMemCLRStatic(CLRDataEnumMemoryFlags flags);
    HRESULT EnumMemCLRHeapCrticalStatic(CLRDataEnumMemoryFlags flags);
    HRESULT EnumMemDumpModuleList(CLRDataEnumMemoryFlags flags);
    HRESULT EnumMemDumpAppDomainInfo(CLRDataEnumMemoryFlags flags);
    HRESULT EnumMemDumpAllThreadsStack(CLRDataEnumMemoryFlags flags);
    HRESULT EnumMemCLRMainModuleInfo();

    bool ReportMem(TADDR addr, TSIZE_T size, bool fExpectSuccess = true);
    bool DacUpdateMemoryRegion(TADDR addr, TSIZE_T bufferSize, BYTE* buffer);

    void ClearDumpStats();
    JITNotification* GetHostJitNotificationTable();
    GcNotification*  GetHostGcNotificationTable();

    void* GetMetaDataFromHost(PEFile* peFile,
                              bool* isAlternate);

    virtual
    interface IMDInternalImport* GetMDImport(const PEFile* peFile, 
                                             const ReflectionModule* reflectionModule,
                                             bool throwEx);

    interface IMDInternalImport* GetMDImport(const PEFile* peFile,
                                             bool throwEx)
    {
        return GetMDImport(peFile, NULL, throwEx);
    }

    interface IMDInternalImport* GetMDImport(const ReflectionModule* reflectionModule,
                                             bool throwEx)
    {
        return GetMDImport(NULL, reflectionModule, throwEx);
    }

    //ClrDump support
    HRESULT STDMETHODCALLTYPE DumpNativeImage(CLRDATA_ADDRESS loadedBase,
                                              LPCWSTR name,
                                              IXCLRDataDisplay *display,
                                              IXCLRLibrarySupport *support,
                                              IXCLRDisassemblySupport *dis);

    // Set whether inconsistencies in the target should raise asserts.
    void SetTargetConsistencyChecks(bool fEnableAsserts);

    // Get whether inconsistencies in the target should raise asserts.
    bool TargetConsistencyAssertsEnabled();

    // Get the ICLRDataTarget2 instance, if any
    ICLRDataTarget2 * GetLegacyTarget2()        { return m_pLegacyTarget2; }

    // Get the ICLRDataTarget3 instance, if any
    ICLRDataTarget3 * GetLegacyTarget3()        { return m_pLegacyTarget3; }

    // 
    // Public Fields
    // Note that it would be nice if all of these were made private.  However, the visibility
    // model of the DAC implementation is that the public surface area is declared in daccess.h
    // (implemented in dacfn.cpp), and the private surface area (like ClrDataAccess) is declared
    // in dacimpl.h which is only included by the DAC infrastructure.  Therefore the DAC 
    // infrastructure agressively uses these fields, and we don't get a huge amount of benefit from
    // reworking this model (since there is some form of encapsulation in place already).
    // 

    // The underlying data target - always present (strong reference)
    ICorDebugDataTarget * m_pTarget;

    // Mutable version of the data target if any - optional (strong reference)
    ICorDebugMutableDataTarget * m_pMutableTarget;

    TADDR m_globalBase;
    DacInstanceManager m_instances;
    ULONG32 m_instanceAge;
    bool m_debugMode;

#ifdef FEATURE_MINIMETADATA_IN_TRIAGEDUMPS

protected:
    DacStreamManager * m_streams;

public:
    // Used to mark the point after which enumerated EE structs of interest
    // will get their names cached in the triage/mini-dump
    void InitStreamsForWriting(IN CLRDataEnumMemoryFlags flags);

    // Used during triage/mini-dump collection to populate the map of
    // pointers to EE struct (MethodDesc* for now) to their corresponding 
    // name.
    bool MdCacheAddEEName(TADDR taEEStruct, const SString& name);

    // Used to mark the end point for the name caching. Will update streams 
    // based on built caches
    void EnumStreams(IN CLRDataEnumMemoryFlags flags);

    // Used during triage/mini-dump analysis to retrieve the name associated
    // with an EE struct pointer (MethodDesc* for now).
    bool MdCacheGetEEName(TADDR taEEStruct, SString & eeName);

#endif // FEATURE_MINIMETADATA_IN_TRIAGEDUMPS

private:
    // Read the DAC table and initialize g_dacGlobals
    HRESULT GetDacGlobals();

    // Verify the target mscorwks.dll matches the version expected
    HRESULT VerifyDlls();

    // Check whether a region of memory is fully readable.
    bool IsFullyReadable(TADDR addr, TSIZE_T size);

    // Legacy target interfaces - optional
    ICLRDataTarget * m_pLegacyTarget;
    ICLRDataTarget2 * m_pLegacyTarget2;
    ICLRDataTarget3 * m_pLegacyTarget3;
    IXCLRDataTarget3 * m_target3;
    ICLRMetadataLocator * m_legacyMetaDataLocator;

    LONG m_refs;
    HRESULT m_memStatus;
    MDImportsCache m_mdImports;
    ICLRDataEnumMemoryRegionsCallback* m_enumMemCb;
    ICLRDataEnumMemoryRegionsCallback2* m_updateMemCb;
    CLRDataEnumMemoryFlags m_enumMemFlags;
    JITNotification* m_jitNotificationTable;
    GcNotification*  m_gcNotificationTable;
    TSIZE_T m_cbMemoryReported;
    DumpMemoryReportStatics m_dumpStats;

    // If true, inconsistencies in the target will cause ASSERTs to be raised in DEBUG builds
    bool m_fEnableTargetConsistencyAsserts;

#ifdef _DEBUG
protected:
    // If true, a mscorwks/mscordacwks mismatch will trigger a nice assert dialog
    bool m_fEnableDllVerificationAsserts;
private:
#endif

#ifdef FEATURE_COMINTEROP
protected:
    // Returns CCW pointer based on a target address.
    PTR_ComCallWrapper DACGetCCWFromAddress(CLRDATA_ADDRESS addr);

private:
    // Returns COM interface pointer corresponding to a given CCW and internal vtable
    // index. Returns NULL if the vtable is unused or not fully laid out.
    PTR_IUnknown DACGetCOMIPFromCCW(PTR_ComCallWrapper pCCW, int vtableIndex);
#endif

    static LONG s_procInit;

public:
    // APIs for picking up the info needed for a debugger to look up an ngen image or IL image
    // from it's search path.
    static bool GetMetaDataFileInfoFromPEFile(PEFile *pPEFile,
                                              DWORD &dwImageTimestamp,
                                              DWORD &dwImageSize,
                                              DWORD &dwDataSize,
                                              DWORD &dwRvaHint,
                                              bool  &isNGEN,
                                              __out_ecount(cchFilePath) LPWSTR wszFilePath,
                                              DWORD cchFilePath);

    static bool GetILImageInfoFromNgenPEFile(PEFile *peFile,
                                             DWORD &dwTimeStamp,
                                             DWORD &dwSize,
                                             __out_ecount(cchPath) LPWSTR wszPath,
                                             const DWORD cchPath);
#if defined(FEATURE_CORESYSTEM)
    static bool ClrDataAccess::GetILImageNameFromNgenImage(LPCWSTR ilExtension,
                                                 __out_ecount(cchFilePath) LPWSTR wszFilePath,
                                                 const DWORD cchFilePath);
#endif // FEATURE_CORESYSTEM
};

extern ClrDataAccess* g_dacImpl;

/*     DacHandleWalker.
 *
 * Iterates over the handle table, enumerating all handles of the requested type on the
 * handle table.  This also will report the handle type, whether the handle is a strong
 * reference, the AppDomain the handle comes from, as well as the reference count (in
 * the case of a RefCount handle).  Optionally this class can also be used to filter
 * based on GC generation that would be collected (that is, to emulate a GC scan of the
 * handle table).
 *
 *     General implementation details:
 * We have four sets of variables:
 * 1.  Overhead variables needed to operate in the Dac.
 * 2.  Variables needed to walk the handle table.  We walk the handle table one bucket
 *     at a time, filling the array the user gave us until we have either enumerated
 *     all handles, or filled the array.
 * 3.  Storage variables to hold the overflow.  That is, we were walking the handle
 *     table, filled the array that the user gave us, then needed to store the extra
 *     handles the handle table continued to enumerate to us.  This is implmeneted
 *     as a linked list of arrays (mHead, mHead.Next, etc).
 * 4.  Variables which store the location of where we are in the overflow data.
 *
 * Note that "mHead" is a HandleChunkHead where we stuff the user's array.  Everything
 * which follows mHead (mHead.Next, etc) is a HandleChunk containing overflow data.
 *
 * Lastly, note this does not do robust error handling.  If we fail to allocate a
 * HandleChunk while walking the handle table, we will miss handles and not report
 * this to the user.  Unfortunately this will have to be fixed in the next iteration
 * when we add more robust error handling to SOS's interface.
 */
 template <class T>
class DefaultCOMImpl : public T
{
public:
    DefaultCOMImpl()
        : mRef(0)
    {
    }
    
    ULONG STDMETHODCALLTYPE AddRef()
    {
        return ++mRef;
    }
    
    ULONG STDMETHODCALLTYPE Release()
    {
        ULONG res = mRef--;
        if (res == 0)
            delete this;
        return res;
    }
    
    HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppObj)
    {
        if (ppObj == NULL)
            return E_INVALIDARG;
        
        if (IsEqualIID(riid, IID_IUnknown))
        {
            AddRef();
            *ppObj = static_cast<IUnknown*>(this);
            return S_OK;
        }
        else if (IsEqualIID(riid, __uuidof(T)))
        {
            AddRef();
            *ppObj = static_cast<T*>(this);
            return S_OK;
        }

        *ppObj = NULL;
        return E_NOINTERFACE;
    }

private:
    ULONG mRef;
};


// A stuct representing a thread's allocation context.
struct AllocInfo
{
    CORDB_ADDRESS Ptr;
    CORDB_ADDRESS Limit;

    AllocInfo()
        : Ptr(0), Limit(0)
    {
    }
};

// A struct representing a segment in the heap.
struct SegmentData
{
    CORDB_ADDRESS Start;
    CORDB_ADDRESS End;

    // Whether this segment is part of the large object heap.
    int Generation;

    SegmentData()
        : Start(0), End(0), Generation(0)
    {
    }
};

// A struct representing a gc heap in the process.
struct HeapData
{
    CORDB_ADDRESS YoungestGenPtr;
    CORDB_ADDRESS YoungestGenLimit;

    CORDB_ADDRESS Gen0Start;
    CORDB_ADDRESS Gen0End;
    
    CORDB_ADDRESS Gen1Start;
    size_t EphemeralSegment;

    size_t SegmentCount;
    SegmentData *Segments;

    HeapData();
    ~HeapData();
};

/* This cache is used to read data from the target process if the reads are known
 * to be sequential.  This will object will read one page of memory out of the
 * process at a time, aligned to the page boundary, to 
 */
class LinearReadCache
{
public:
    LinearReadCache();
    ~LinearReadCache();

    /* Reads an address out of the target process, caching the page of memory read.
     * Params:
     *   addr - The address to read out of the target process.
     *   t - A pointer to the data to stuff it in.  We will read sizeof(T) data
     *       from the process and write it into the location t points to.  This
     *       parameter must be non-null.
     * Returns:
     *   True if the read succeeded.  False if it did not, usually as a result
     *   of the memory simply not being present in the target process.
     * Note:
     *   The state of *t is undefined if this function returns false.  We may
     *   have written partial data to it if we return false, so you must
     *   absolutely NOT use it if Read returns false.
     */
    template <class T>
    bool Read(CORDB_ADDRESS addr, T *t)
    {
        _ASSERTE(t);

        // Unfortunately the ctor can fail the alloc for the byte array.  In this case
        // we'll just fall back to non-cached reads.
        if (mPage == NULL)
            return MisalignedRead(addr, t);

        // Is addr on the current page?  If not read the page of memory addr is on.
        // If this fails, we will fall back to a raw read out of the process (which
        // is what MisalignedRead does).
        if ((addr < mCurrPageStart) || (addr - mCurrPageStart > mCurrPageSize))
            if (!MoveToPage(addr))
                return MisalignedRead(addr, t);

        // If MoveToPage succeeds, we MUST be on the right page.
        _ASSERTE(addr >= mCurrPageStart);
        
        // However, the amount of data requested may fall off of the page.  In that case,
        // fall back to MisalignedRead.
        CORDB_ADDRESS offset = addr - mCurrPageStart;
        if (offset + sizeof(T) > mCurrPageSize)
            return MisalignedRead(addr, t);

        // If we reach here we know we are on the right page of memory in the cache, and
        // that the read won't fall off of the end of the page.
        *t = *reinterpret_cast<T*>(mPage+offset);
        return true;
    }

    // helper used to read the MethodTable
    bool ReadMT(CORDB_ADDRESS addr, TADDR *mt)
    {
        if (!Read(addr, mt))
            return false;

        // clear the GC flag bits off the MethodTable
        // equivalent to Object::GetGCSafeMethodTable()
        *mt &= ~3;
        return true;
    }

private:
    /* Sets the cache to the page specified by addr, or false if we could not move to
     * that page.
     */
    bool MoveToPage(CORDB_ADDRESS addr);

    /* Attempts to read from the target process if the data is possibly hanging off
     * the end of a page.
     */
    template<class T>
    inline bool MisalignedRead(CORDB_ADDRESS addr, T *t)
    {
        return SUCCEEDED(DacReadAll(TO_TADDR(addr), t, sizeof(t), false));
    }

private:
    CORDB_ADDRESS mCurrPageStart;
    ULONG32 mPageSize, mCurrPageSize;
    BYTE *mPage;
};

DWORD DacGetNumHeaps();

/* The implementation of the dac heap walker.  This class will enumerate all objects on
 * the heap with three important caveats:
 * - This class will skip all Free objects in the heap.  Free objects are an
 *   implementation detail of the GC, and ICorDebug does not have a mechanism
 *   to expose them.
 * - This class does NOT guarantee that all objects will be enumerated.  In
 *   the event that we find heap corruption on a segment, or if the background
 *   GC is modifying a segment, the remainder of that segment will be skipped
 *   by design.
 * - The GC heap must be in a walkable state before you attempt to use this
 *   class on it.  The IDacDbiInterface::AreGCStructuresValid function will
 *   tell you whether it is safe to walk the heap or not.
 */
class DacHeapWalker
{
    static CORDB_ADDRESS HeapStart;
    static CORDB_ADDRESS HeapEnd;

public:
    DacHeapWalker();
    ~DacHeapWalker();

    /* Initializes the heap walker.  This must be called before Next or
     * HasMoreObjects.  Returns false if the initialization was not successful.
     * (In practice this should only return false if we hit an OOM trying
     * to allocate space for data structures.)  Limits the heap walk to be in the range
     * [start, end] (inclusive).  Use DacHeapWalker::HeapStart, DacHeapWalker::HeapEnd
     * as start or end to start from the beginning or end.
     */
    HRESULT Init(CORDB_ADDRESS start=HeapStart, CORDB_ADDRESS end=HeapEnd);

    /* Returns a CORDB_ADDRESS which points to the next value on the heap.
     * You must call HasMoreObjects on this class, and it must return true
     * before calling Next.
     */
    HRESULT Next(CORDB_ADDRESS *pValue, CORDB_ADDRESS *pMT, ULONG64 *size);

    /* Returns true if there are more objects on the heap, false otherwise.
     */
    inline bool HasMoreObjects() const
    {
        return mCurrHeap < mHeapCount;
    }

    HRESULT Reset(CORDB_ADDRESS start, CORDB_ADDRESS end);
    
    static HRESULT InitHeapDataWks(HeapData *&pHeaps, size_t &count);
    static HRESULT InitHeapDataSvr(HeapData *&pHeaps, size_t &count);

    HRESULT GetHeapData(HeapData **ppHeapData, size_t *pNumHeaps);

    SegmentData *FindSegment(CORDB_ADDRESS obj);
    
    HRESULT ListNearObjects(CORDB_ADDRESS obj, CORDB_ADDRESS *pPrev, CORDB_ADDRESS *pContaining, CORDB_ADDRESS *pNext);

private:
    HRESULT MoveToNextObject();

    bool GetSize(TADDR tMT, size_t &size);

    inline static size_t Align(size_t size)
    {
        if (sizeof(TADDR) == 4)
            return (size+3) & ~3;
        else
            return (size+7) & ~7;
    }

    inline static size_t AlignLarge(size_t size)
    {
        return (size + 7) & ~7;
    }

    template <class T>
    static int GetSegmentCount(T seg_start)
    {
        int count = 0;
        while (seg_start)
        {
            // If we find this many segments, something is seriously wrong.
            if (count++ > 4096)
                break;

            seg_start = seg_start->next;
        }

        return count;
    }

    HRESULT NextSegment();
    void CheckAllocAndSegmentRange();

private:
    int mThreadCount;
    AllocInfo *mAllocInfo;

    size_t mHeapCount;
    HeapData *mHeaps;

    CORDB_ADDRESS mCurrObj;
    size_t mCurrSize;
    TADDR mCurrMT;

    size_t mCurrHeap;
    size_t mCurrSeg;

    CORDB_ADDRESS mStart;
    CORDB_ADDRESS mEnd;

    LinearReadCache mCache;
    static CORDB_ADDRESS sFreeMT;
};

struct DacGcReference;
struct SOSStackErrorList
{
    SOSStackRefError error;
    SOSStackErrorList *pNext;
    
    SOSStackErrorList()
        : pNext(0)
    {
    }
};

class DacStackReferenceWalker;
class DacStackReferenceErrorEnum : public DefaultCOMImpl<ISOSStackRefErrorEnum>
{
public:
    DacStackReferenceErrorEnum(DacStackReferenceWalker *pEnum, SOSStackErrorList *pErrors);
    ~DacStackReferenceErrorEnum();
    
    HRESULT STDMETHODCALLTYPE Skip(unsigned int count);
    HRESULT STDMETHODCALLTYPE Reset();
    HRESULT STDMETHODCALLTYPE GetCount(unsigned int *pCount);
    HRESULT STDMETHODCALLTYPE Next(unsigned int count, SOSStackRefError ref[], unsigned int *pFetched);
    
private:
    // The lifetime of the error list is tied to the enum, so we must addref/release it.
    DacStackReferenceWalker *mEnum;
    SOSStackErrorList *mHead;
    SOSStackErrorList *mCurr;
};

// For GCCONTEXT
#include "gcenv.h"

 /* DacStackReferenceWalker.
 */
class DacStackReferenceWalker : public DefaultCOMImpl<ISOSStackRefEnum>
{
    struct DacScanContext : public ScanContext
    {
        DacStackReferenceWalker *pWalker;
        Frame *pFrame;
        TADDR sp, pc;
        bool stop;
        GCEnumCallback pEnumFunc;
        
        DacScanContext()
            : pWalker(NULL), pFrame(0), sp(0), pc(0), stop(false), pEnumFunc(0)
        {
        }
    };

    typedef struct _StackRefChunkHead
    {
        struct _StackRefChunkHead *next;  // Next chunk
        unsigned int count;               // The count of how many StackRefs were written to pData
        unsigned int size;                // The capacity of pData (in bytes)
        void *pData;                      // The overflow data
        
        _StackRefChunkHead()
            : next(0), count(0), size(0), pData(0)
        {
        }
    } StackRefChunkHead;

    // The actual struct used for storing overflow StackRefs
    typedef struct _StackRefChunk : public StackRefChunkHead
    {
        SOSStackRefData data[64];
        
        _StackRefChunk()
        {
            pData = data;
            size = sizeof(data);
        }
    } StackRefChunk;
public:
    DacStackReferenceWalker(ClrDataAccess *dac, DWORD osThreadID);
    ~DacStackReferenceWalker();
    
    HRESULT Init();
    
    HRESULT STDMETHODCALLTYPE Skip(unsigned int count);
    HRESULT STDMETHODCALLTYPE Reset();
    HRESULT STDMETHODCALLTYPE GetCount(unsigned int *pCount);
    HRESULT STDMETHODCALLTYPE Next(unsigned int count,
                                   SOSStackRefData refs[],
                                   unsigned int *pFetched);
   
   // Dac-Dbi Functions
   HRESULT Next(ULONG celt, DacGcReference roots[], ULONG *pceltFetched);
   Thread *GetThread() const
   {
        return mThread;
   }
                                   
    HRESULT STDMETHODCALLTYPE EnumerateErrors(ISOSStackRefErrorEnum **ppEnum);
                                   
private:
    static StackWalkAction Callback(CrawlFrame *pCF, VOID *pData);
    static void GCEnumCallbackSOS(LPVOID hCallback, OBJECTREF *pObject, DWORD flags, DacSlotLocation loc);
    static void GCReportCallbackSOS(PTR_PTR_Object ppObj, ScanContext *sc, DWORD flags);
    static void GCEnumCallbackDac(LPVOID hCallback, OBJECTREF *pObject, DWORD flags, DacSlotLocation loc);
    static void GCReportCallbackDac(PTR_PTR_Object ppObj, ScanContext *sc, DWORD flags);

    CLRDATA_ADDRESS ReadPointer(TADDR addr);

    template <class StructType>
    StructType *GetNextObject(DacScanContext *ctx)
    {
        SUPPORTS_DAC;
        
        // If we failed on a previous call (OOM) don't keep trying to allocate, it's not going to work.
        if (ctx->stop || !mCurr)
            return NULL;
        
        // We've moved past the size of the current chunk.  We'll allocate a new chunk
        // and stuff the references there.  These are cleaned up by the destructor.
        if (mCurr->count >= mCurr->size/sizeof(StructType))
        {
            if (mCurr->next == NULL)
            {
                StackRefChunk *next = new (nothrow) StackRefChunk;
                if (next != NULL)
                {
                    mCurr->next = next;
                }
                else
                {
                    ctx->stop = true;
                    return NULL;
                }
            }
            
            mCurr = mCurr->next;
        }
        
        // Fill the current ref.
        StructType *pData = (StructType*)mCurr->pData;
        return &pData[mCurr->count++];
    }


    template <class IntType, class StructType>
    IntType WalkStack(IntType count, StructType refs[], promote_func promote, GCEnumCallback enumFunc)
    {
        _ASSERTE(mThread);
        _ASSERTE(!mEnumerated);
        
        // If this is the first time we were called, fill local data structures.
        // This will fill out the user's handles as well.
        _ASSERTE(mCurr == NULL);
        _ASSERTE(mHead.next == NULL);
        
        // Get the current thread's context and set that as the filter context
        if (mThread->GetFilterContext() == NULL && mThread->GetProfilerFilterContext() == NULL)
        {
            T_CONTEXT ctx;
            mDac->m_pTarget->GetThreadContext(mThread->GetOSThreadId(), CONTEXT_FULL, sizeof(ctx), (BYTE*)&ctx);
            mThread->SetProfilerFilterContext(&ctx);
        }
        
        // Setup GCCONTEXT structs for the stackwalk.
        GCCONTEXT gcctx;
        DacScanContext dsc;
        dsc.pWalker = this;
        dsc.pEnumFunc = enumFunc;
        gcctx.f = promote;
        gcctx.sc = &dsc;
        
        // Put the user's array/count in the 
        mHead.size = count*sizeof(StructType);
        mHead.pData = refs;
        mHead.count = 0;
        
        mCurr = &mHead;
        
        // Walk the stack, set mEnumerated to true to ensure we don't do it again.
        unsigned int flagsStackWalk = ALLOW_INVALID_OBJECTS|ALLOW_ASYNC_STACK_WALK;
#if defined(WIN64EXCEPTIONS)
        flagsStackWalk |= GC_FUNCLET_REFERENCE_REPORTING;
#endif // defined(WIN64EXCEPTIONS)

        mEnumerated = true;
        mThread->StackWalkFrames(DacStackReferenceWalker::Callback, &gcctx, flagsStackWalk);
        
        // We have filled the user's array as much as we could.  If there's more data than
        // could fit, mHead.Next will contain a linked list of refs to enumerate.
        mCurr = mHead.next;
        
        // Return how many we put in the user's array.
        return mHead.count;
    }
    
    template <class IntType, class StructType, promote_func PromoteFunc, GCEnumCallback EnumFunc>
    HRESULT DoStackWalk(IntType count, StructType stackRefs[], IntType *pFetched)
    {
        HRESULT hr = S_OK;
        IntType fetched = 0;
        if (!mEnumerated)
        {
            // If this is the first time we were called, fill local data structures.
            // This will fill out the user's handles as well.
            fetched = (IntType)WalkStack((unsigned int)count, stackRefs, PromoteFunc, EnumFunc);
        }
        
        while (fetched < count)
        {
            if (mCurr == NULL)
            {
                // Case 1: We have no more refs to walk.
                hr = S_FALSE;
                break;
            }
            else if (mChunkIndex >= mCurr->count)
            {
                // Case 2: We have exhausted the current chunk.
                mCurr = mCurr->next;
                mChunkIndex = 0;
            }
            else
            {
                // Case 3:  The last call to "Next" filled the user's array and had some ref
                // data leftover.  Walk the linked-list of arrays copying them into the user's
                // buffer until we have either exhausted the user's array or the leftover data.
                IntType toCopy = count - fetched;  // Fill the user's buffer...
                
                // ...unless that would go past the bounds of the current chunk.
                if (toCopy + mChunkIndex > mCurr->count)
                    toCopy = mCurr->count - mChunkIndex;
                
                memcpy(stackRefs+fetched, (StructType*)mCurr->pData+mChunkIndex, toCopy*sizeof(StructType));
                mChunkIndex += toCopy;
                fetched += toCopy;
            }
        }
        
        *pFetched = fetched;
        
        return hr;
    }

private:
    // Dac variables required for entering/leaving the dac.
    ClrDataAccess *mDac;
    ULONG32 m_instanceAge;
    
    // Operational variables
    Thread *mThread;
    SOSStackErrorList *mErrors;
    bool mEnumerated;
    
    // Storage variables
    StackRefChunkHead mHead;
    unsigned int mChunkIndex;
    
    // Iterator variables
    StackRefChunkHead *mCurr;
    int mIteratorIndex;
    
    // Heap.  Used to resolve interior pointers.
    DacHeapWalker mHeap;
};



struct DacGcReference;
class DacHandleWalker : public DefaultCOMImpl<ISOSHandleEnum>
{
    typedef struct _HandleChunkHead
    {
        struct _HandleChunkHead *Next;  // Next chunk
        unsigned int Count;             // The count of how many handles were written to pData
        unsigned int Size;              // The capacity of pData
        void *pData;           // The overflow data
        
        _HandleChunkHead()
            : Next(0), Count(0), Size(0), pData(0)
        {
        }
    } HandleChunkHead;

    // The actual struct used for storing overflow handles
    typedef struct _HandleChunk : public HandleChunkHead
    {
        SOSHandleData Data[128];
        
        _HandleChunk()
        {
            pData = Data;
            Size = sizeof(Data);
        }
    } HandleChunk;

    // Parameter used in HndEnumHandles callback.
    struct DacHandleWalkerParam
    {
        HandleChunkHead *Curr;      // The current chunk to write to
        HRESULT Result;             // HRESULT of the current enumeration
        CLRDATA_ADDRESS AppDomain;  // The AppDomain for the current bucket we are walking
        unsigned int Type;          // The type of handle we are currently walking
        
        DacHandleWalkerParam(HandleChunk *curr)
            : Curr(curr), Result(S_OK), AppDomain(0), Type(0)
        {
        }
    };

public:
    DacHandleWalker();
    ~DacHandleWalker();
    
    HRESULT Init(ClrDataAccess *dac, UINT types[], UINT typeCount);
    HRESULT Init(ClrDataAccess *dac, UINT types[], UINT typeCount, int gen);
    HRESULT Init(UINT32 typemask);
    
    // SOS functions
    HRESULT STDMETHODCALLTYPE Skip(unsigned int count);
    HRESULT STDMETHODCALLTYPE Reset();
    HRESULT STDMETHODCALLTYPE GetCount(unsigned int *pCount);
    HRESULT STDMETHODCALLTYPE Next(unsigned int count,
                                   SOSHandleData handles[],
                                   unsigned int *pNeeded);
   
   // Dac-Dbi Functions
   HRESULT Next(ULONG celt, DacGcReference roots[], ULONG *pceltFetched);
private:
    static void CALLBACK EnumCallback(PTR_UNCHECKED_OBJECTREF pref, LPARAM *pExtraInfo, LPARAM userParam, LPARAM type);
    static void GetRefCountedHandleInfo(
        OBJECTREF oref, unsigned int uType, 
        unsigned int *pRefCount, unsigned int *pJupiterRefCount, BOOL *pIsPegged, BOOL *pIsStrong);
    static UINT32 BuildTypemask(UINT types[], UINT typeCount);

private:
    static void CALLBACK EnumCallbackSOS(PTR_UNCHECKED_OBJECTREF pref, LPARAM *pExtraInfo, LPARAM userParam, LPARAM type);
    static void CALLBACK EnumCallbackDac(PTR_UNCHECKED_OBJECTREF pref, LPARAM *pExtraInfo, LPARAM userParam, LPARAM type);
    
    bool FetchMoreHandles(HANDLESCANPROC proc);
    static inline bool IsAlwaysStrongReference(unsigned int type)
    {
        return type == HNDTYPE_STRONG || type == HNDTYPE_PINNED || type == HNDTYPE_ASYNCPINNED || type == HNDTYPE_SIZEDREF;
    }

    template <class StructType, class IntType, HANDLESCANPROC EnumFunc>
    HRESULT DoHandleWalk(IntType celt, StructType handles[], IntType *pceltFetched)
    {
        SUPPORTS_DAC;
        
        if (handles == NULL || pceltFetched == NULL)
            return E_POINTER;
        
        HRESULT hr = S_OK;
        IntType fetched = 0;
        bool done = false;

        // On each iteration of the loop, either fetch more handles (filling in
        // the user's data structure), or copy handles from previous calls to
        // FetchMoreHandles which we could not store in the user's data (or simply
        // advance the current chunk to the next chunk).
        while (fetched < celt)
        {
            if (mCurr == NULL)
            {
                // Case 1:  We have no overflow data.  Stuff the user's array/size into
                // mHead, fetch more handles.  Additionally, if the previous call to
                // FetchMoreHandles returned false (mMap == NULL), break.
                if (mMap == NULL)
                    break;
                
                mHead.pData = handles+fetched;
                mHead.Size = (celt - fetched)*sizeof(StructType);
                
                done = !FetchMoreHandles(EnumFunc);
                fetched += mHead.Count;
                
                // Sanity check to make sure we haven't overflowed.  This should not happen.
                _ASSERTE(fetched <= celt);
            }
            else if (mChunkIndex >= mCurr->Count)
            {
                // Case 2:  We have overflow data, but the current index into the current
                // chunk is past the bounds.  Move to the next.  This could set mCurr to
                // null, which we'll catch on the next iteration.
                mCurr = mCurr->Next;
                mChunkIndex = 0;
            }
            else
            {
                // Case 3:  The last call to "Next" filled the user's array and had some handle
                // data leftover.  Walk the linked-list of arrays copying them into the user's
                // buffer until we have either exhausted the user's array or the leftover data.
                unsigned int toCopy = celt - fetched;  // Fill the user's buffer...
                
                // ...unless that would go past the bounds of the current chunk.
                if (toCopy + mChunkIndex > mCurr->Count)
                    toCopy = mCurr->Count - mChunkIndex;
                
                memcpy(handles+fetched, ((StructType*)(mCurr->pData))+mChunkIndex, toCopy*sizeof(StructType));
                mChunkIndex += toCopy;
                fetched += toCopy;
            }
        }
        
        if (fetched < celt)
            hr = S_FALSE;
            
        *pceltFetched = fetched;
        
        return hr;
    }
    
private:
    // Dac variables required for entering/leaving the dac.
    ClrDataAccess *mDac;
    ULONG32 m_instanceAge;
    
    // Handle table walking variables.
    HandleTableMap *mMap;
    int mIndex;
    UINT32 mTypeMask;
    int mGenerationFilter;
    
    // Storage variables
    HandleChunk mHead;
    unsigned int mChunkIndex;
    
    // Iterator variables
    HandleChunkHead *mCurr;
    int mIteratorIndex;
};


//----------------------------------------------------------------------------
//
// ClrDataAppDomain.
//
//----------------------------------------------------------------------------

class ClrDataAppDomain : public IXCLRDataAppDomain
{
public:
    ClrDataAppDomain(ClrDataAccess* dac,
                     AppDomain* appDomain);
    ~ClrDataAppDomain(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataAppDomain.
    //

    virtual HRESULT STDMETHODCALLTYPE GetProcess(
        /* [out] */ IXCLRDataProcess **process);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetUniqueID(
        /* [out] */ ULONG64 *id);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataAppDomain *appDomain);

    virtual HRESULT STDMETHODCALLTYPE GetManagedObject(
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    AppDomain* GetAppDomain(void)
    {
        SUPPORTS_DAC;
        return m_appDomain;
    }

private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    AppDomain* m_appDomain;
};

//----------------------------------------------------------------------------
//
// ClrDataAssembly.
//
//----------------------------------------------------------------------------

class ClrDataAssembly : public IXCLRDataAssembly
{
public:
    ClrDataAssembly(ClrDataAccess* dac,
                    Assembly* assembly);
    ~ClrDataAssembly(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataAssembly.
    //

    virtual HRESULT STDMETHODCALLTYPE StartEnumModules(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumModule(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE EndEnumModules(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumAppDomains(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumAppDomain(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataAppDomain **appDomain);

    virtual HRESULT STDMETHODCALLTYPE EndEnumAppDomains(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetFileName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetDisplayName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataAssembly *assembly);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    Assembly* m_assembly;
};

//----------------------------------------------------------------------------
//
// ClrDataModule.
//
//----------------------------------------------------------------------------

class ClrDataModule : public IXCLRDataModule, IXCLRDataModule2
{
public:
    ClrDataModule(ClrDataAccess* dac,
                  Module* module);
    ~ClrDataModule(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataModule.
    //

    virtual HRESULT STDMETHODCALLTYPE StartEnumAssemblies(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumAssembly(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataAssembly **assembly);

    virtual HRESULT STDMETHODCALLTYPE EndEnumAssemblies(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumAppDomains(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumAppDomain(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataAppDomain **appDomain);

    virtual HRESULT STDMETHODCALLTYPE EndEnumAppDomains(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumTypeDefinitions(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumTypeDefinition(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataTypeDefinition **typeDefinition);

    virtual HRESULT STDMETHODCALLTYPE EndEnumTypeDefinitions(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumTypeInstances(
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumTypeInstance(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataTypeInstance **typeInstance);

    virtual HRESULT STDMETHODCALLTYPE EndEnumTypeInstances(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumTypeDefinitionsByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumTypeDefinitionByName(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataTypeDefinition **type);

    virtual HRESULT STDMETHODCALLTYPE EndEnumTypeDefinitionsByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumTypeInstancesByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataAppDomain *appDomain,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumTypeInstanceByName(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataTypeInstance **type);

    virtual HRESULT STDMETHODCALLTYPE EndEnumTypeInstancesByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetTypeDefinitionByToken(
        /* [in] */ mdTypeDef token,
        /* [out] */ IXCLRDataTypeDefinition **typeDefinition);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodDefinitionsByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodDefinitionByName(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodDefinition **method);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodDefinitionsByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodInstancesByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodInstanceByName(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodInstance **method);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodInstancesByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetMethodDefinitionByToken(
        /* [in] */ mdMethodDef token,
        /* [out] */ IXCLRDataMethodDefinition **methodDefinition);

    virtual HRESULT STDMETHODCALLTYPE StartEnumDataByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [in] */ IXCLRDataTask* tlsTask,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumDataByName(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE EndEnumDataByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetFileName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetVersionId(
        /* [out] */ GUID* vid);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataModule *mod);

    virtual HRESULT STDMETHODCALLTYPE StartEnumExtents(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumExtent(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ CLRDATA_MODULE_EXTENT *extent);

    virtual HRESULT STDMETHODCALLTYPE EndEnumExtents(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    HRESULT RequestGetModulePtr(IN ULONG32 inBufferSize,
                              IN BYTE* inBuffer,
                              IN ULONG32 outBufferSize,
                              OUT BYTE* outBuffer);

    Module* GetModule(void)
    {
        return m_module;
    }

    //
    // IXCLRDataModule2
    //
    virtual HRESULT STDMETHODCALLTYPE SetJITCompilerFlags(
        /* [in] */ DWORD dwFlags );

private:
    // Returns an instance of IID_IMetaDataImport.
    HRESULT GetMdInterface(PVOID* retIface);

    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    Module* m_module;
    IMetaDataImport* m_mdImport;
    bool m_setExtents;
    CLRDATA_MODULE_EXTENT m_extents[2];
    CLRDATA_MODULE_EXTENT* m_extentsEnd;
};

//----------------------------------------------------------------------------
//
// ClrDataTypeDefinition.
//
//----------------------------------------------------------------------------

class ClrDataTypeDefinition : public IXCLRDataTypeDefinition
{
public:
    ClrDataTypeDefinition(ClrDataAccess* dac,
                          Module* module,
                          mdTypeDef token,
                          TypeHandle typeHandle);
    ~ClrDataTypeDefinition(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataTypeDefinition.
    //

    virtual HRESULT STDMETHODCALLTYPE GetModule(
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodDefinitions(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodDefinition(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodDefinition **methodDefinition);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodDefinitions(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodDefinitionsByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodDefinitionByName(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodDefinition **method);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodDefinitionsByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetMethodDefinitionByToken(
        /* [in] */ mdMethodDef token,
        /* [out] */ IXCLRDataMethodDefinition **methodDefinition);

    virtual HRESULT STDMETHODCALLTYPE StartEnumInstances(
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumInstance(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataTypeInstance **instance);

    virtual HRESULT STDMETHODCALLTYPE EndEnumInstances(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetNumFields(
        /* [in] */ ULONG32 flags,
        /* [out] */ ULONG32 *numFields);

    virtual HRESULT STDMETHODCALLTYPE StartEnumFields(
        /* [in] */ ULONG32 flags,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumField(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [in] */ ULONG32 nameBufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(nameBufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataTypeDefinition **type,
        /* [out] */ ULONG32 *flags,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EnumField2(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [in] */ ULONG32 nameBufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(nameBufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataTypeDefinition **type,
        /* [out] */ ULONG32 *flags,
        /* [out] */ IXCLRDataModule** tokenScope,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EndEnumFields(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumFieldsByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 nameFlags,
        /* [in] */ ULONG32 fieldFlags,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumFieldByName(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataTypeDefinition **type,
        /* [out] */ ULONG32 *flags,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EnumFieldByName2(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataTypeDefinition **type,
        /* [out] */ ULONG32 *flags,
        /* [out] */ IXCLRDataModule** tokenScope,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EndEnumFieldsByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetFieldByToken(
        /* [in] */ mdFieldDef token,
        /* [in] */ ULONG32 nameBufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(nameBufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataTypeDefinition **type,
        /* [out] */ ULONG32* flags);

    virtual HRESULT STDMETHODCALLTYPE GetFieldByToken2(
        /* [in] */ IXCLRDataModule* tokenScope,
        /* [in] */ mdFieldDef token,
        /* [in] */ ULONG32 nameBufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(nameBufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataTypeDefinition **type,
        /* [out] */ ULONG32* flags);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetTokenAndScope(
        /* [out] */ mdTypeDef *token,
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE GetCorElementType(
        /* [out] */ CorElementType *type);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE GetBase(
        /* [out] */ IXCLRDataTypeDefinition **base);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataTypeDefinition *type);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    virtual HRESULT STDMETHODCALLTYPE GetArrayRank(
        /* [out] */ ULONG32* rank);

    virtual HRESULT STDMETHODCALLTYPE GetTypeNotification(
        /* [out] */ ULONG32* flags);

    virtual HRESULT STDMETHODCALLTYPE SetTypeNotification(
        /* [in] */ ULONG32 flags);

    static HRESULT NewFromModule(ClrDataAccess* dac,
                                 Module* module,
                                 mdTypeDef token,
                                 ClrDataTypeDefinition** typeDef,
                                 IXCLRDataTypeDefinition** pubTypeDef);

    TypeHandle GetTypeHandle(void)
    {
        return m_typeHandle;
    }

private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    Module* m_module;
    mdTypeDef m_token;
    TypeHandle m_typeHandle;
};

//----------------------------------------------------------------------------
//
// ClrDataTypeInstance.
//
//----------------------------------------------------------------------------

class ClrDataTypeInstance : public IXCLRDataTypeInstance
{
public:
    ClrDataTypeInstance(ClrDataAccess* dac,
                        AppDomain* appDomain,
                        TypeHandle typeHandle);
    ~ClrDataTypeInstance(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataTypeInstance.
    //

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodInstances(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodInstance(
        /* [in, out] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodInstance **methodInstance);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodInstances(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumMethodInstancesByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumMethodInstanceByName(
        /* [in] */ CLRDATA_ENUM* handle,
        /* [out] */ IXCLRDataMethodInstance **method);

    virtual HRESULT STDMETHODCALLTYPE EndEnumMethodInstancesByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetNumStaticFields(
        /* [out] */ ULONG32 *numFields);

    virtual HRESULT STDMETHODCALLTYPE GetStaticFieldByIndex(
        /* [in] */ ULONG32 index,
        /* [in] */ IXCLRDataTask *tlsTask,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE StartEnumStaticFieldsByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataTask *tlsTask,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumStaticFieldByName(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE EndEnumStaticFieldsByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetNumStaticFields2(
        /* [in] */ ULONG32 flags,
        /* [out] */ ULONG32 *numFields);

    virtual HRESULT STDMETHODCALLTYPE StartEnumStaticFields(
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataTask *tlsTask,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumStaticField(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE EnumStaticField2(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **value,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataModule** tokenScope,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EndEnumStaticFields(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumStaticFieldsByName2(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 nameFlags,
        /* [in] */ ULONG32 fieldFlags,
        /* [in] */ IXCLRDataTask *tlsTask,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumStaticFieldByName3(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **value,
        /* [out] */ IXCLRDataModule** tokenScope,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EnumStaticFieldByName2(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE EndEnumStaticFieldsByName2(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetStaticFieldByToken(
        /* [in] */ mdFieldDef token,
        /* [in] */ IXCLRDataTask *tlsTask,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetStaticFieldByToken2(
        /* [in] */ IXCLRDataModule* tokenScope,
        /* [in] */ mdFieldDef token,
        /* [in] */ IXCLRDataTask *tlsTask,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetModule(
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE GetDefinition(
        /* [out] */ IXCLRDataTypeDefinition **typeDefinition);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE GetBase(
        /* [out] */ IXCLRDataTypeInstance **base);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataTypeInstance *type);

    virtual HRESULT STDMETHODCALLTYPE GetNumTypeArguments(
        /* [out] */ ULONG32 *numTypeArgs);

    virtual HRESULT STDMETHODCALLTYPE GetTypeArgumentByIndex(
        /* [in] */ ULONG32 index,
        /* [out] */ IXCLRDataTypeInstance **typeArg);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    static HRESULT NewFromModule(ClrDataAccess* dac,
                                 AppDomain* appDomain,
                                 Module* module,
                                 mdTypeDef token,
                                 ClrDataTypeInstance** typeInst,
                                 IXCLRDataTypeInstance** pubTypeInst);

    TypeHandle GetTypeHandle(void)
    {
        return m_typeHandle;
    }

private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    AppDomain* m_appDomain;
    TypeHandle m_typeHandle;
};

//----------------------------------------------------------------------------
//
// ClrDataMethodDefinition.
//
//----------------------------------------------------------------------------

class ClrDataMethodDefinition : public IXCLRDataMethodDefinition
{
public:
    ClrDataMethodDefinition(ClrDataAccess* dac,
                            Module* module,
                            mdMethodDef token,
                            MethodDesc* methodDesc);
    ~ClrDataMethodDefinition(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataMethodDefinition.
    //

    virtual HRESULT STDMETHODCALLTYPE GetTypeDefinition(
        /* [out] */ IXCLRDataTypeDefinition **typeDefinition);

    virtual HRESULT STDMETHODCALLTYPE StartEnumInstances(
        /* [in] */ IXCLRDataAppDomain* appDomain,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumInstance(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataMethodInstance **instance);

    virtual HRESULT STDMETHODCALLTYPE EndEnumInstances(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetTokenAndScope(
        /* [out] */ mdMethodDef *token,
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataMethodDefinition *method);

    virtual HRESULT STDMETHODCALLTYPE GetLatestEnCVersion(
        /* [out] */ ULONG32* version);

    virtual HRESULT STDMETHODCALLTYPE StartEnumExtents(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumExtent(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ CLRDATA_METHDEF_EXTENT *extent);

    virtual HRESULT STDMETHODCALLTYPE EndEnumExtents(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetCodeNotification(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE SetCodeNotification(
        /* [in] */ ULONG32 flags);

    virtual HRESULT STDMETHODCALLTYPE GetRepresentativeEntryAddress(
        /* [out] */ CLRDATA_ADDRESS* addr);

    virtual HRESULT STDMETHODCALLTYPE HasClassOrMethodInstantiation(
        /*[out]*/ BOOL* bGeneric);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    COR_ILMETHOD* GetIlMethod(void);
    
    static HRESULT NewFromModule(ClrDataAccess* dac,
                                 Module* module,
                                 mdMethodDef token,
                                 ClrDataMethodDefinition** methDef,
                                 IXCLRDataMethodDefinition** pubMethDef);

    static HRESULT GetSharedMethodFlags(MethodDesc* methodDesc,
                                        ULONG32* flags);

    // We don't need this if we are able to form name using token
    MethodDesc *GetMethodDesc() { return m_methodDesc;}
private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    Module* m_module;
    mdMethodDef m_token;
    MethodDesc* m_methodDesc;
};

//----------------------------------------------------------------------------
//
// ClrDataMethodInstance.
//
//----------------------------------------------------------------------------

class ClrDataMethodInstance : public IXCLRDataMethodInstance
{
public:
    ClrDataMethodInstance(ClrDataAccess* dac,
                          AppDomain* appDomain,
                          MethodDesc* methodDesc);
    ~ClrDataMethodInstance(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataMethodInstance.
    //

    virtual HRESULT STDMETHODCALLTYPE GetTypeInstance(
        /* [out] */ IXCLRDataTypeInstance **typeInstance);

    virtual HRESULT STDMETHODCALLTYPE GetDefinition(
        /* [out] */ IXCLRDataMethodDefinition **methodDefinition);

    virtual HRESULT STDMETHODCALLTYPE GetTokenAndScope(
        /* [out] */ mdMethodDef *token,
        /* [out] */ IXCLRDataModule **mod);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataMethodInstance *method);

    virtual HRESULT STDMETHODCALLTYPE GetEnCVersion(
        /* [out] */ ULONG32* version);

    virtual HRESULT STDMETHODCALLTYPE GetNumTypeArguments(
        /* [out] */ ULONG32 *numTypeArgs);

    virtual HRESULT STDMETHODCALLTYPE GetTypeArgumentByIndex(
        /* [in] */ ULONG32 index,
        /* [out] */ IXCLRDataTypeInstance **typeArg);

    virtual HRESULT STDMETHODCALLTYPE GetILOffsetsByAddress(
        /* [in] */ CLRDATA_ADDRESS address,
        /* [in] */ ULONG32 offsetsLen,
        /* [out] */ ULONG32 *offsetsNeeded,
        /* [size_is][out] */ ULONG32 ilOffsets[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetAddressRangesByILOffset(
        /* [in] */ ULONG32 ilOffset,
        /* [in] */ ULONG32 rangesLen,
        /* [out] */ ULONG32 *rangesNeeded,
        /* [size_is][out] */ CLRDATA_ADDRESS_RANGE addressRanges[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetILAddressMap(
        /* [in] */ ULONG32 mapLen,
        /* [out] */ ULONG32 *mapNeeded,
        /* [size_is][out] */ CLRDATA_IL_ADDRESS_MAP maps[  ]);

    virtual HRESULT STDMETHODCALLTYPE StartEnumExtents(
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumExtent(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ CLRDATA_ADDRESS_RANGE *extent);

    virtual HRESULT STDMETHODCALLTYPE EndEnumExtents(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetRepresentativeEntryAddress(
        /* [out] */ CLRDATA_ADDRESS* addr);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    static HRESULT NewFromModule(ClrDataAccess* dac,
                                 AppDomain* appDomain,
                                 Module* module,
                                 mdMethodDef token,
                                 ClrDataMethodInstance** methInst,
                                 IXCLRDataMethodInstance** pubMethInst);

private:
    friend class ClrDataAccess;
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    AppDomain* m_appDomain;
    MethodDesc* m_methodDesc;
};

//----------------------------------------------------------------------------
//
// ClrDataTask.
//
//----------------------------------------------------------------------------

class ClrDataTask : public IXCLRDataTask
{
public:
    ClrDataTask(ClrDataAccess* dac,
                Thread* Thread);
    ~ClrDataTask(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataTask.
    //

    virtual HRESULT STDMETHODCALLTYPE GetProcess(
        /* [out] */ IXCLRDataProcess **process);

    virtual HRESULT STDMETHODCALLTYPE GetCurrentAppDomain(
        /* [out] */ IXCLRDataAppDomain **appDomain);

    virtual HRESULT STDMETHODCALLTYPE GetName(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetUniqueID(
        /* [out] */ ULONG64 *id);

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE IsSameObject(
        /* [in] */ IXCLRDataTask *task);

    virtual HRESULT STDMETHODCALLTYPE GetManagedObject(
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE GetDesiredExecutionState(
        /* [out] */ ULONG32 *state);

    virtual HRESULT STDMETHODCALLTYPE SetDesiredExecutionState(
        /* [in] */ ULONG32 state);

    virtual HRESULT STDMETHODCALLTYPE CreateStackWalk(
        /* [in] */ ULONG32 flags,
        /* [out] */ IXCLRDataStackWalk **stackWalk);

    virtual HRESULT STDMETHODCALLTYPE GetOSThreadID(
        /* [out] */ ULONG32 *id);

    virtual HRESULT STDMETHODCALLTYPE GetContext(
        /* [in] */ ULONG32 contextFlags,
        /* [in] */ ULONG32 contextBufSize,
        /* [out] */ ULONG32 *contextSize,
        /* [size_is][out] */ BYTE contextBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE SetContext(
        /* [in] */ ULONG32 contextSize,
        /* [size_is][in] */ BYTE context[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetCurrentExceptionState(
        /* [out] */ IXCLRDataExceptionState **exception);

    virtual HRESULT STDMETHODCALLTYPE GetLastExceptionState(
        /* [out] */ IXCLRDataExceptionState **exception);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    Thread* GetThread(void)
    {
        return m_thread;
    }

private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    Thread* m_thread;
};

//----------------------------------------------------------------------------
//
// ClrDataStackWalk.
//
//----------------------------------------------------------------------------

class ClrDataStackWalk : public IXCLRDataStackWalk
{
public:
    ClrDataStackWalk(ClrDataAccess* dac,
                     Thread* Thread,
                     ULONG32 flags);
    ~ClrDataStackWalk(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataStackWalk.
    //

    virtual HRESULT STDMETHODCALLTYPE GetContext(
        /* [in] */ ULONG32 contextFlags,
        /* [in] */ ULONG32 contextBufSize,
        /* [out] */ ULONG32 *contextSize,
        /* [size_is][out] */ BYTE contextBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE SetContext(
        /* [in] */ ULONG32 contextSize,
        /* [size_is][in] */ BYTE context[  ]);

    virtual HRESULT STDMETHODCALLTYPE Next( void);

    virtual HRESULT STDMETHODCALLTYPE GetStackSizeSkipped(
        /* [out] */ ULONG64 *stackSizeSkipped);

    virtual HRESULT STDMETHODCALLTYPE GetFrameType(
        /* [out] */ CLRDataSimpleFrameType *simpleType,
        /* [out] */ CLRDataDetailedFrameType *detailedType);

    virtual HRESULT STDMETHODCALLTYPE GetFrame(
        /* [out] */ IXCLRDataFrame **frame);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    virtual HRESULT STDMETHODCALLTYPE SetContext2(
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 contextSize,
        /* [size_is][in] */ BYTE context[  ]);

    HRESULT Init(void);

private:
    void FilterFrames(void);
    void RawGetFrameType(
        /* [out] */ CLRDataSimpleFrameType* simpleType,
        /* [out] */ CLRDataDetailedFrameType* detailedType);

    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    Thread* m_thread;
    ULONG32 m_walkFlags;
    StackFrameIterator m_frameIter;
    REGDISPLAY m_regDisp;
    T_CONTEXT m_context;
    TADDR m_stackPrev;

    // This is part of a test hook for debugging.  Unless you're code:ClrDataStackWalk::Next
    //  you should never do anything with this member.
    INDEBUG( int m_framesUnwound; )

};

//----------------------------------------------------------------------------
//
// ClrDataFrame.
//
//----------------------------------------------------------------------------

class ClrDataFrame : public IXCLRDataFrame,
                            IXCLRDataFrame2
{
    friend class ClrDataStackWalk;

public:
    ClrDataFrame(ClrDataAccess* dac,
                 CLRDataSimpleFrameType simpleType,
                 CLRDataDetailedFrameType detailedType,
                 AppDomain* appDomain,
                 MethodDesc* methodDesc);
    ~ClrDataFrame(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataFrame.
    //

    virtual HRESULT STDMETHODCALLTYPE GetContext(
        /* [in] */ ULONG32 contextFlags,
        /* [in] */ ULONG32 contextBufSize,
        /* [out] */ ULONG32 *contextSize,
        /* [size_is][out] */ BYTE contextBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetFrameType(
        /* [out] */ CLRDataSimpleFrameType *simpleType,
        /* [out] */ CLRDataDetailedFrameType *detailedType);

    virtual HRESULT STDMETHODCALLTYPE GetAppDomain(
        /* [out] */ IXCLRDataAppDomain **appDomain);

    virtual HRESULT STDMETHODCALLTYPE GetNumArguments(
        /* [out] */ ULONG32 *numParams);

    virtual HRESULT STDMETHODCALLTYPE GetArgumentByIndex(
        /* [in] */ ULONG32 index,
        /* [out] */ IXCLRDataValue **arg,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetNumLocalVariables(
        /* [out] */ ULONG32 *numLocals);

    virtual HRESULT STDMETHODCALLTYPE GetLocalVariableByIndex(
        /* [in] */ ULONG32 index,
        /* [out] */ IXCLRDataValue **localVariable,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part(bufLen, *nameLen) WCHAR name[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetNumTypeArguments(
        /* [out] */ ULONG32 *numTypeArgs);

    virtual HRESULT STDMETHODCALLTYPE GetTypeArgumentByIndex(
        /* [in] */ ULONG32 index,
        /* [out] */ IXCLRDataTypeInstance **typeArg);

    virtual HRESULT STDMETHODCALLTYPE GetCodeName(
        /* [in] */ ULONG32 flags,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_opt(bufLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetMethodInstance(
        /* [out] */ IXCLRDataMethodInstance **method);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    //
    // IXCLRDataFrame2.
    //

    virtual HRESULT STDMETHODCALLTYPE GetExactGenericArgsToken(
        /* [out] */ IXCLRDataValue ** genericToken);

private:
    HRESULT GetMethodSig(MetaSig** sig,
                         ULONG32* count);
    HRESULT GetLocalSig(MetaSig** sig,
                        ULONG32* count);
    HRESULT ValueFromDebugInfo(MetaSig* sig,
                               bool isArg,
                               DWORD sigIndex,
                               DWORD varInfoSlot,
                               IXCLRDataValue** value);

    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    CLRDataSimpleFrameType m_simpleType;
    CLRDataDetailedFrameType m_detailedType;
    AppDomain* m_appDomain;
    MethodDesc* m_methodDesc;
    REGDISPLAY m_regDisp;
    T_CONTEXT m_context;
    MetaSig* m_methodSig;
    MetaSig* m_localSig;
};

//----------------------------------------------------------------------------
//
// ClrDataExceptionState.
//
//----------------------------------------------------------------------------

#ifdef WIN64EXCEPTIONS
typedef ExceptionTracker ClrDataExStateType;
#else // WIN64EXCEPTIONS
typedef ExInfo ClrDataExStateType;
#endif // WIN64EXCEPTIONS


class ClrDataExceptionState : public IXCLRDataExceptionState
{
public:
    ClrDataExceptionState(ClrDataAccess* dac,
                          AppDomain* appDomain,
                          Thread* thread,
                          ULONG32 flags,
                          ClrDataExStateType* exInfo,
                          OBJECTHANDLE throwable,
                          ClrDataExStateType* prevExInfo);
    ~ClrDataExceptionState(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataExceptionState.
    //

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE GetPrevious(
        /* [out] */ IXCLRDataExceptionState **exState);

    virtual HRESULT STDMETHODCALLTYPE GetManagedObject(
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE GetBaseType(
        /* [out] */ CLRDataBaseExceptionType *type);

    virtual HRESULT STDMETHODCALLTYPE GetCode(
        /* [out] */ ULONG32 *code);

    virtual HRESULT STDMETHODCALLTYPE GetString(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *strLen,
        /* [size_is][out] */ __out_ecount_part(bufLen, *strLen) WCHAR str[  ]);

    virtual HRESULT STDMETHODCALLTYPE IsSameState(
        /* [in] */ EXCEPTION_RECORD64 *exRecord,
        /* [in] */ ULONG32 contextSize,
        /* [size_is][in] */ BYTE cxRecord[  ]);

    virtual HRESULT STDMETHODCALLTYPE IsSameState2(
        /* [in] */ ULONG32 flags,
        /* [in] */ EXCEPTION_RECORD64 *exRecord,
        /* [in] */ ULONG32 contextSize,
        /* [size_is][in] */ BYTE cxRecord[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetTask(
        /* [out] */ IXCLRDataTask** task);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    static HRESULT NewFromThread(ClrDataAccess* dac,
                                 Thread* thread,
                                 ClrDataExceptionState** exception,
                                 IXCLRDataExceptionState** pubException);
    
    PTR_CONTEXT          GetCurrentContextRecord();
    PTR_EXCEPTION_RECORD GetCurrentExceptionRecord();

friend class ClrDataAccess;    
private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    AppDomain* m_appDomain;
    Thread* m_thread;
    ULONG32 m_flags;
    ClrDataExStateType* m_exInfo;
    OBJECTHANDLE m_throwable;
    ClrDataExStateType* m_prevExInfo;
};

//----------------------------------------------------------------------------
//
// ClrDataValue.
//
//----------------------------------------------------------------------------

class ClrDataValue : public IXCLRDataValue
{
public:
    ClrDataValue(ClrDataAccess* dac,
                 AppDomain* appDomain,
                 Thread* thread,
                 ULONG32 flags,
                 TypeHandle typeHandle,
                 ULONG64 baseAddr,
                 ULONG32 numLocs,
                 NativeVarLocation* locs);
    ~ClrDataValue(void);

    // IUnknown.
    STDMETHOD(QueryInterface)(THIS_
                              IN REFIID interfaceId,
                              OUT PVOID* iface);
    STDMETHOD_(ULONG, AddRef)(THIS);
    STDMETHOD_(ULONG, Release)(THIS);

    //
    // IXCLRDataValue.
    //

    virtual HRESULT STDMETHODCALLTYPE GetFlags(
        /* [out] */ ULONG32 *flags);

    virtual HRESULT STDMETHODCALLTYPE GetAddress(
        /* [out] */ CLRDATA_ADDRESS *address);

    virtual HRESULT STDMETHODCALLTYPE GetSize(
        /* [out] */ ULONG64 *size);

    virtual HRESULT STDMETHODCALLTYPE GetBytes(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *dataSize,
        /* [size_is][out] */ BYTE buffer[  ]);

    virtual HRESULT STDMETHODCALLTYPE SetBytes(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *dataSize,
        /* [size_is][in] */ BYTE buffer[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetType(
        /* [out] */ IXCLRDataTypeInstance **typeInstance);

    virtual HRESULT STDMETHODCALLTYPE GetNumFields(
        /* [out] */ ULONG32 *numFields);

    virtual HRESULT STDMETHODCALLTYPE GetFieldByIndex(
        /* [in] */ ULONG32 index,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE GetNumFields2(
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataTypeInstance *fromType,
        /* [out] */ ULONG32 *numFields);

    virtual HRESULT STDMETHODCALLTYPE StartEnumFields(
        /* [in] */ ULONG32 flags,
        /* [in] */ IXCLRDataTypeInstance *fromType,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumField(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 nameBufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(nameBufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EnumField2(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 nameBufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(nameBufLen, *nameLen) WCHAR nameBuf[  ],
        /* [out] */ IXCLRDataModule** tokenScope,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EndEnumFields(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE StartEnumFieldsByName(
        /* [in] */ LPCWSTR name,
        /* [in] */ ULONG32 nameFlags,
        /* [in] */ ULONG32 fieldFlags,
        /* [in] */ IXCLRDataTypeInstance *fromType,
        /* [out] */ CLRDATA_ENUM *handle);

    virtual HRESULT STDMETHODCALLTYPE EnumFieldByName(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **field,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EnumFieldByName2(
        /* [out][in] */ CLRDATA_ENUM *handle,
        /* [out] */ IXCLRDataValue **field,
        /* [out] */ IXCLRDataModule** tokenScope,
        /* [out] */ mdFieldDef *token);

    virtual HRESULT STDMETHODCALLTYPE EndEnumFieldsByName(
        /* [in] */ CLRDATA_ENUM handle);

    virtual HRESULT STDMETHODCALLTYPE GetFieldByToken(
        /* [in] */ mdFieldDef token,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetFieldByToken2(
        /* [in] */ IXCLRDataModule* tokenScope,
        /* [in] */ mdFieldDef token,
        /* [out] */ IXCLRDataValue **field,
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *nameLen,
        /* [size_is][out] */ __out_ecount_part_opt(bufLen, *nameLen) WCHAR nameBuf[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetAssociatedValue(
        /* [out] */ IXCLRDataValue **assocValue);

    virtual HRESULT STDMETHODCALLTYPE GetAssociatedType(
        /* [out] */ IXCLRDataTypeInstance **assocType);

    virtual HRESULT STDMETHODCALLTYPE GetString(
        /* [in] */ ULONG32 bufLen,
        /* [out] */ ULONG32 *strLen,
        /* [size_is][out] */ __out_ecount_part(bufLen, *strLen) WCHAR str[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetArrayProperties(
        /* [out] */ ULONG32 *rank,
        /* [out] */ ULONG32 *totalElements,
        /* [in] */ ULONG32 numDim,
        /* [size_is][out] */ ULONG32 dims[  ],
        /* [in] */ ULONG32 numBases,
        /* [size_is][out] */ LONG32 bases[  ]);

    virtual HRESULT STDMETHODCALLTYPE GetArrayElement(
        /* [in] */ ULONG32 numInd,
        /* [size_is][in] */ LONG32 indices[  ],
        /* [out] */ IXCLRDataValue **value);

    virtual HRESULT STDMETHODCALLTYPE GetNumLocations(
        /* [out] */ ULONG32* numLocs);
    
    virtual HRESULT STDMETHODCALLTYPE GetLocationByIndex(
        /* [in] */ ULONG32 loc,
        /* [out] */ ULONG32* flags,
        /* [out] */ CLRDATA_ADDRESS* arg);

    virtual HRESULT STDMETHODCALLTYPE Request(
        /* [in] */ ULONG32 reqCode,
        /* [in] */ ULONG32 inBufferSize,
        /* [size_is][in] */ BYTE *inBuffer,
        /* [in] */ ULONG32 outBufferSize,
        /* [size_is][out] */ BYTE *outBuffer);

    HRESULT GetRefAssociatedValue(IXCLRDataValue** assocValue);

    static HRESULT NewFromFieldDesc(ClrDataAccess* dac,
                                    AppDomain* appDomain,
                                    ULONG32 flags,
                                    FieldDesc* fieldDesc,
                                    ULONG64 objBase,
                                    Thread* tlsThread,
                                    ClrDataValue** value,
                                    IXCLRDataValue** pubValue,
                                    ULONG32 nameBufRetLen,
                                    ULONG32* nameLenRet,
                                    __out_ecount_part_opt(nameBufRetLen, *nameLenRet) WCHAR nameBufRet[  ],
                                    IXCLRDataModule** tokenScopeRet,
                                    mdFieldDef* tokenRet);

    HRESULT NewFromSubField(FieldDesc* fieldDesc,
                            ULONG32 flags,
                            ClrDataValue** value,
                            IXCLRDataValue** pubValue,
                            ULONG32 nameBufRetLen,
                            ULONG32* nameLenRet,
                            __out_ecount_part_opt(nameBufRetLen, *nameLenRet) WCHAR nameBufRet[  ],
                            IXCLRDataModule** tokenScopeRet,
                            mdFieldDef* tokenRet)
    {
        return ClrDataValue::NewFromFieldDesc(m_dac,
                                              m_appDomain,
                                              flags,
                                              fieldDesc,
                                              m_baseAddr,
                                              m_thread,
                                              value,
                                              pubValue,
                                              nameBufRetLen,
                                              nameLenRet,
                                              nameBufRet,
                                              tokenScopeRet,
                                              tokenRet);
    }

    bool CanHaveFields(void)
    {
        return (m_flags & CLRDATA_VALUE_IS_REFERENCE) == 0;
    }

    HRESULT IntGetBytes(
        /* [in] */ ULONG32 bufLen,
        /* [size_is][out] */ BYTE buffer[  ]);

private:
    LONG m_refs;
    ClrDataAccess* m_dac;
    ULONG32 m_instanceAge;
    AppDomain* m_appDomain;
    Thread* m_thread;
    ULONG32 m_flags;
    TypeHandle m_typeHandle;
    ULONG64 m_totalSize;
    ULONG64 m_baseAddr;
    ULONG32 m_numLocs;
    NativeVarLocation m_locs[MAX_NATIVE_VAR_LOCS];
};

//----------------------------------------------------------------------------
//
// EnumMethodDefinitions.
//
//----------------------------------------------------------------------------

class EnumMethodDefinitions
{
public:
    HRESULT Start(Module* mod,
                  bool useAddrFilter,
                  CLRDATA_ADDRESS addrFilter);
    HRESULT Next(ClrDataAccess* dac,
                 IXCLRDataMethodDefinition **method);

    static HRESULT CdStart(Module* mod,
                           bool useAddrFilter,
                           CLRDATA_ADDRESS addrFilter,
                           CLRDATA_ENUM* handle);
    static HRESULT CdNext(ClrDataAccess* dac,
                          CLRDATA_ENUM* handle,
                          IXCLRDataMethodDefinition** method);
    static HRESULT CdEnd(CLRDATA_ENUM handle);

    Module* m_module;
    bool m_useAddrFilter;
    CLRDATA_ADDRESS m_addrFilter;
    MetaEnum m_typeEnum;
    mdToken m_typeToken;
    bool m_needMethodStart;
    MetaEnum m_methodEnum;
};

//----------------------------------------------------------------------------
//
// EnumMethodInstances.
//
//----------------------------------------------------------------------------

class EnumMethodInstances
{
public:
    EnumMethodInstances(MethodDesc* methodDesc,
                        IXCLRDataAppDomain* givenAppDomain);

    HRESULT Next(ClrDataAccess* dac,
                 IXCLRDataMethodInstance **instance);

    static HRESULT CdStart(MethodDesc* methodDesc,
                           IXCLRDataAppDomain* appDomain,
                           CLRDATA_ENUM* handle);
    static HRESULT CdNext(ClrDataAccess* dac,
                          CLRDATA_ENUM* handle,
                          IXCLRDataMethodInstance** method);
    static HRESULT CdEnd(CLRDATA_ENUM handle);

    MethodDesc* m_methodDesc;
    AppDomain* m_givenAppDomain;
    bool m_givenAppDomainUsed;
    AppDomainIterator m_domainIter;
    AppDomain* m_appDomain;
    LoadedMethodDescIterator m_methodIter;
};

//----------------------------------------------------------------------------
//
// Internal functions.
//
//----------------------------------------------------------------------------

#define DAC_ENTER() \
    EnterCriticalSection(&g_dacCritSec); \
    ClrDataAccess* __prevDacImpl = g_dacImpl; \
    g_dacImpl = this;

// When entering a child object we validate that
// the process's host instance cache hasn't been flushed
// since the child was created.
#define DAC_ENTER_SUB(dac) \
    EnterCriticalSection(&g_dacCritSec); \
    if (dac->m_instanceAge != m_instanceAge) \
    { \
        LeaveCriticalSection(&g_dacCritSec); \
        return E_INVALIDARG; \
    } \
    ClrDataAccess* __prevDacImpl = g_dacImpl; \
    g_dacImpl = (dac)

#define DAC_LEAVE() \
    g_dacImpl = __prevDacImpl; \
    LeaveCriticalSection(&g_dacCritSec)


#define SOSHelperEnter() \
    DAC_ENTER_SUB(mDac); \
    HRESULT hr = S_OK;   \
    EX_TRY               \
    {

#define SOSHelperLeave() \
    }                   \
    EX_CATCH            \
    {                   \
        if (!DacExceptionFilter(GET_EXCEPTION(), mDac, &hr)) \
        {               \
            EX_RETHROW; \
        }               \
    }                   \
    EX_END_CATCH(SwallowAllExceptions) \
    DAC_LEAVE();

HRESULT DacGetHostVtPtrs(void);
bool DacExceptionFilter(Exception* ex, ClrDataAccess* process,
                        HRESULT* status);
Thread* __stdcall DacGetThread(ULONG32 osThread);
BOOL DacGetThreadContext(Thread* thread, T_CONTEXT* context);

// Imports from request_svr.cpp, to provide data we need from the SVR namespace
int GCHeapCount();
HRESULT GetServerHeapData(CLRDATA_ADDRESS addr, DacpHeapSegmentData *pSegment);
HRESULT GetServerHeaps(CLRDATA_ADDRESS pGCHeaps[], ICorDebugDataTarget* pTarget);

#if defined(DAC_MEASURE_PERF)

#if defined(_TARGET_X86_)

// Assume Pentium CPU

#define CCNT_OVERHEAD_32  8
#define CCNT_OVERHEAD    13 

#pragma warning( disable: 4035 )        /* Don't complain about lack of return value */

__inline unsigned __int64 GetCycleCount ()
{
__asm   _emit   0x0F
__asm   _emit   0x31    /* rdtsc */
    // return EDX:EAX       causes annoying warning
};

__inline unsigned GetCycleCount32 ()  // enough for about 40 seconds
{
    LIMITED_METHOD_CONTRACT;
    
__asm   push    EDX
__asm   _emit   0x0F
__asm   _emit   0x31    /* rdtsc */
__asm   pop     EDX
    // return EAX       causes annoying warning
};

#pragma warning( default: 4035 )

#else // #if defined(_TARGET_X86_)

#define CCNT_OVERHEAD    0 // Don't know

__inline unsigned __int64 GetCycleCount()
{
    LIMITED_METHOD_CONTRACT;
    
    LARGE_INTEGER qwTmp;
    QueryPerformanceCounter(&qwTmp);
    return qwTmp.QuadPart;
}

#endif  // #if defined(_TARGET_X86_)

extern unsigned __int64 g_nTotalTime;
extern unsigned __int64 g_nStackTotalTime;
extern unsigned __int64 g_nReadVirtualTotalTime;
extern unsigned __int64 g_nFindTotalTime;
extern unsigned __int64 g_nFindHashTotalTime;
extern unsigned __int64 g_nFindHits;
extern unsigned __int64 g_nFindCalls;
extern unsigned __int64 g_nFindFails;
extern unsigned __int64 g_nStackWalk;
extern unsigned __int64 g_nFindStackTotalTime;

#endif // #if defined(DAC_MEASURE_PERF)

#endif // #ifndef __DACIMPL_H__