summaryrefslogtreecommitdiff
path: root/src/ToolBox/SOS/Strike/strike.cpp
blob: 2b54b4f03763cafed26376790e0474d688f712b4 (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
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

// ==++==
// 
 
// 
// ==--==

// ===========================================================================
// STRIKE.CPP
// ===========================================================================
//
// History:
//   09/07/99  Microsoft  Created
//
//************************************************************************************************
// SOS is the native debugging extension designed to support investigations into CLR (mis-)
// behavior by both users of the runtime as well as the code owners. It allows inspection of 
// internal structures, of user visible entities, as well as execution control.
// 
// This is the main SOS file hosting the implementation of all the exposed commands. A good 
// starting point for understanding the semantics of these commands is the sosdocs.txt file.
// 
// #CrossPlatformSOS
// SOS currently supports cross platform debugging from x86 to ARM. It takes a different approach 
// from the DAC: whereas for the DAC we produce one binary for each supported host-target 
// architecture pair, for SOS we produce only one binary for each host architecture; this one 
// binary contains code for all supported target architectures. In doing this SOS depends on two
// assumptions:
//   . that the debugger will load the appropriate DAC, and 
//   . that the host and target word size is identical.
// The second assumption is identical to the DAC assumption, and there will be considerable effort
// required (in the EE, the DAC, and SOS) if we ever need to remove it.
// 
// In an ideal world SOS would be able to retrieve all platform specific information it needs 
// either from the debugger or from DAC. However, SOS has taken some subtle and not so subtle
// dependencies on the CLR and the target platform.
// To resolve this problem, SOS now abstracts the target behind the IMachine interface, and uses 
// calls on IMachine to take target-specific actions. It implements X86Machine, ARMMachine, and 
// AMD64Machine. An instance of these exists in each appropriate host (e.g. the X86 version of SOS
// contains instaces of X86Machine and ARMMachine, the ARM version contains an instance of 
// ARMMachine, and the AMD64 version contains an instance of AMD64Machine). The code included in 
// each version if determined by the SosTarget*** MSBuild symbols, and SOS_TARGET_*** conditional 
// compilation symbols (as specified in sos.targets).
// 
// Most of the target specific code is hosted in disasm.h/.cpp, and disasmX86.cpp, disasmARM.cpp.
// Some code currently under _TARGET_*** ifdefs may need to be reviewed/revisited.
// 
// Issues:
// The one-binary-per-host decision does have some drawbacks: 
//   . Currently including system headers or even CLR headers will only account for the host 
//     target, IOW, when building the X86 version of SOS, CONTEXT will refer to the X86 CONTEXT 
//     structure, so we need to be careful when debugging ARM targets. The CONTEXT issue is 
//     partially resolved by CROSS_PLATFORM_CONTEXT (there is still a need to be very careful 
//     when handling arrays of CONTEXTs - see _EFN_StackTrace for details on this).
//   . For larger includes (e.g. GC info), we will need to include files in specific namespaces, 
//     with specific _TARGET_*** macros defined in order to avoid name clashes and ensure correct
//     system types are used.
// -----------------------------------------------------------------------------------------------

#define DO_NOT_DISABLE_RAND //this is a standalone tool, and can use rand()

#include <windows.h>
#include <winver.h>
#include <winternl.h>
#include <psapi.h>
#ifndef FEATURE_PAL
#include <list>   
#endif // !FEATURE_PAL
#include <wchar.h>

#include "platformspecific.h"

#define NOEXTAPI
#define KDEXT_64BIT
#include <wdbgexts.h>
#undef DECLARE_API
#undef StackTrace

#include <dbghelp.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

#include "strike.h"
#include "sos.h"

#ifndef STRESS_LOG
#define STRESS_LOG
#endif // STRESS_LOG
#define STRESS_LOG_READONLY
#include "stresslog.h"

#include "util.h"

#include "corhdr.h"
#include "cor.h"
#include "cordebug.h"
#include "dacprivate.h"
#include "corexcep.h"

#define  CORHANDLE_MASK 0x1
#define SWITCHED_OUT_FIBER_OSID 0xbaadf00d;

#define DEFINE_EXT_GLOBALS

#include "data.h"
#include "disasm.h"

#include "predeftlsslot.h"

#include "hillclimbing.h"

#include "sos_md.h"

#ifndef FEATURE_PAL

#include "ExpressionNode.h"
#include "WatchCmd.h"

#include <set>
#include <algorithm>
#include <vector>

#include "tls.h"

typedef struct _VM_COUNTERS {
    SIZE_T PeakVirtualSize;
    SIZE_T VirtualSize;
    ULONG PageFaultCount;
    SIZE_T PeakWorkingSetSize;
    SIZE_T WorkingSetSize;
    SIZE_T QuotaPeakPagedPoolUsage;
    SIZE_T QuotaPagedPoolUsage;
    SIZE_T QuotaPeakNonPagedPoolUsage;
    SIZE_T QuotaNonPagedPoolUsage;
    SIZE_T PagefileUsage;
    SIZE_T PeakPagefileUsage;
} VM_COUNTERS;
typedef VM_COUNTERS *PVM_COUNTERS;

const PROCESSINFOCLASS ProcessVmCounters = static_cast<PROCESSINFOCLASS>(3);

#endif // !FEATURE_PAL

BOOL CallStatus;
BOOL ControlC = FALSE;

IMetaDataDispenserEx *pDisp = NULL;
WCHAR g_mdName[mdNameLen];

#ifndef FEATURE_PAL
HMODULE g_hInstance = NULL;
#include <vector>
#include <algorithm>
#endif // !FEATURE_PAL

#ifdef _MSC_VER
#pragma warning(disable:4244)   // conversion from 'unsigned int' to 'unsigned short', possible loss of data
#pragma warning(disable:4189)   // local variable is initialized but not referenced
#endif

#ifdef FEATURE_PAL
#define SOSPrefix ""
#else
#define SOSPrefix "!"
#endif

#if defined _X86_ && !defined FEATURE_PAL
// disable FPO for X86 builds
#pragma optimize("y", off)
#endif

#undef assert

#ifdef _MSC_VER
#pragma warning(default:4244)
#pragma warning(default:4189)
#endif

#ifndef FEATURE_PAL
#include "ntinfo.h"
#endif // FEATURE_PAL

#ifndef IfFailRet
#define IfFailRet(EXPR) do { Status = (EXPR); if(FAILED(Status)) { return (Status); } } while (0)
#endif

#ifdef FEATURE_PAL

#define NOTHROW
#define MINIDUMP_NOT_SUPPORTED()

#else // !FEATURE_PAL

#define MINIDUMP_NOT_SUPPORTED()   \
    if (IsMiniDumpFile())      \
    {                          \
        ExtOut("This command is not supported in a minidump without full memory\n"); \
        ExtOut("To try the command anyway, run !MinidumpMode 0\n"); \
        return Status;         \
    }

#define NOTHROW (std::nothrow)

#include "safemath.h"

DECLARE_API (MinidumpMode)
{
    INIT_API ();
    DWORD_PTR Value=0;

    CMDValue arg[] = 
    {   // vptr, type
        {&Value, COHEX}
    };

    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg)) 
    {
        return Status;
    }    
    if (nArg == 0)
    {
        // Print status of current mode
       ExtOut("Current mode: %s - unsafe minidump commands are %s.\n",
               g_InMinidumpSafeMode ? "1" : "0",
               g_InMinidumpSafeMode ? "disabled" : "enabled");
    }
    else
    {
        if (Value != 0 && Value != 1)
        {
            ExtOut("Mode must be 0 or 1\n");
            return Status;
        }

        g_InMinidumpSafeMode = (BOOL) Value;
        ExtOut("Unsafe minidump commands are %s.\n",
                g_InMinidumpSafeMode ? "disabled" : "enabled");
    }

    return Status;
}

#endif // FEATURE_PAL

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to get the MethodDesc for a given eip     *  
*                                                                      *
\**********************************************************************/
DECLARE_API(IP2MD)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();

    BOOL dml = FALSE;
    TADDR IP = 0;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&IP, COHEX},
    };
    size_t nArg;
    
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    EnableDMLHolder dmlHolder(dml);

    if (IP == 0)
    {
        ExtOut("%s is not IP\n", args);
        return Status;
    }

    CLRDATA_ADDRESS cdaStart = TO_CDADDR(IP);
    CLRDATA_ADDRESS pMD;

    
    if ((Status = g_sos->GetMethodDescPtrFromIP(cdaStart, &pMD)) != S_OK)
    {
        ExtOut("Failed to request MethodData, not in JIT code range\n");
        return Status;
    }

    DMLOut("MethodDesc:   %s\n", DMLMethodDesc(pMD));
    DumpMDInfo(TO_TADDR(pMD), cdaStart, FALSE /* fStackTraceFormat */);

    WCHAR filename[MAX_LONGPATH];
    ULONG linenum;
    // symlines will be non-zero only if SYMOPT_LOAD_LINES was set in the symbol options
    ULONG symlines = 0;
    if (SUCCEEDED(g_ExtSymbols->GetSymbolOptions(&symlines)))
    {
        symlines &= SYMOPT_LOAD_LINES;
    }

    if (symlines != 0 && 
        SUCCEEDED(GetLineByOffset(TO_CDADDR(IP), &linenum, filename, _countof(filename))))
    {
        ExtOut("Source file:  %S @ %d\n", filename, linenum);
    }

    return Status;
}

// (MAX_STACK_FRAMES is also used by x86 to prevent infinite loops in _EFN_StackTrace)
#define MAX_STACK_FRAMES 1000

#ifdef _TARGET_WIN64_

// I use a global set of frames for stack walking on win64 because the debugger's
// GetStackTrace function doesn't provide a way to find out the total size of a stackwalk,
// and I'd like to have a reasonably big maximum without overflowing the stack by declaring
// the buffer locally and I also want to get a managed trace in a low memory environment
// (so no dynamic allocation if possible).
DEBUG_STACK_FRAME g_Frames[MAX_STACK_FRAMES];
AMD64_CONTEXT g_X64FrameContexts[MAX_STACK_FRAMES];

static HRESULT
GetContextStackTrace(PULONG pnumFrames)
{
    PDEBUG_CONTROL4 debugControl4;
    HRESULT hr;

    // Do we have advanced capability?
    if ((hr = g_ExtControl->QueryInterface(__uuidof(IDebugControl4), (void **)&debugControl4)) == S_OK)
    {
        // GetContextStackTrace fills g_X64FrameContexts as an array of 
        // contexts packed as target architecture contexts. We cannot 
        // safely cast this as an array of CROSS_PLATFORM_CONTEXT, since 
        // sizeof(CROSS_PLATFORM_CONTEXT) != sizeof(TGT_CONTEXT)
        hr = debugControl4->GetContextStackTrace(
            NULL,
            0,
            g_Frames,
            MAX_STACK_FRAMES,
            g_X64FrameContexts,
            MAX_STACK_FRAMES*g_targetMachine->GetContextSize(),
            g_targetMachine->GetContextSize(),
            pnumFrames);

        debugControl4->Release();
    }
    return hr;
}

#endif // _TARGET_WIN64_

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function displays the stack trace.  It looks at each DWORD   *  
*    on stack.  If the DWORD is a return address, the symbol name or
*    managed function name is displayed.                               *
*                                                                      *
\**********************************************************************/
void DumpStackInternal(DumpStackFlag *pDSFlag)
{    
    ReloadSymbolWithLineInfo();
    
    ULONG64 StackOffset;
    g_ExtRegisters->GetStackOffset (&StackOffset);
    if (pDSFlag->top == 0) {
        pDSFlag->top = TO_TADDR(StackOffset);
    }
    size_t value;
    while (g_ExtData->ReadVirtual(TO_CDADDR(pDSFlag->top), &value, sizeof(size_t), NULL) != S_OK) {
        if (IsInterrupt())
            return;
        pDSFlag->top = NextOSPageAddress(pDSFlag->top);
    }

#ifndef FEATURE_PAL     
    if (pDSFlag->end == 0) {
        // Find the current stack range
        NT_TIB teb;
        ULONG64 dwTebAddr=0;

        g_ExtSystem->GetCurrentThreadTeb(&dwTebAddr);
        if (SafeReadMemory(TO_TADDR(dwTebAddr), &teb, sizeof(NT_TIB), NULL))
        {
            if (pDSFlag->top > TO_TADDR(teb.StackLimit)
            && pDSFlag->top <= TO_TADDR(teb.StackBase))
            {
                if (pDSFlag->end == 0 || pDSFlag->end > TO_TADDR(teb.StackBase))
                    pDSFlag->end = TO_TADDR(teb.StackBase);
            }
        }
    }
#endif // FEATURE_PAL
    
    if (pDSFlag->end == 0)
    {
        ExtOut("TEB information is not available so a stack size of 0xFFFF is assumed\n");
        pDSFlag->end = pDSFlag->top + 0xFFFF;
    }
    
    if (pDSFlag->end < pDSFlag->top)
    {
        ExtOut("Wrong option: stack selection wrong\n");
        return;
    }

    DumpStackWorker(*pDSFlag);
}


DECLARE_API(DumpStack)
{
    INIT_API_NO_RET_ON_FAILURE();

    MINIDUMP_NOT_SUPPORTED();

    DumpStackFlag DSFlag;
    DSFlag.fEEonly = FALSE;
    DSFlag.fSuppressSrcInfo = FALSE;
    DSFlag.top = 0;
    DSFlag.end = 0;

    BOOL dml = FALSE;
    CMDOption option[] = {
        // name, vptr, type, hasValue
        {"-EE", &DSFlag.fEEonly, COBOOL, FALSE},
        {"-n",  &DSFlag.fSuppressSrcInfo, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };
    CMDValue arg[] = {
        // vptr, type
        {&DSFlag.top, COHEX},
        {&DSFlag.end, COHEX}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
        return Status;

    // symlines will be non-zero only if SYMOPT_LOAD_LINES was set in the symbol options
    ULONG symlines = 0;
    if (!DSFlag.fSuppressSrcInfo && SUCCEEDED(g_ExtSymbols->GetSymbolOptions(&symlines)))
    {
        symlines &= SYMOPT_LOAD_LINES;
    }
    DSFlag.fSuppressSrcInfo = DSFlag.fSuppressSrcInfo || (symlines == 0);

    EnableDMLHolder enabledml(dml);

    ULONG id = 0;
    g_ExtSystem->GetCurrentThreadSystemId(&id);
    ExtOut("OS Thread Id: 0x%x ", id);
    g_ExtSystem->GetCurrentThreadId(&id);
    ExtOut("(%d)\n", id);

    DumpStackInternal(&DSFlag);
    return Status;
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function displays the stack trace for threads that EE knows  *  
*    from ThreadStore.                                                 *
*                                                                      *
\**********************************************************************/
DECLARE_API (EEStack)
{
    INIT_API();    

    MINIDUMP_NOT_SUPPORTED();  

    DumpStackFlag DSFlag;
    DSFlag.fEEonly = FALSE;
    DSFlag.fSuppressSrcInfo = FALSE;
    DSFlag.top = 0;
    DSFlag.end = 0;

    BOOL bShortList = FALSE;
    BOOL dml = FALSE;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-EE", &DSFlag.fEEonly, COBOOL, FALSE},
        {"-short", &bShortList, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };    

    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
    {
        return Status;
    }

    EnableDMLHolder enableDML(dml);

    ULONG Tid;
    g_ExtSystem->GetCurrentThreadId(&Tid);

    DacpThreadStoreData ThreadStore;
    if ((Status = ThreadStore.Request(g_sos)) != S_OK)
    {
        ExtOut("Failed to request ThreadStore\n");
        return Status;
    }    

    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread)
    {
        if (IsInterrupt())
            break;

        DacpThreadData Thread;        
        if ((Status = Thread.Request(g_sos, CurThread)) != S_OK)
        {
            ExtOut("Failed to request Thread at %p\n", CurThread);
            return Status;
        }

        ULONG id=0;
        if (g_ExtSystem->GetThreadIdBySystemId (Thread.osThreadId, &id) != S_OK)
        {
            CurThread = Thread.nextThread;    
            continue;
        }
        
        ExtOut("---------------------------------------------\n");
        ExtOut("Thread %3d\n", id);
        BOOL doIt = FALSE;

        
#define TS_Hijacked 0x00000080

        if (!bShortList) 
        {
            doIt = TRUE;
        }
        else if ((Thread.lockCount > 0) || (Thread.state & TS_Hijacked)) 
        {             
            // TODO: bring back || (int)vThread.m_pFrame != -1  {
            doIt = TRUE;
        }
        else 
        {
            ULONG64 IP;
            g_ExtRegisters->GetInstructionOffset (&IP);
            JITTypes jitType;
            TADDR methodDesc;
            TADDR gcinfoAddr;
            IP2MethodDesc (TO_TADDR(IP), methodDesc, jitType, gcinfoAddr);
            if (methodDesc)
            {
                doIt = TRUE;
            }
        }
        
        if (doIt) 
        {
            g_ExtSystem->SetCurrentThreadId(id);
            DSFlag.top = 0;
            DSFlag.end = 0;
            DumpStackInternal(&DSFlag);
        }

        CurThread = Thread.nextThread;
    }

    g_ExtSystem->SetCurrentThreadId(Tid);
    return Status;
}

HRESULT DumpStackObjectsRaw(size_t nArg, __in_z LPSTR exprBottom, __in_z LPSTR exprTop, BOOL bVerify)
{
    size_t StackTop = 0;
    size_t StackBottom = 0;
    if (nArg==0)
    {
        ULONG64 StackOffset;
        g_ExtRegisters->GetStackOffset(&StackOffset);

        StackTop = TO_TADDR(StackOffset);
    }
    else
    {
        StackTop = GetExpression(exprTop);
        if (StackTop == 0)
        {
            ExtOut("wrong option: %s\n", exprTop);
            return E_FAIL;
        }

        if (nArg==2)
        {
            StackBottom = GetExpression(exprBottom);
            if (StackBottom == 0)
            {
                ExtOut("wrong option: %s\n", exprBottom);
                return E_FAIL;
            }
        }
    }
    
#ifndef FEATURE_PAL
    NT_TIB teb;
    ULONG64 dwTebAddr=0;
    HRESULT hr = g_ExtSystem->GetCurrentThreadTeb(&dwTebAddr);
    if (SUCCEEDED(hr) && SafeReadMemory (TO_TADDR(dwTebAddr), &teb, sizeof (NT_TIB), NULL))
    {
        if (StackTop > TO_TADDR(teb.StackLimit) && StackTop <= TO_TADDR(teb.StackBase))
        {
            if (StackBottom == 0 || StackBottom > TO_TADDR(teb.StackBase))
                StackBottom = TO_TADDR(teb.StackBase);
        }
    }
#endif
    
    if (StackBottom == 0)
        StackBottom = StackTop + 0xFFFF;
    
    if (StackBottom < StackTop)
    {
        ExtOut("Wrong option: stack selection wrong\n");
        return E_FAIL;
    }

    // We can use the gc snapshot to eliminate object addresses that are
    // not on the gc heap. 
    if (!g_snapshot.Build())
    {
        ExtOut("Unable to determine bounds of gc heap\n");
        return E_FAIL;
    }   

    // Print thread ID.
    ULONG id = 0;
    g_ExtSystem->GetCurrentThreadSystemId (&id);
    ExtOut("OS Thread Id: 0x%x ", id);
    g_ExtSystem->GetCurrentThreadId (&id);
    ExtOut("(%d)\n", id);
    
    DumpStackObjectsHelper(StackTop, StackBottom, bVerify);
    return S_OK;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the address and name of all       *
*    Managed Objects on the stack.                                     *  
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpStackObjects)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    StringHolder exprTop, exprBottom;

    BOOL bVerify = FALSE;
    BOOL dml = FALSE;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-verify", &bVerify, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };    
    CMDValue arg[] = 
    {   // vptr, type
        {&exprTop.data, COSTRING},
        {&exprBottom.data, COSTRING}
    };
    size_t nArg;

    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder enableDML(dml);
    
    return DumpStackObjectsRaw(nArg, exprBottom.data, exprTop.data, bVerify);
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a MethodDesc      *
*    for a given address                                               *  
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpMD)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    
    DWORD_PTR dwStartAddr = NULL;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&dwStartAddr, COHEX},
    };
    size_t nArg;

    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    
    DumpMDInfo(dwStartAddr);
    
    return Status;
}

BOOL GatherDynamicInfo(TADDR DynamicMethodObj, DacpObjectData *codeArray, 
                       DacpObjectData *tokenArray, TADDR *ptokenArrayAddr)
{
    BOOL bRet = FALSE;
    int iOffset;
    DacpObjectData objData; // temp object

    if (codeArray == NULL || tokenArray == NULL)
        return bRet;
    
    if (objData.Request(g_sos, TO_CDADDR(DynamicMethodObj)) != S_OK)
        return bRet;
    
    iOffset = GetObjFieldOffset(DynamicMethodObj, objData.MethodTable, W("m_resolver"));
    if (iOffset <= 0)
        return bRet;
    
    TADDR resolverPtr;
    if (FAILED(MOVE(resolverPtr, DynamicMethodObj + iOffset)))
        return bRet;

    if (objData.Request(g_sos, TO_CDADDR(resolverPtr)) != S_OK)
        return bRet;
    
    iOffset = GetObjFieldOffset(resolverPtr, objData.MethodTable, W("m_code"));
    if (iOffset <= 0)
        return bRet;

    TADDR codePtr;
    if (FAILED(MOVE(codePtr, resolverPtr + iOffset)))
        return bRet;

    if (codeArray->Request(g_sos, TO_CDADDR(codePtr)) != S_OK)
        return bRet;
    
    if (codeArray->dwComponentSize != 1)
        return bRet;
        
    // We also need the resolution table
    iOffset = GetObjFieldOffset (resolverPtr, objData.MethodTable, W("m_scope"));
    if (iOffset <= 0)
        return bRet;

    TADDR scopePtr;
    if (FAILED(MOVE(scopePtr, resolverPtr + iOffset)))
        return bRet;

    if (objData.Request(g_sos, TO_CDADDR(scopePtr)) != S_OK)
        return bRet;
    
    iOffset = GetObjFieldOffset (scopePtr, objData.MethodTable, W("m_tokens"));
    if (iOffset <= 0)
        return bRet;

    TADDR tokensPtr;
    if (FAILED(MOVE(tokensPtr, scopePtr + iOffset)))
        return bRet;

    if (objData.Request(g_sos, TO_CDADDR(tokensPtr)) != S_OK)
        return bRet;
    
    iOffset = GetObjFieldOffset(tokensPtr, objData.MethodTable, W("_items"));
    if (iOffset <= 0)
        return bRet;

    TADDR itemsPtr;
    MOVE (itemsPtr, tokensPtr + iOffset);

    *ptokenArrayAddr = itemsPtr;
    
    if (tokenArray->Request(g_sos, TO_CDADDR(itemsPtr)) != S_OK)
        return bRet;

    bRet = TRUE; // whew.
    return bRet;
}

DECLARE_API(DumpIL)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    DWORD_PTR dwStartAddr = NULL;
    DWORD_PTR dwDynamicMethodObj = NULL;
    BOOL dml = FALSE;
    BOOL fILPointerDirectlySpecified = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
        {"/i", &fILPointerDirectlySpecified, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&dwStartAddr, COHEX},
    };
    size_t nArg;

    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);    
    if (dwStartAddr == NULL)
    {
        ExtOut("Must pass a valid expression\n");
        return Status;
    }

    if (fILPointerDirectlySpecified)
    {
        return DecodeILFromAddress(NULL, dwStartAddr);
    }

    if (!g_snapshot.Build())
    {
        ExtOut("Unable to build snapshot of the garbage collector state\n");
        return Status;
    }

    if (g_snapshot.GetHeap(dwStartAddr) != NULL)
    {
        dwDynamicMethodObj = dwStartAddr;
    }
    
    if (dwDynamicMethodObj == NULL)
    {
        // We have been given a MethodDesc
        DacpMethodDescData MethodDescData;
        if (MethodDescData.Request(g_sos, TO_CDADDR(dwStartAddr)) != S_OK)
        {
            ExtOut("%p is not a MethodDesc\n", SOS_PTR(dwStartAddr));
            return Status;
        }

        if (MethodDescData.bIsDynamic && MethodDescData.managedDynamicMethodObject)
        {
            dwDynamicMethodObj = TO_TADDR(MethodDescData.managedDynamicMethodObject);
            if (dwDynamicMethodObj == NULL)
            {
                ExtOut("Unable to print IL for DynamicMethodDesc %p\n", SOS_PTR(dwDynamicMethodObj));
                return Status;
            }
        }
        else
        {
            // This is not a dynamic method, print the IL for it.
            // Get the module
            DacpModuleData dmd;    
            if (dmd.Request(g_sos, MethodDescData.ModulePtr) != S_OK)
            {
                ExtOut("Unable to get module\n");
                return Status;
            }

            ToRelease<IMetaDataImport> pImport = MDImportForModule(&dmd);
            if (pImport == NULL)
            {
                ExtOut("bad import\n");
                return Status;
            }

            ULONG pRva;
            DWORD dwFlags;
            if (pImport->GetRVA(MethodDescData.MDToken, &pRva, &dwFlags) != S_OK)
            {
                ExtOut("error in import\n");
                return Status;
            }    

            CLRDATA_ADDRESS ilAddrClr;
            if (g_sos->GetILForModule(MethodDescData.ModulePtr, pRva, &ilAddrClr) != S_OK)
            {
                ExtOut("FindIL failed\n");
                return Status;
            }

            TADDR ilAddr = TO_TADDR(ilAddrClr);
            IfFailRet(DecodeILFromAddress(pImport, ilAddr));
        }
    }
    
    if (dwDynamicMethodObj != NULL)
    {
        // We have a DynamicMethod managed object, let us visit the town and paint.        
        DacpObjectData codeArray;
        DacpObjectData tokenArray;
        DWORD_PTR tokenArrayAddr;
        if (!GatherDynamicInfo (dwDynamicMethodObj, &codeArray, &tokenArray, &tokenArrayAddr))
        {
            DMLOut("Error gathering dynamic info from object at %s.\n", DMLObject(dwDynamicMethodObj));
            return Status;
        }
        
        // Read the memory into a local buffer
        BYTE *pArray = new NOTHROW BYTE[(SIZE_T)codeArray.dwNumComponents];
        if (pArray == NULL)
        {
            ExtOut("Not enough memory to read IL\n");
            return Status;
        }
        
        Status = g_ExtData->ReadVirtual(UL64_TO_CDA(codeArray.ArrayDataPtr), pArray, (ULONG)codeArray.dwNumComponents, NULL);
        if (Status != S_OK)
        {
            ExtOut("Failed to read memory\n");
            delete [] pArray;
            return Status;
        }

        // Now we have a local copy of the IL, and a managed array for token resolution.
        // Visit our IL parser with this info.        
        ExtOut("This is dynamic IL. Exception info is not reported at this time.\n");
        ExtOut("If a token is unresolved, run \"!do <addr>\" on the addr given\n");
        ExtOut("in parenthesis. You can also look at the token table yourself, by\n");
        ExtOut("running \"!DumpArray %p\".\n\n", SOS_PTR(tokenArrayAddr));
        DecodeDynamicIL(pArray, (ULONG)codeArray.dwNumComponents, tokenArray);
        
        delete [] pArray;                
    }    
    return Status;
}

void DumpSigWorker (
        DWORD_PTR dwSigAddr,
        DWORD_PTR dwModuleAddr,
        BOOL fMethod)
{
    //
    // Find the length of the signature and copy it into the debugger process.
    //

    ULONG cbSig = 0;
    const ULONG cbSigInc = 256;
    ArrayHolder<COR_SIGNATURE> pSig = new NOTHROW COR_SIGNATURE[cbSigInc];
    if (pSig == NULL)
    {
        ReportOOM();        
        return;
    }
    
    CQuickBytes sigString;
    for (;;)
    {
        if (IsInterrupt())
            return;

        ULONG cbCopied;
        if (!SafeReadMemory(TO_TADDR(dwSigAddr + cbSig), pSig + cbSig, cbSigInc, &cbCopied))
            return;
        cbSig += cbCopied;

        sigString.ReSize(0);
        GetSignatureStringResults result;
        if (fMethod)
            result = GetMethodSignatureString(pSig, cbSig, dwModuleAddr, &sigString);
        else
            result = GetSignatureString(pSig, cbSig, dwModuleAddr, &sigString);

        if (GSS_ERROR == result)
            return;

        if (GSS_SUCCESS == result)
            break;

        // If we didn't get the full amount back, and we failed to parse the
        // signature, it's not valid because of insufficient data
        if (cbCopied < 256)
        {
            ExtOut("Invalid signature\n");
            return;
        }

#ifdef _PREFAST_
#pragma warning(push)
#pragma warning(disable:6280) // "Suppress PREFast warning about mismatch alloc/free"
#endif

        PCOR_SIGNATURE pSigNew = (PCOR_SIGNATURE)realloc(pSig, cbSig+cbSigInc);

#ifdef _PREFAST_
#pragma warning(pop)
#endif

        if (pSigNew == NULL)
        {
            ExtOut("Out of memory\n");
            return;
        }
        
        pSig = pSigNew;
    }

    ExtOut("%S\n", (PCWSTR)sigString.Ptr());
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump a signature object.               *
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpSig)
{
    INIT_API();

    MINIDUMP_NOT_SUPPORTED();
    
    //
    // Fetch arguments
    //

    StringHolder sigExpr;
    StringHolder moduleExpr;
    CMDValue arg[] = 
    {
        {&sigExpr.data, COSTRING},
        {&moduleExpr.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg))
    {
        return Status;
    }
    if (nArg != 2)
    {
        ExtOut("!DumpSig <sigaddr> <moduleaddr>\n");
        return Status;
    }

    DWORD_PTR dwSigAddr = GetExpression(sigExpr.data);        
    DWORD_PTR dwModuleAddr = GetExpression(moduleExpr.data);

    if (dwSigAddr == 0 || dwModuleAddr == 0)
    {
        ExtOut("Invalid parameters %s %s\n", sigExpr.data, moduleExpr.data);
        return Status;
    }
    
    DumpSigWorker(dwSigAddr, dwModuleAddr, TRUE);
    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump a portion of a signature object.  *
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpSigElem)
{
    INIT_API();

    MINIDUMP_NOT_SUPPORTED();
    

    //
    // Fetch arguments
    //

    StringHolder sigExpr;
    StringHolder moduleExpr;
    CMDValue arg[] = 
    {
        {&sigExpr.data, COSTRING},
        {&moduleExpr.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg))
    {
        return Status;
    }

    if (nArg != 2)
    {
        ExtOut("!DumpSigElem <sigaddr> <moduleaddr>\n");
        return Status;
    }

    DWORD_PTR dwSigAddr = GetExpression(sigExpr.data);        
    DWORD_PTR dwModuleAddr = GetExpression(moduleExpr.data);

    if (dwSigAddr == 0 || dwModuleAddr == 0)
    {
        ExtOut("Invalid parameters %s %s\n", sigExpr.data, moduleExpr.data);
        return Status;
    }

    DumpSigWorker(dwSigAddr, dwModuleAddr, FALSE);
    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of an EEClass from   *  
*    a given address
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpClass)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    
    DWORD_PTR dwStartAddr = 0;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&dwStartAddr, COHEX}
    };

    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    if (nArg == 0) 
    {
        ExtOut("Missing EEClass address\n");
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);

    CLRDATA_ADDRESS methodTable;
    if ((Status=g_sos->GetMethodTableForEEClass(TO_CDADDR(dwStartAddr), &methodTable)) != S_OK)
    {
        ExtOut("Invalid EEClass address\n");
        return Status;
    }

    DacpMethodTableData mtdata;
    if ((Status=mtdata.Request(g_sos, TO_CDADDR(methodTable)))!=S_OK)
    {
        ExtOut("EEClass has an invalid MethodTable address\n");
        return Status;
    }            

    sos::MethodTable mt = TO_TADDR(methodTable);
    ExtOut("Class Name:      %S\n", mt.GetName());

    WCHAR fileName[MAX_LONGPATH];
    FileNameForModule(TO_TADDR(mtdata.Module), fileName);
    ExtOut("mdToken:         %p\n", mtdata.cl);
    ExtOut("File:            %S\n", fileName);

    CLRDATA_ADDRESS ParentEEClass = NULL;
    if (mtdata.ParentMethodTable)
    {
        DacpMethodTableData mtdataparent;
        if ((Status=mtdataparent.Request(g_sos, TO_CDADDR(mtdata.ParentMethodTable)))!=S_OK)
        {
            ExtOut("EEClass has an invalid MethodTable address\n");
            return Status;
        }                     
        ParentEEClass = mtdataparent.Class;
    }

    DMLOut("Parent Class:    %s\n", DMLClass(ParentEEClass));
    DMLOut("Module:          %s\n", DMLModule(mtdata.Module));
    DMLOut("Method Table:    %s\n", DMLMethodTable(methodTable));
    ExtOut("Vtable Slots:    %x\n", mtdata.wNumVirtuals);
    ExtOut("Total Method Slots:  %x\n", mtdata.wNumVtableSlots);
    ExtOut("Class Attributes:    %x  ", mtdata.dwAttrClass);

    if (IsTdInterface(mtdata.dwAttrClass))
        ExtOut("Interface, ");
    if (IsTdAbstract(mtdata.dwAttrClass))
        ExtOut("Abstract, ");
    if (IsTdImport(mtdata.dwAttrClass))
        ExtOut("ComImport, ");
    
    ExtOut("\n");        

    DacpMethodTableTransparencyData transparency;
    if (SUCCEEDED(transparency.Request(g_sos, methodTable)))
    {
        ExtOut("Transparency:        %s\n", GetTransparency(transparency));
    }

    DacpMethodTableFieldData vMethodTableFields;
    if (SUCCEEDED(vMethodTableFields.Request(g_sos, methodTable)))
    {
        ExtOut("NumInstanceFields:   %x\n", vMethodTableFields.wNumInstanceFields);
        ExtOut("NumStaticFields:     %x\n", vMethodTableFields.wNumStaticFields);

        if (vMethodTableFields.wNumThreadStaticFields != 0)
        {
            ExtOut("NumThreadStaticFields: %x\n", vMethodTableFields.wNumThreadStaticFields);
        }


        if (vMethodTableFields.wContextStaticsSize)
        {
            ExtOut("ContextStaticOffset: %x\n", vMethodTableFields.wContextStaticOffset);
            ExtOut("ContextStaticsSize:  %x\n", vMethodTableFields.wContextStaticsSize);
        }

    
        if (vMethodTableFields.wNumInstanceFields + vMethodTableFields.wNumStaticFields > 0)
        {
            DisplayFields(methodTable, &mtdata, &vMethodTableFields, NULL, TRUE, FALSE);
        }
    }

    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a MethodTable     *  
*    from a given address                                              *
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpMT)
{
    DWORD_PTR dwStartAddr=0;
    DWORD_PTR dwOriginalAddr;
    
    INIT_API();

    MINIDUMP_NOT_SUPPORTED();
    
    BOOL bDumpMDTable = FALSE;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-MD", &bDumpMDTable, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&dwStartAddr, COHEX}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    TableOutput table(2, 16, AlignLeft, false);

    if (nArg == 0)
    {
        Print("Missing MethodTable address\n");
        return Status;
    }

    dwOriginalAddr = dwStartAddr;
    dwStartAddr = dwStartAddr&~3;
    
    if (!IsMethodTable(dwStartAddr))
    {
        Print(dwOriginalAddr, " is not a MethodTable\n");
        return Status;
    }
 
    DacpMethodTableData vMethTable;
    vMethTable.Request(g_sos, TO_CDADDR(dwStartAddr));    

    if (vMethTable.bIsFree) 
    {
        Print("Free MethodTable\n");
        return Status;
    }

    table.WriteRow("EEClass:", EEClassPtr(vMethTable.Class));

    table.WriteRow("Module:", ModulePtr(vMethTable.Module));

    sos::MethodTable mt = (TADDR)dwStartAddr;
    table.WriteRow("Name:", mt.GetName());

    WCHAR fileName[MAX_LONGPATH];
    FileNameForModule(TO_TADDR(vMethTable.Module), fileName);
    table.WriteRow("mdToken:", Pointer(vMethTable.cl));
    table.WriteRow("File:", fileName[0] ? fileName : W("Unknown Module"));

    table.WriteRow("BaseSize:", PrefixHex(vMethTable.BaseSize));
    table.WriteRow("ComponentSize:", PrefixHex(vMethTable.ComponentSize));
    table.WriteRow("Slots in VTable:", Decimal(vMethTable.wNumMethods));
    
    table.SetColWidth(0, 29);
    table.WriteRow("Number of IFaces in IFaceMap:", Decimal(vMethTable.wNumInterfaces));

    if (bDumpMDTable)
    {
        table.ReInit(4, POINTERSIZE_HEX, AlignRight);
        table.SetColAlignment(3, AlignLeft);
        table.SetColWidth(2, 6);

        Print("--------------------------------------\n");
        Print("MethodDesc Table\n");

        table.WriteRow("Entry", "MethodDesc", "JIT", "Name");

        for (DWORD n = 0; n < vMethTable.wNumMethods; n++)
        {
            JITTypes jitType;
            DWORD_PTR methodDesc=0;
            DWORD_PTR gcinfoAddr;

            CLRDATA_ADDRESS entry;
            if (g_sos->GetMethodTableSlot(dwStartAddr, n, &entry) != S_OK)
            {
                PrintLn("<error getting slot ", Decimal(n), ">");
                continue;
            }

            IP2MethodDesc((DWORD_PTR)entry, methodDesc, jitType, gcinfoAddr);
            table.WriteColumn(0, entry);
            table.WriteColumn(1, MethodDescPtr(methodDesc));

            if (jitType == TYPE_UNKNOWN && methodDesc != NULL)
            {
                // We can get a more accurate jitType from NativeCodeAddr of the methoddesc,
                // because the methodtable entry hasn't always been patched.
                DacpMethodDescData tmpMethodDescData;
                if (tmpMethodDescData.Request(g_sos, TO_CDADDR(methodDesc)) == S_OK)
                {
                    DacpCodeHeaderData codeHeaderData;                        
                    if (codeHeaderData.Request(g_sos,tmpMethodDescData.NativeCodeAddr) == S_OK)
                    {        
                        jitType = (JITTypes) codeHeaderData.JITType;
                    }
                }
            }

            const char *pszJitType = "NONE";
            if (jitType == TYPE_JIT)
                pszJitType = "JIT";
            else if (jitType == TYPE_PJIT)
                pszJitType = "PreJIT";
            else
            {
                DacpMethodDescData MethodDescData;
                if (MethodDescData.Request(g_sos, TO_CDADDR(methodDesc)) == S_OK)
                {
                    // Is it an fcall?
                    if ((TO_TADDR(MethodDescData.NativeCodeAddr) >=  TO_TADDR(moduleInfo[MSCORWKS].baseAddr)) &&
                        ((TO_TADDR(MethodDescData.NativeCodeAddr) <  TO_TADDR(moduleInfo[MSCORWKS].baseAddr + moduleInfo[MSCORWKS].size))))
                    {
                        pszJitType = "FCALL";
                    }
                }
            }

            table.WriteColumn(2, pszJitType);
            
            NameForMD_s(methodDesc,g_mdName,mdNameLen);                        
            table.WriteColumn(3, g_mdName);
        }
    }
    return Status;    
}

extern size_t Align (size_t nbytes);

HRESULT PrintVC(TADDR taMT, TADDR taObject, BOOL bPrintFields = TRUE)
{       
    HRESULT Status;
    DacpMethodTableData mtabledata;
    if ((Status = mtabledata.Request(g_sos, TO_CDADDR(taMT)))!=S_OK)
        return Status;
    
    size_t size = mtabledata.BaseSize;
    if ((Status=g_sos->GetMethodTableName(TO_CDADDR(taMT), mdNameLen, g_mdName, NULL))!=S_OK)
        return Status;

    ExtOut("Name:        %S\n", g_mdName);
    DMLOut("MethodTable: %s\n", DMLMethodTable(taMT));
    DMLOut("EEClass:     %s\n", DMLClass(mtabledata.Class));
    ExtOut("Size:        %d(0x%x) bytes\n", size, size);

    FileNameForModule(TO_TADDR(mtabledata.Module), g_mdName);
    ExtOut("File:        %S\n", g_mdName[0] ? g_mdName : W("Unknown Module"));

    if (bPrintFields)
    {
        DacpMethodTableFieldData vMethodTableFields;
        if ((Status = vMethodTableFields.Request(g_sos,TO_CDADDR(taMT)))!=S_OK)
            return Status;

        ExtOut("Fields:\n");

        if (vMethodTableFields.wNumInstanceFields + vMethodTableFields.wNumStaticFields > 0)
            DisplayFields(TO_CDADDR(taMT), &mtabledata, &vMethodTableFields, taObject, TRUE, TRUE);
    }

    return S_OK;
}

void PrintRuntimeTypeInfo(TADDR p_rtObject, const DacpObjectData & rtObjectData)
{
    // Get the method table
    int iOffset = GetObjFieldOffset(p_rtObject, rtObjectData.MethodTable, W("m_handle"));
    if (iOffset > 0)
    {            
        TADDR mtPtr;
        if (SUCCEEDED(GetMTOfObject(p_rtObject + iOffset, &mtPtr)))
        {
            sos::MethodTable mt = mtPtr;
            ExtOut("Type Name:   %S\n", mt.GetName());
            DMLOut("Type MT:     %s\n", DMLMethodTable(mtPtr));
        }                        
    }        
}

HRESULT PrintObj(TADDR taObj, BOOL bPrintFields = TRUE)
{
    if (!sos::IsObject(taObj, true))
    {
        ExtOut("<Note: this object has an invalid CLASS field>\n");
    }

    DacpObjectData objData;
    HRESULT Status;
    if ((Status=objData.Request(g_sos, TO_CDADDR(taObj))) != S_OK)
    {        
        ExtOut("Invalid object\n");
        return Status;
    }

    if (objData.ObjectType==OBJ_FREE)
    {
        ExtOut("Free Object\n");
        DWORD_PTR size = (DWORD_PTR)objData.Size;
        ExtOut("Size:        %" POINTERSIZE_TYPE "d(0x%" POINTERSIZE_TYPE "x) bytes\n", size, size);
        return S_OK;
    }
    
    sos::Object obj = taObj;
    ExtOut("Name:        %S\n", obj.GetTypeName());
    DMLOut("MethodTable: %s\n", DMLMethodTable(objData.MethodTable));

    
    DacpMethodTableData mtabledata;
    if ((Status=mtabledata.Request(g_sos,objData.MethodTable)) == S_OK)
    {
        DMLOut("EEClass:     %s\n", DMLClass(mtabledata.Class));
    }
    else        
    {
        ExtOut("Invalid EEClass address\n");
        return Status;
    }

    if (objData.RCW != NULL)
    {
        DMLOut("RCW:         %s\n", DMLRCWrapper(objData.RCW));
    }
    if (objData.CCW != NULL)
    {
        DMLOut("CCW:         %s\n", DMLCCWrapper(objData.CCW));
    }

    DWORD_PTR size = (DWORD_PTR)objData.Size;
    ExtOut("Size:        %" POINTERSIZE_TYPE "d(0x%" POINTERSIZE_TYPE "x) bytes\n", size, size);

    if (_wcscmp(obj.GetTypeName(), W("System.RuntimeType")) == 0)
    {
        PrintRuntimeTypeInfo(taObj, objData);
    }

    if (_wcscmp(obj.GetTypeName(), W("System.RuntimeType+RuntimeTypeCache")) == 0)
    {
        // Get the method table
        int iOffset = GetObjFieldOffset (taObj, objData.MethodTable, W("m_runtimeType"));
        if (iOffset > 0)
        {            
            TADDR rtPtr;
            if (MOVE(rtPtr, taObj + iOffset) == S_OK)
            {
                DacpObjectData rtObjectData;
                if ((Status=rtObjectData.Request(g_sos, TO_CDADDR(rtPtr))) != S_OK)
                {        
                    ExtOut("Error when reading RuntimeType field\n");
                    return Status;
                }

                PrintRuntimeTypeInfo(rtPtr, rtObjectData);
            }                        
        }        
    }

    if (objData.ObjectType==OBJ_ARRAY)
    {
        ExtOut("Array:       Rank %d, Number of elements %" POINTERSIZE_TYPE "d, Type %s",
                objData.dwRank, (DWORD_PTR)objData.dwNumComponents, ElementTypeName(objData.ElementType));

        IfDMLOut(" (<exec cmd=\"!DumpArray /d %p\">Print Array</exec>)", SOS_PTR(taObj));
        ExtOut("\n");
        
        if (objData.ElementType == ELEMENT_TYPE_I1 ||
            objData.ElementType == ELEMENT_TYPE_U1 ||
            objData.ElementType == ELEMENT_TYPE_CHAR)
        {
            bool wide = objData.ElementType == ELEMENT_TYPE_CHAR;

            // Get the size of the character array, but clamp it to a reasonable length.
            TADDR pos = taObj + (2 * sizeof(DWORD_PTR));
            DWORD_PTR num;
            moveN(num, taObj + sizeof(DWORD_PTR));

            if (IsDMLEnabled())
                DMLOut("<exec cmd=\"%s %x L%x\">Content</exec>:     ", (wide) ? "dw" : "db", pos, num);
            else
                ExtOut("Content:     ");
            CharArrayContent(pos, (ULONG)(num <= 128 ? num : 128), wide);
            ExtOut("\n");
        }
    }
    else
    {
        FileNameForModule(TO_TADDR(mtabledata.Module), g_mdName);
        ExtOut("File:        %S\n", g_mdName[0] ? g_mdName : W("Unknown Module"));
    }

    if (objData.ObjectType == OBJ_STRING)
    {
        ExtOut("String:      ");
        StringObjectContent(taObj);
        ExtOut("\n");
    }
    else if (objData.ObjectType == OBJ_OBJECT)
    {
        ExtOut("Object\n");
    }    

    if (bPrintFields)
    {
        DacpMethodTableFieldData vMethodTableFields;
        if ((Status = vMethodTableFields.Request(g_sos,TO_CDADDR(objData.MethodTable)))!=S_OK)
            return Status;

        ExtOut("Fields:\n");
        if (vMethodTableFields.wNumInstanceFields + vMethodTableFields.wNumStaticFields > 0)
        {
            DisplayFields(objData.MethodTable, &mtabledata, &vMethodTableFields, taObj, TRUE, FALSE);
        }
        else
        {
            ExtOut("None\n");
        }
    }

    sos::ThinLockInfo lockInfo;
    if (obj.GetThinLock(lockInfo))
    {
        ExtOut("ThinLock owner %x (%p), Recursive %x\n", lockInfo.ThreadId, 
            SOS_PTR(lockInfo.ThreadPtr), lockInfo.Recursion);
    }
    
    return S_OK;
}

BOOL IndicesInRange (DWORD * indices, DWORD * lowerBounds, DWORD * bounds, DWORD rank)
{
    int i = 0;
    if (!ClrSafeInt<int>::subtraction((int)rank, 1, i))
    {
        ExtOut("<integer underflow>\n");
        return FALSE;
    }

    for (; i >= 0; i--)
    {
        if (indices[i] >= bounds[i] + lowerBounds[i])
        {
            if (i == 0)
            {
                return FALSE;
            }
            
            indices[i] = lowerBounds[i];
            indices[i - 1]++;
        }
    }

    return TRUE;
}

void ExtOutIndices (DWORD * indices, DWORD rank)
{
    for (DWORD i = 0; i < rank; i++)
    {
        ExtOut("[%d]", indices[i]);
    }
}

size_t OffsetFromIndices (DWORD * indices, DWORD * lowerBounds, DWORD * bounds, DWORD rank)
{
    _ASSERTE(rank >= 0);
    size_t multiplier = 1;
    size_t offset = 0;
    int i = 0;
    if (!ClrSafeInt<int>::subtraction((int)rank, 1, i))
    {
        ExtOut("<integer underflow>\n");
        return 0;
    }

    for (; i >= 0; i--) 
    {
        DWORD curIndex = indices[i] - lowerBounds[i];
        offset += curIndex * multiplier;
        multiplier *= bounds[i];
    }

    return offset;
}
HRESULT PrintArray(DacpObjectData& objData, DumpArrayFlags& flags, BOOL isPermSetPrint);
#ifdef _DEBUG
HRESULT PrintPermissionSet (TADDR p_PermSet)
{
    HRESULT Status = S_OK;

    DacpObjectData PermSetData;
    if ((Status=PermSetData.Request(g_sos, TO_CDADDR(p_PermSet))) != S_OK)
    {        
        ExtOut("Invalid object\n");
        return Status;
    }

    
    sos::MethodTable mt = TO_TADDR(PermSetData.MethodTable);
    if (_wcscmp (W("System.Security.PermissionSet"), mt.GetName()) != 0 && _wcscmp(W("System.Security.NamedPermissionSet"), mt.GetName()) != 0)
    {
        ExtOut("Invalid PermissionSet object\n");
        return S_FALSE;
    }

    ExtOut("PermissionSet object: %p\n", SOS_PTR(p_PermSet));
    
    // Print basic info

    // Walk the fields, printing some fields in a special way.

    int iOffset = GetObjFieldOffset (p_PermSet, PermSetData.MethodTable, W("m_Unrestricted"));
    
    if (iOffset > 0)        
    {
        BYTE unrestricted;
        MOVE(unrestricted, p_PermSet + iOffset);
        if (unrestricted)
            ExtOut("Unrestricted: TRUE\n");
        else
            ExtOut("Unrestricted: FALSE\n");
    }

    iOffset = GetObjFieldOffset (p_PermSet, PermSetData.MethodTable, W("m_permSet"));
    if (iOffset > 0)
    {
        TADDR tbSetPtr;
        MOVE(tbSetPtr, p_PermSet + iOffset);
        if (tbSetPtr != NULL)
        {
            DacpObjectData tbSetData;
            if ((Status=tbSetData.Request(g_sos, TO_CDADDR(tbSetPtr))) != S_OK)
            {        
                ExtOut("Invalid object\n");
                return Status;
            }

            iOffset = GetObjFieldOffset (tbSetPtr, tbSetData.MethodTable, W("m_Set"));
            if (iOffset > 0)
            {
                DWORD_PTR PermsArrayPtr;
                MOVE(PermsArrayPtr, tbSetPtr + iOffset);
                if (PermsArrayPtr != NULL)
                {
                    // Print all the permissions in the array
                    DacpObjectData objData;
                    if ((Status=objData.Request(g_sos, TO_CDADDR(PermsArrayPtr))) != S_OK)
                    {        
                        ExtOut("Invalid object\n");
                        return Status;
                    }
                    DumpArrayFlags flags;
                    flags.bDetail = TRUE;
                    return PrintArray(objData, flags, TRUE);
                }
            }

            iOffset = GetObjFieldOffset (tbSetPtr, tbSetData.MethodTable, W("m_Obj"));
            if (iOffset > 0)
            {
                DWORD_PTR PermObjPtr;
                MOVE(PermObjPtr, tbSetPtr + iOffset);
                if (PermObjPtr != NULL)
                {
                    // Print the permission object
                    return PrintObj(PermObjPtr);
                }
            }
            

        }
    }
    return Status;
}

#endif // _DEBUG

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of an object from a  *  
*    given address
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpArray)
{
    INIT_API();

    DumpArrayFlags flags;
    
    MINIDUMP_NOT_SUPPORTED();

    BOOL dml = FALSE;
    
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-start", &flags.startIndex, COSIZE_T, TRUE},
        {"-length", &flags.Length, COSIZE_T, TRUE},
        {"-details", &flags.bDetail, COBOOL, FALSE},
        {"-nofields", &flags.bNoFieldsForElement, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&flags.strObject, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    DWORD_PTR p_Object = GetExpression (flags.strObject);
    if (p_Object == 0)
    {
        ExtOut("Invalid parameter %s\n", flags.strObject);
        return Status;
    }

    if (!sos::IsObject(p_Object, true))
    {
        ExtOut("<Note: this object has an invalid CLASS field>\n");
    }
    
    DacpObjectData objData;
    if ((Status=objData.Request(g_sos, TO_CDADDR(p_Object))) != S_OK)
    {  
        ExtOut("Invalid object\n");
        return Status;
    }

    if (objData.ObjectType != OBJ_ARRAY)
    {
        ExtOut("Not an array, please use !DumpObj instead\n");
        return S_OK;
    }
    return PrintArray(objData, flags, FALSE);
}


HRESULT PrintArray(DacpObjectData& objData, DumpArrayFlags& flags, BOOL isPermSetPrint)
{
    HRESULT Status = S_OK;

    if (objData.dwRank != 1 && (flags.Length != (DWORD_PTR)-1 ||flags.startIndex != 0))
    {
        ExtOut("For multi-dimension array, length and start index are supported\n");
        return S_OK;
    }

    if (flags.startIndex > objData.dwNumComponents)
    {
        ExtOut("Start index out of range\n");
        return S_OK;
    }

    if (!flags.bDetail && flags.bNoFieldsForElement)
    {
        ExtOut("-nofields has no effect unless -details is specified\n");
    }
    
    DWORD i;
    if (!isPermSetPrint)
    {
        // TODO: don't depend on this being a MethodTable
        NameForMT_s(TO_TADDR(objData.ElementTypeHandle), g_mdName, mdNameLen);

        ExtOut("Name:        %S[", g_mdName);
        for (i = 1; i < objData.dwRank; i++)
            ExtOut(",");
        ExtOut("]\n");
        
        DMLOut("MethodTable: %s\n", DMLMethodTable(objData.MethodTable));

        {
            DacpMethodTableData mtdata;
            if (SUCCEEDED(mtdata.Request(g_sos, objData.MethodTable)))
            {
                DMLOut("EEClass:     %s\n", DMLClass(mtdata.Class));
            }            
        }

        DWORD_PTR size = (DWORD_PTR)objData.Size;
        ExtOut("Size:        %" POINTERSIZE_TYPE "d(0x%" POINTERSIZE_TYPE "x) bytes\n", size, size);

        ExtOut("Array:       Rank %d, Number of elements %" POINTERSIZE_TYPE "d, Type %s\n", 
                objData.dwRank, (DWORD_PTR)objData.dwNumComponents, ElementTypeName(objData.ElementType));
        DMLOut("Element Methodtable: %s\n", DMLMethodTable(objData.ElementTypeHandle));
    }

    BOOL isElementValueType = IsElementValueType(objData.ElementType);

    DWORD dwRankAllocSize;
    if (!ClrSafeInt<DWORD>::multiply(sizeof(DWORD), objData.dwRank, dwRankAllocSize))
    {
        ExtOut("Integer overflow on array rank\n");
        return Status;
    }

    DWORD *lowerBounds = (DWORD *)alloca(dwRankAllocSize);
    if (!SafeReadMemory(objData.ArrayLowerBoundsPtr, lowerBounds, dwRankAllocSize, NULL))
    {
        ExtOut("Failed to read lower bounds info from the array\n");        
        return S_OK;
    }

    DWORD *bounds = (DWORD *)alloca(dwRankAllocSize);
    if (!SafeReadMemory (objData.ArrayBoundsPtr, bounds, dwRankAllocSize, NULL))
    {
        ExtOut("Failed to read bounds info from the array\n");        
        return S_OK;
    }

    //length is only supported for single-dimension array
    if (objData.dwRank == 1 && flags.Length != (DWORD_PTR)-1)
    {
        bounds[0] = _min(bounds[0], (DWORD)(flags.Length + flags.startIndex) - lowerBounds[0]);
    }
    
    DWORD *indices = (DWORD *)alloca(dwRankAllocSize);
    for (i = 0; i < objData.dwRank; i++)
    {
        indices[i] = lowerBounds[i];
    }

    //start index is only supported for single-dimension array
    if (objData.dwRank == 1)
    {
        indices[0] = (DWORD)flags.startIndex;
    }
    
    //Offset should be calculated by OffsetFromIndices. However because of the way 
    //how we grow indices, incrementing offset by one happens to match indices in every iteration    
    for (size_t offset = OffsetFromIndices (indices, lowerBounds, bounds, objData.dwRank);
        IndicesInRange (indices, lowerBounds, bounds, objData.dwRank); 
        indices[objData.dwRank - 1]++, offset++)
    {      
        if (IsInterrupt())
        {
            ExtOut("interrupted by user\n");
            break;
        }

        TADDR elementAddress = TO_TADDR(objData.ArrayDataPtr + offset * objData.dwComponentSize);
        TADDR p_Element = NULL;
        if (isElementValueType)
        {
            p_Element = elementAddress;        
        }
        else if (!SafeReadMemory (elementAddress, &p_Element, sizeof (p_Element), NULL))
        {
            ExtOut("Failed to read element at ");        
            ExtOutIndices(indices, objData.dwRank);
            ExtOut("\n");
            continue;
        }

        if (p_Element)
        {
            ExtOutIndices(indices, objData.dwRank);

            if (isElementValueType)
            {
                DMLOut( " %s\n", DMLValueClass(objData.MethodTable, p_Element));
            }
            else
            {
                DMLOut(" %s\n", DMLObject(p_Element));
            }
        }
        else if (!isPermSetPrint)
        {
            ExtOutIndices(indices, objData.dwRank);
            ExtOut(" null\n");
        }

        if (flags.bDetail)
        {
            IncrementIndent();
            if (isElementValueType)
            {
                PrintVC(TO_TADDR(objData.ElementTypeHandle), elementAddress, !flags.bNoFieldsForElement);
            }
            else if (p_Element != NULL)
            {
                PrintObj(p_Element, !flags.bNoFieldsForElement);
            }
            DecrementIndent();
        }
    }
    
    return S_OK;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of an object from a  *  
*    given address
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpObj)    
{
    INIT_API();

    MINIDUMP_NOT_SUPPORTED();    

    BOOL dml = FALSE;
    BOOL bNoFields = FALSE;
    BOOL bRefs = FALSE;
    StringHolder str_Object;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-nofields", &bNoFields, COBOOL, FALSE},
        {"-refs", &bRefs, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&str_Object.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    
    DWORD_PTR p_Object = GetExpression(str_Object.data);
    EnableDMLHolder dmlHolder(dml);
    if (p_Object == 0)
    {
        ExtOut("Invalid parameter %s\n", args);
        return Status;
    }

    Status = PrintObj(p_Object, !bNoFields);
    
    if (SUCCEEDED(Status) && bRefs)
    {
        ExtOut("GC Refs:\n");
        TableOutput out(2, POINTERSIZE_HEX, AlignRight, 4);
        out.WriteRow("offset", "object");
        for (sos::RefIterator itr(TO_TADDR(p_Object)); itr; ++itr)
            out.WriteRow(Hex(itr.GetOffset()), ObjectPtr(*itr));
    }
    
    return Status;
}

CLRDATA_ADDRESS isExceptionObj(CLRDATA_ADDRESS mtObj)
{
    // We want to follow back until we get the mt for System.Exception
    DacpMethodTableData dmtd;
    CLRDATA_ADDRESS walkMT = mtObj;
    while(walkMT != NULL)
    {
        if (dmtd.Request(g_sos, walkMT) != S_OK)
        {
            break;            
        }
        if (walkMT == g_special_usefulGlobals.ExceptionMethodTable)
        {
            return walkMT;
        }
        walkMT = dmtd.ParentMethodTable;
    }
    return NULL;
}

CLRDATA_ADDRESS isSecurityExceptionObj(CLRDATA_ADDRESS mtObj)
{
    // We want to follow back until we get the mt for System.Exception
    DacpMethodTableData dmtd;
    CLRDATA_ADDRESS walkMT = mtObj;
    while(walkMT != NULL)
    {
        if (dmtd.Request(g_sos, walkMT) != S_OK)
        {
            break;            
        }
        NameForMT_s(TO_TADDR(walkMT), g_mdName, mdNameLen);                
        if (_wcscmp(W("System.Security.SecurityException"), g_mdName) == 0)
        {
            return walkMT;
        }
        walkMT = dmtd.ParentMethodTable;
    }
    return NULL;
}

// Fill the passed in buffer with a text header for generated exception information.
// Returns the number of characters in the wszBuffer array on exit.
// If NULL is passed for wszBuffer, just returns the number of characters needed.
size_t AddExceptionHeader (__out_ecount_opt(bufferLength) WCHAR *wszBuffer, size_t bufferLength)
{
#ifdef _TARGET_WIN64_
    const WCHAR *wszHeader = W("    SP               IP               Function\n");
#else
    const WCHAR *wszHeader = W("    SP       IP       Function\n");
#endif // _TARGET_WIN64_
    if (wszBuffer)
    {
        swprintf_s(wszBuffer, bufferLength, wszHeader);
    }
    return _wcslen(wszHeader);
}

struct StackTraceElement 
{
    UINT_PTR        ip;
    UINT_PTR        sp;
    DWORD_PTR       pFunc;  // MethodDesc
    // TRUE if this element represents the last frame of the foreign
    // exception stack trace.
    BOOL            fIsLastFrameFromForeignStackTrace;

};

#include "sos_stacktrace.h"

class StringOutput
{
public:
    CQuickString cs;
    StringOutput()
    {
        cs.Alloc(1024);
        cs.String()[0] = L'\0';
    }

    BOOL Append(__in_z LPCWSTR pszStr)
    {
        size_t iInputLen = _wcslen (pszStr);        
        size_t iCurLen = _wcslen (cs.String());
        if ((iCurLen + iInputLen + 1) > cs.Size())
        {
            if (cs.ReSize(iCurLen + iInputLen + 1) != S_OK)
            {
                return FALSE;
            }
        }

        wcsncat_s (cs.String(), cs.Size(), pszStr, _TRUNCATE);
        return TRUE;
    }
    
    size_t Length()
    {
        return _wcslen(cs.String());
    }

    WCHAR *String()
    {
        return cs.String();
    }
};

static HRESULT DumpMDInfoBuffer(DWORD_PTR dwStartAddr, DWORD Flags, ULONG64 Esp, ULONG64 IPAddr, StringOutput& so);

// Using heuristics to determine if an exception object represented an async (hardware) or a 
// managed exception
// We need to use these heuristics when the System.Exception object is not the active exception
// on some thread, but it's something found somewhere on the managed heap.

// uses the MapWin32FaultToCOMPlusException to figure out how we map async exceptions
// to managed exceptions and their HRESULTs
static const HRESULT AsyncHResultValues[] =
{
    COR_E_ARITHMETIC,    // kArithmeticException
    COR_E_OVERFLOW,      // kOverflowException
    COR_E_DIVIDEBYZERO,  // kDivideByZeroException
    COR_E_FORMAT,        // kFormatException
    COR_E_NULLREFERENCE, // kNullReferenceException
    E_POINTER,           // kAccessViolationException
    // the EE is raising the next exceptions more often than the OS will raise an async 
    // exception for these conditions, so in general treat these as Synchronous
      // COR_E_INDEXOUTOFRANGE, // kIndexOutOfRangeException
      // COR_E_OUTOFMEMORY,   // kOutOfMemoryException
      // COR_E_STACKOVERFLOW, // kStackOverflowException
    COR_E_DATAMISALIGNED, // kDataMisalignedException
    
};
BOOL IsAsyncException(TADDR taObj, TADDR mtObj)
{
    // by default we'll treat exceptions as synchronous
    UINT32 xcode = EXCEPTION_COMPLUS;
    int iOffset = GetObjFieldOffset (taObj, mtObj, W("_xcode"));
    if (iOffset > 0)
    {
        HRESULT hr = MOVE(xcode, taObj + iOffset);
        if (hr != S_OK)
        {
            xcode = EXCEPTION_COMPLUS;
            goto Done;
        }
    }

    if (xcode == EXCEPTION_COMPLUS)
    {
        HRESULT ehr = 0;
        iOffset = GetObjFieldOffset (taObj, mtObj, W("_HResult"));
        if (iOffset > 0)
        {
            HRESULT hr = MOVE(ehr, taObj + iOffset);
            if (hr != S_OK)
            {
                xcode = EXCEPTION_COMPLUS;
                goto Done;
            }
            for (size_t idx = 0; idx < _countof(AsyncHResultValues); ++idx)
            {
                if (ehr == AsyncHResultValues[idx])
                {
                    xcode = ehr;
                    break;
                }
            }
        }
    }
Done:
    return xcode != EXCEPTION_COMPLUS;
}

// Overload that mirrors the code above when the ExceptionObjectData was already retrieved from LS
BOOL IsAsyncException(const DacpExceptionObjectData & excData)
{
    if (excData.XCode != EXCEPTION_COMPLUS)
        return TRUE;

    HRESULT ehr = excData.HResult;
    for (size_t idx = 0; idx < _countof(AsyncHResultValues); ++idx)
    {
        if (ehr == AsyncHResultValues[idx])
        {
            return TRUE;
        }
    }

    return FALSE;
}


#define SOS_STACKTRACE_SHOWEXPLICITFRAMES  0x00000002
size_t FormatGeneratedException (DWORD_PTR dataPtr, 
    UINT bytes, 
    __out_ecount_opt(bufferLength) WCHAR *wszBuffer, 
    size_t bufferLength, 
    BOOL bAsync,
    BOOL bNestedCase = FALSE,
    BOOL bLineNumbers = FALSE)
{
    UINT count = bytes / sizeof(StackTraceElement);
    size_t Length = 0;

    if (wszBuffer && bufferLength > 0)
    {
        wszBuffer[0] = L'\0';
    }
    
    // Buffer is calculated for sprintf below ("   %p %p %S\n");
    WCHAR wszLineBuffer[mdNameLen + 8 + sizeof(size_t)*2 + MAX_LONGPATH + 8];

    if (count == 0)
    {
        return 0;
    }
    
    if (bNestedCase)
    {
        // If we are computing the call stack for a nested exception, we
        // don't want to print the last frame, because the outer exception
        // will have that frame.
        count--;
    }
    
    for (UINT i = 0; i < count; i++)
    {
        StackTraceElement ste;
        MOVE (ste, dataPtr + i*sizeof(StackTraceElement));

        // ste.ip must be adjusted because of an ancient workaround in the exception 
        // infrastructure. The workaround is that the exception needs to have
        // an ip address that will map to the line number where the exception was thrown.
        // (It doesn't matter that it's not a valid instruction). (see /vm/excep.cpp)
        //
        // This "counterhack" is not 100% accurate
        // The biggest issue is that !PrintException must work with exception objects 
        // that may not be currently active; as a consequence we cannot rely on the 
        // state of some "current thread" to infer whether the IP values stored in 
        // the exception object have been adjusted or not. If we could, we may examine 
        // the topmost "Frame" and make the decision based on whether it's a 
        // FaultingExceptionFrame or not.
        // 1. On IA64 the IP values are never adjusted by the EE so there's nothing 
        //    to adjust back.
        // 2. On AMD64:
        //    (a) if the exception was an async (hardware) exception add 1 to all 
        //        IP values in the exception object
        //    (b) if the exception was a managed exception (either raised by the 
        //        EE or thrown by managed code) do not adjust any IP values
        // 3. On X86:
        //    (a) if the exception was an async (hardware) exception add 1 to 
        //        all but the topmost IP value in the exception object
        //    (b) if the exception was a managed exception (either raised by 
        //        the EE or thrown by managed code) add 1 to all IP values in 
        //        the exception object
#if defined(_TARGET_AMD64_)
        if (bAsync)
        {
            ste.ip += 1;
        }
#elif defined(_TARGET_X86_)
        if (IsDbgTargetX86() && (!bAsync || i != 0))
        {
            ste.ip += 1;
        }
#endif // defined(_TARGET_AMD64_) || defined(_TARGET__X86_)

        StringOutput so;
        HRESULT Status = DumpMDInfoBuffer(ste.pFunc, SOS_STACKTRACE_SHOWADDRESSES|SOS_STACKTRACE_SHOWEXPLICITFRAMES, ste.sp, ste.ip, so);

        // If DumpMDInfoBuffer failed (due to out of memory or missing metadata), 
        // or did not update so (when ste is an explicit frames), do not update wszBuffer
        if (Status == S_OK)
        {
            WCHAR filename[MAX_LONGPATH] = W("");
            ULONG linenum = 0;
            if (bLineNumbers && 
                SUCCEEDED(GetLineByOffset(TO_CDADDR(ste.ip), &linenum, filename, _countof(filename))))
            {
                swprintf_s(wszLineBuffer, _countof(wszLineBuffer), W("    %s [%s @ %d]\n"), so.String(), filename, linenum);
            }
            else
            {
                swprintf_s(wszLineBuffer, _countof(wszLineBuffer), W("    %s\n"), so.String());
            }

            Length += _wcslen(wszLineBuffer);

            if (wszBuffer)
            {
                wcsncat_s(wszBuffer, bufferLength, wszLineBuffer, _TRUNCATE);
            }
        }
    }

    return Length;
}

// ExtOut has an internal limit for the string size
void SosExtOutLargeString(__inout_z __inout_ecount_opt(len) WCHAR * pwszLargeString, size_t len)
{
    const size_t chunkLen = 2048;

    WCHAR *pwsz = pwszLargeString;  // beginning of a chunk
    size_t count = len/chunkLen;
    // write full chunks
    for (size_t idx = 0; idx < count; ++idx)
    {
        WCHAR *pch = pwsz + chunkLen; // after the chunk
        // zero terminate the chunk
        WCHAR ch = *pch;
        *pch = L'\0';

        ExtOut("%S", pwsz);

        // restore whacked char
        *pch = ch;

        // advance to next chunk
        pwsz += chunkLen;
    }

    // last chunk
    ExtOut("%S", pwsz);
}

HRESULT FormatException(TADDR taObj, BOOL bLineNumbers = FALSE)
{
    HRESULT Status = S_OK;

    DacpObjectData objData;
    if ((Status=objData.Request(g_sos, TO_CDADDR(taObj))) != S_OK)
    {        
        ExtOut("Invalid object\n");
        return Status;
    }

    // Make sure it is an exception object, and get the MT of Exception
    CLRDATA_ADDRESS exceptionMT = isExceptionObj(objData.MethodTable);
    if (exceptionMT == NULL)
    {
        ExtOut("Not a valid exception object\n");
        return Status;
    }

    DMLOut("Exception object: %s\n", DMLObject(taObj));
    
    if (NameForMT_s(TO_TADDR(objData.MethodTable), g_mdName, mdNameLen))
    {
        ExtOut("Exception type:   %S\n", g_mdName);
    }
    else
    {
        ExtOut("Exception type:   <Unknown>\n");
    }

    // Print basic info

    // First try to get exception object data using ISOSDacInterface2
    DacpExceptionObjectData excData;
    BOOL bGotExcData = SUCCEEDED(excData.Request(g_sos, TO_CDADDR(taObj)));

    // Walk the fields, printing some fields in a special way.
    // HR, InnerException, Message, StackTrace, StackTraceString

    {
        TADDR taMsg = 0;
        if (bGotExcData)
        {
            taMsg = TO_TADDR(excData.Message);
        }
        else
        {
            int iOffset = GetObjFieldOffset(taObj, objData.MethodTable, W("_message"));
            if (iOffset > 0)
            {
                MOVE (taMsg, taObj + iOffset);
            }
        }

        ExtOut("Message:          ");

        if (taMsg)
            StringObjectContent(taMsg);
        else
            ExtOut("<none>");

        ExtOut("\n");
    }

    {
        TADDR taInnerExc = 0;
        if (bGotExcData)
        {
            taInnerExc = TO_TADDR(excData.InnerException);
        }
        else
        {
            int iOffset = GetObjFieldOffset(taObj, objData.MethodTable, W("_innerException"));
            if (iOffset > 0)
            {
                MOVE (taInnerExc, taObj + iOffset);
            }
        }

        ExtOut("InnerException:   ");
        if (taInnerExc)
        {
            TADDR taMT;
            if (SUCCEEDED(GetMTOfObject(taInnerExc, &taMT)))
            {
                NameForMT_s(taMT, g_mdName, mdNameLen);                
                ExtOut("%S, ", g_mdName);
                if (IsDMLEnabled())
                    DMLOut("Use <exec cmd=\"!PrintException /d %p\">!PrintException %p</exec> to see more.\n", taInnerExc, taInnerExc);
                else
                    ExtOut("Use !PrintException %p to see more.\n", SOS_PTR(taInnerExc));
            }
            else
            {
                ExtOut("<invalid MethodTable of inner exception>");
            }
        }
        else
        {
            ExtOut("<none>\n");
        }
    }

    BOOL bAsync = bGotExcData ? IsAsyncException(excData)
                              : IsAsyncException(taObj, TO_TADDR(objData.MethodTable));

    {
        TADDR taStackTrace = 0;
        if (bGotExcData)
        {
            taStackTrace = TO_TADDR(excData.StackTrace);
        }
        else
        {
            int iOffset = GetObjFieldOffset (taObj, objData.MethodTable, W("_stackTrace"));
            if (iOffset > 0)        
            {
                MOVE(taStackTrace, taObj + iOffset);
            }
        }

        ExtOut("StackTrace (generated):\n");
        if (taStackTrace)
        {
            DWORD arrayLen;
            HRESULT hr = MOVE(arrayLen, taStackTrace + sizeof(DWORD_PTR));

            if (arrayLen != 0 && hr == S_OK)
            {
#ifdef _TARGET_WIN64_
                DWORD_PTR dataPtr = taStackTrace + sizeof(DWORD_PTR) + sizeof(DWORD) + sizeof(DWORD);
#else
                DWORD_PTR dataPtr = taStackTrace + sizeof(DWORD_PTR) + sizeof(DWORD);
#endif // _TARGET_WIN64_
                size_t stackTraceSize = 0;
                MOVE (stackTraceSize, dataPtr);

                DWORD cbStackSize = static_cast<DWORD>(stackTraceSize * sizeof(StackTraceElement));
                dataPtr += sizeof(size_t) + sizeof(size_t); // skip the array header, then goes the data
            
                if (stackTraceSize == 0)
                {
                    ExtOut("Unable to decipher generated stack trace\n");
                }
                else
                {
                    size_t iHeaderLength = AddExceptionHeader (NULL, 0);
                    size_t iLength = FormatGeneratedException (dataPtr, cbStackSize, NULL, 0, bAsync, FALSE, bLineNumbers);
                    WCHAR *pwszBuffer = new NOTHROW WCHAR[iHeaderLength + iLength + 1];
                    if (pwszBuffer)
                    {
                        AddExceptionHeader(pwszBuffer, iHeaderLength + 1);
                        FormatGeneratedException(dataPtr, cbStackSize, pwszBuffer + iHeaderLength, iLength + 1, bAsync, FALSE, bLineNumbers);
                        SosExtOutLargeString(pwszBuffer, iHeaderLength + iLength + 1);
                        delete[] pwszBuffer;
                    }
                    ExtOut("\n");
                }
            }
            else
            {
                ExtOut("<Not Available>\n");
            }
        }                   
        else
        {
            ExtOut("<none>\n");
        }
    }

    {
        TADDR taStackString;
        if (bGotExcData)
        {
            taStackString = TO_TADDR(excData.StackTraceString);
        }
        else
        {
            int iOffset = GetObjFieldOffset (taObj, objData.MethodTable, W("_stackTraceString"));
            MOVE (taStackString, taObj + iOffset);
        }

        ExtOut("StackTraceString: ");
        if (taStackString)
        {
            StringObjectContent(taStackString);
            ExtOut("\n\n"); // extra newline looks better
        }
        else
        {
            ExtOut("<none>\n");
        }
    }

    {
        DWORD hResult;
        if (bGotExcData)
        {
            hResult = excData.HResult;
        }
        else
        {
            int iOffset = GetObjFieldOffset (taObj, objData.MethodTable, W("_HResult"));
            MOVE (hResult, taObj + iOffset);
        }

        ExtOut("HResult: %lx\n", hResult);
    }

    if (isSecurityExceptionObj(objData.MethodTable) != NULL)
    {
        // We have a SecurityException Object: print out the debugString if present
        int iOffset = GetObjFieldOffset (taObj, objData.MethodTable, W("m_debugString"));
        if (iOffset > 0)        
        {
            TADDR taDebugString;
            MOVE (taDebugString, taObj + iOffset);                
            
            if (taDebugString)
            {
                ExtOut("SecurityException Message: ");
                StringObjectContent(taDebugString);
                ExtOut("\n\n"); // extra newline looks better
            }
        }            
    }

    return Status;
}

DECLARE_API(PrintException)
{
    INIT_API();
    
    BOOL dml = FALSE;
    BOOL bShowNested = FALSE;   
    BOOL bLineNumbers = FALSE;
    BOOL bCCW = FALSE;
    StringHolder strObject;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-nested", &bShowNested, COBOOL, FALSE},
        {"-lines", &bLineNumbers, COBOOL, FALSE},
        {"-l", &bLineNumbers, COBOOL, FALSE},
        {"-ccw", &bCCW, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&strObject, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (bLineNumbers)
    {
        ULONG symlines = 0;
        if (SUCCEEDED(g_ExtSymbols->GetSymbolOptions(&symlines)))
        {
            symlines &= SYMOPT_LOAD_LINES;
        }
        if (symlines == 0)
        {
            ExtOut("In order for the option -lines to enable display of source information\n"
                   "the debugger must be configured to load the line number information from\n"
                   "the symbol files. Use the \".lines; .reload\" command to achieve this.\n");
            // don't even try
            bLineNumbers = FALSE;
        }
    }

    EnableDMLHolder dmlHolder(dml);
    DWORD_PTR p_Object = NULL;
    if (nArg == 0)
    {
        if (bCCW)
        {
            ExtOut("No CCW pointer specified\n");
            return Status;
        }

        // Look at the last exception object on this thread

        CLRDATA_ADDRESS threadAddr = GetCurrentManagedThread();
        DacpThreadData Thread;
        
        if ((threadAddr == NULL) || (Thread.Request(g_sos, threadAddr) != S_OK))
        {
            ExtOut("The current thread is unmanaged\n");
            return Status;
        }

        DWORD_PTR dwAddr = NULL;
        if ((!SafeReadMemory(TO_TADDR(Thread.lastThrownObjectHandle),
                            &dwAddr,
                            sizeof(dwAddr), NULL)) || (dwAddr==NULL))
        {
            ExtOut("There is no current managed exception on this thread\n");            
        }    
        else
        {        
            p_Object = dwAddr;        
        }
    }
    else
    {
        p_Object = GetExpression(strObject.data);
        if (p_Object == 0)
        {
            if (bCCW)
            {
                ExtOut("Invalid CCW pointer %s\n", args);
            }
            else
            {
                ExtOut("Invalid exception object %s\n", args);
            }
            return Status;
        }

        if (bCCW)
        {
            // check if the address is a CCW pointer and then
            // get the exception object from it
            DacpCCWData ccwData;
            if (ccwData.Request(g_sos, p_Object) == S_OK)
            {
                p_Object = TO_TADDR(ccwData.managedObject);
            }
        }
    }

    if (p_Object)
    {
        FormatException(p_Object, bLineNumbers);
    }

    // Are there nested exceptions?
    CLRDATA_ADDRESS threadAddr = GetCurrentManagedThread();
    DacpThreadData Thread;
    
    if ((threadAddr == NULL) || (Thread.Request(g_sos, threadAddr) != S_OK))
    {
        ExtOut("The current thread is unmanaged\n");
        return Status;
    }

    if (Thread.firstNestedException)
    {
        if (!bShowNested)
        {
            ExtOut("There are nested exceptions on this thread. Run with -nested for details\n");
            return Status;
        }
        
        CLRDATA_ADDRESS currentNested = Thread.firstNestedException;
        do
        {
            CLRDATA_ADDRESS obj = 0, next = 0;
            Status = g_sos->GetNestedExceptionData(currentNested, &obj, &next);

            if (Status != S_OK)
            {
                ExtOut("Error retrieving nested exception info %p\n", SOS_PTR(currentNested));
                return Status;
            }

            if (IsInterrupt())
            {
                ExtOut("<aborted>\n");
                return Status;
            }

            ExtOut("\nNested exception -------------------------------------------------------------\n");
            Status = FormatException((DWORD_PTR) obj, bLineNumbers);
            if (Status != S_OK)
            {
                return Status;
            }
            
            currentNested = next;
        }
        while(currentNested != NULL);        
    }
    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of an object from a  *  
*    given address
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpVC)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    DWORD_PTR p_MT = NULL;
    DWORD_PTR p_Object = NULL;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&p_MT, COHEX},
        {&p_Object, COHEX},
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (nArg!=2)
    {
        ExtOut("Usage: !DumpVC <Method Table> <Value object start addr>\n");
        return Status;
    }
    
    if (!IsMethodTable(p_MT))
    {
        ExtOut("Not a managed object\n");
        return S_OK;
    } 

    return PrintVC(p_MT, p_Object);
}

#ifndef FEATURE_PAL

#ifdef FEATURE_COMINTEROP

DECLARE_API(DumpRCW)
{
    INIT_API();
    
    BOOL dml = FALSE;
    StringHolder strObject;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE}
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&strObject, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (nArg == 0)
    {
        ExtOut("Missing RCW address\n");
        return Status;
    }
    else
    {
        DWORD_PTR p_RCW = GetExpression(strObject.data);
        if (p_RCW == 0)
        {
            ExtOut("Invalid RCW %s\n", args);
        }
        else
        {
            DacpRCWData rcwData;
            if ((Status = rcwData.Request(g_sos, p_RCW)) != S_OK)
            {
                ExtOut("Error requesting RCW data\n");
                return Status;
            }
            BOOL isDCOMProxy;
            if (FAILED(rcwData.IsDCOMProxy(g_sos, p_RCW, &isDCOMProxy)))
            {
                isDCOMProxy = FALSE;
            }

            DMLOut("Managed object:             %s\n", DMLObject(rcwData.managedObject));
            DMLOut("Creating thread:            %p\n", SOS_PTR(rcwData.creatorThread));
            ExtOut("IUnknown pointer:           %p\n", SOS_PTR(rcwData.unknownPointer));
            ExtOut("COM Context:                %p\n", SOS_PTR(rcwData.ctxCookie));
            ExtOut("Managed ref count:          %d\n", rcwData.refCount);
            ExtOut("IUnknown V-table pointer :  %p (captured at RCW creation time)\n", SOS_PTR(rcwData.vtablePtr));

            ExtOut("Flags:                      %s%s%s%s%s%s%s%s\n", 
                (rcwData.isDisconnected? "IsDisconnected " : ""),
                (rcwData.supportsIInspectable? "SupportsIInspectable " : ""),
                (rcwData.isAggregated? "IsAggregated " : ""),
                (rcwData.isContained? "IsContained " : ""),
                (rcwData.isJupiterObject? "IsJupiterObject " : ""),
                (rcwData.isFreeThreaded? "IsFreeThreaded " : ""),
                (rcwData.identityPointer == TO_CDADDR(p_RCW)? "IsUnique " : ""),
                (isDCOMProxy ? "IsDCOMProxy " : "")
                );

            // Jupiter data hidden by default
            if (rcwData.isJupiterObject)
            {
                ExtOut("IJupiterObject:    %p\n", SOS_PTR(rcwData.jupiterObject));            
            }
            
            ExtOut("COM interface pointers:\n");

            ArrayHolder<DacpCOMInterfacePointerData> pArray = new NOTHROW DacpCOMInterfacePointerData[rcwData.interfaceCount];
            if (pArray == NULL)
            {
                ReportOOM();            
                return Status;
            }

            if ((Status = g_sos->GetRCWInterfaces(p_RCW, rcwData.interfaceCount, pArray, NULL)) != S_OK)
            {
                ExtOut("Error requesting COM interface pointers\n");
                return Status;
            }

            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s Type\n", "IP", "Context", "MT");
            for (int i = 0; i < rcwData.interfaceCount; i++)
            {
                // Ignore any NULL MethodTable interface cache. At this point only IJupiterObject 
                // is saved as NULL MethodTable at first slot, and we've already printed outs its 
                // value earlier.
                if (pArray[i].methodTable == NULL)
                    continue;
                
                NameForMT_s(TO_TADDR(pArray[i].methodTable), g_mdName, mdNameLen);
                
                DMLOut("%p %p %s %S\n", SOS_PTR(pArray[i].interfacePtr), SOS_PTR(pArray[i].comContext), DMLMethodTable(pArray[i].methodTable), g_mdName);
            }
        }
    }

    return Status;
}

DECLARE_API(DumpCCW)
{
    INIT_API();
    
    BOOL dml = FALSE;
    StringHolder strObject;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE}
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&strObject, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (nArg == 0)
    {
        ExtOut("Missing CCW address\n");
        return Status;
    }
    else
    {
        DWORD_PTR p_CCW = GetExpression(strObject.data);
        if (p_CCW == 0)
        {
            ExtOut("Invalid CCW %s\n", args);
        }
        else
        {
            DacpCCWData ccwData;
            if ((Status = ccwData.Request(g_sos, p_CCW)) != S_OK)
            {
                ExtOut("Error requesting CCW data\n");
                return Status;
            }

            if (ccwData.ccwAddress != p_CCW)
                ExtOut("CCW:               %p\n", SOS_PTR(ccwData.ccwAddress));
            
            DMLOut("Managed object:    %s\n", DMLObject(ccwData.managedObject));
            ExtOut("Outer IUnknown:    %p\n", SOS_PTR(ccwData.outerIUnknown));
            ExtOut("Ref count:         %d%s\n", ccwData.refCount, ccwData.isNeutered ? " (NEUTERED)" : "");
            ExtOut("Flags:             %s%s\n",
                (ccwData.isExtendsCOMObject? "IsExtendsCOMObject " : ""),
                (ccwData.isAggregated? "IsAggregated " : "")
                );
                
            // Jupiter information hidden by default
            if (ccwData.jupiterRefCount > 0)
            {
                ExtOut("Jupiter ref count: %d%s%s%s%s\n", 
                    ccwData.jupiterRefCount, 
                    (ccwData.isPegged || ccwData.isGlobalPegged) ? ", Pegged by" : "",
                    ccwData.isPegged ? " Jupiter " : "",
                    (ccwData.isPegged && ccwData.isGlobalPegged) ? "&" : "",
                    ccwData.isGlobalPegged ? " CLR " : ""
                    );
            }
            
            ExtOut("RefCounted Handle: %p%s\n", 
                SOS_PTR(ccwData.handle), 
                (ccwData.hasStrongRef ? " (STRONG)" : " (WEAK)"));

            ExtOut("COM interface pointers:\n");            

            ArrayHolder<DacpCOMInterfacePointerData> pArray = new NOTHROW DacpCOMInterfacePointerData[ccwData.interfaceCount];
            if (pArray == NULL)
            {
                ReportOOM();            
                return Status;
            }

            if ((Status = g_sos->GetCCWInterfaces(p_CCW, ccwData.interfaceCount, pArray, NULL)) != S_OK)
            {
                ExtOut("Error requesting COM interface pointers\n");
                return Status;
            }

            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s Type\n", "IP", "MT", "Type");
            for (int i = 0; i < ccwData.interfaceCount; i++)
            {
                if (pArray[i].methodTable == NULL)
                {
                    wcscpy_s(g_mdName, mdNameLen, W("IDispatch/IUnknown"));
                }
                else
                {
                    NameForMT_s(TO_TADDR(pArray[i].methodTable), g_mdName, mdNameLen);
                }
                
                DMLOut("%p %s %S\n", pArray[i].interfacePtr, DMLMethodTable(pArray[i].methodTable), g_mdName);
            }
        }
    }

    return Status;
}

#endif // FEATURE_COMINTEROP

#ifdef _DEBUG
/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a PermissionSet   *
*    from a given address.                                             * 
*                                                                      *
\**********************************************************************/
/* 
    COMMAND: dumppermissionset.
    !DumpPermissionSet <PermissionSet object address>

    This command allows you to examine a PermissionSet object. Note that you can 
    also use DumpObj such an object in greater detail. DumpPermissionSet attempts 
    to extract all the relevant information from a PermissionSet that you might be 
    interested in when performing Code Access Security (CAS) related debugging.

    Here is a simple PermissionSet object:

    0:000> !DumpPermissionSet 014615f4 
    PermissionSet object: 014615f4
    Unrestricted: TRUE

    Note that this is an unrestricted PermissionSet object that does not contain 
    any individual permissions. 

    Here is another example of a PermissionSet object, one that is not unrestricted 
    and contains a single permission:

    0:003> !DumpPermissionSet 01469fa8 
    PermissionSet object: 01469fa8
    Unrestricted: FALSE
    Name: System.Security.Permissions.ReflectionPermission
    MethodTable: 5b731308
    EEClass: 5b7e0d78
    Size: 12(0xc) bytes
     (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_32\mscorlib\2.0.
    0.0__b77a5c561934e089\mscorlib.dll)

    Fields:
          MT    Field   Offset                 Type VT     Attr    Value Name
    5b73125c  4001d66        4         System.Int32  0 instance        2 m_flags

    Here is another example of an unrestricted PermissionSet, one that contains 
    several permissions. The numbers in parentheses before each Permission object 
    represents the index of that Permission in the PermissionSet.

    0:003> !DumpPermissionSet 01467bd8
    PermissionSet object: 01467bd8
    Unrestricted: FALSE
    [1] 01467e90
        Name: System.Security.Permissions.FileDialogPermission
        MethodTable: 5b73023c
        EEClass: 5b7dfb18
        Size: 12(0xc) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        5b730190  4001cc2        4         System.Int32  0 instance        1 access
    [4] 014682a8
        Name: System.Security.Permissions.ReflectionPermission
        MethodTable: 5b731308
        EEClass: 5b7e0d78
        Size: 12(0xc) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_32\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        5b73125c  4001d66        4         System.Int32  0 instance        0 m_flags
    [17] 0146c060
        Name: System.Diagnostics.EventLogPermission
        MethodTable: 569841c4
        EEClass: 56a03e5c
        Size: 28(0x1c) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        5b6d65d4  4003078        4      System.Object[]  0 instance 0146c190 tagNames
        5b6c9ed8  4003079        8          System.Type  0 instance 0146c17c permissionAccessType
        5b6cd928  400307a       10       System.Boolean  0 instance        0 isUnrestricted
        5b6c45f8  400307b        c ...ections.Hashtable  0 instance 0146c1a4 rootTable
        5b6c090c  4003077      bfc        System.String  0   static 00000000 computerName
        56984434  40030e7       14 ...onEntryCollection  0 instance 00000000 innerCollection
    [18] 0146ceb4
        Name: System.Net.WebPermission
        MethodTable: 5696dfc4
        EEClass: 569e256c
        Size: 20(0x14) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        5b6cd928  400238e        c       System.Boolean  0 instance        0 m_Unrestricted
        5b6cd928  400238f        d       System.Boolean  0 instance        0 m_UnrestrictedConnect
        5b6cd928  4002390        e       System.Boolean  0 instance        0 m_UnrestrictedAccept
        5b6c639c  4002391        4 ...ections.ArrayList  0 instance 0146cf3c m_connectList
        5b6c639c  4002392        8 ...ections.ArrayList  0 instance 0146cf54 m_acceptList
        569476f8  4002393      8a4 ...Expressions.Regex  0   static 00000000 s_MatchAllRegex
    [19] 0146a5fc
        Name: System.Net.DnsPermission
        MethodTable: 56966408
        EEClass: 569d3c08
        Size: 12(0xc) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        5b6cd928  4001d2c        4       System.Boolean  0 instance        1 m_noRestriction
    [20] 0146d8ec
        Name: System.Web.AspNetHostingPermission
        MethodTable: 569831bc
        EEClass: 56a02ccc
        Size: 12(0xc) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        56983090  4003074        4         System.Int32  0 instance      600 _level
    [21] 0146e394
        Name: System.Net.NetworkInformation.NetworkInformationPermission
        MethodTable: 5697ac70
        EEClass: 569f7104
        Size: 16(0x10) bytes
         (C:\WINDOWS\Microsoft.NET\Framework\v2.0.x86chk\assembly\GAC_MSIL\System\2.0.0.0__b77a5c561934e089\System.dll)
        Fields:
              MT    Field   Offset                 Type VT     Attr    Value Name
        5697ab38  4002c34        4         System.Int32  0 instance        0 access
        5b6cd928  4002c35        8       System.Boolean  0 instance        0 unrestricted


    The abbreviation !dps can be used for brevity.

    \\
*/
DECLARE_API(DumpPermissionSet)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    DWORD_PTR p_Object = NULL;

    CMDValue arg[] = 
    {
        {&p_Object, COHEX}
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (nArg!=1)
    {
        ExtOut("Usage: !DumpPermissionSet <PermissionSet object addr>\n");
        return Status;
    }
    

    return PrintPermissionSet(p_Object);
}

#endif // _DEBUG

void GCPrintGenerationInfo(DacpGcHeapDetails &heap);
void GCPrintSegmentInfo(DacpGcHeapDetails &heap, DWORD_PTR &total_size);

#endif // FEATURE_PAL

void DisplayInvalidStructuresMessage()
{
    ExtOut("The garbage collector data structures are not in a valid state for traversal.\n");
    ExtOut("It is either in the \"plan phase,\" where objects are being moved around, or\n");
    ExtOut("we are at the initialization or shutdown of the gc heap. Commands related to \n");
    ExtOut("displaying, finding or traversing objects as well as gc heap segments may not \n");
    ExtOut("work properly. !dumpheap and !verifyheap may incorrectly complain of heap \n");
    ExtOut("consistency errors.\n");
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function dumps GC heap size.                                 *  
*                                                                      *
\**********************************************************************/
DECLARE_API(EEHeap)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    BOOL dml = FALSE;
    BOOL showgc = FALSE;
    BOOL showloader = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-gc", &showgc, COBOOL, FALSE},
        {"-loader", &showloader, COBOOL, FALSE},
        {"/d", &dml, COBOOL, FALSE},
    };

    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (showloader || !showgc)
    {
        // Loader heap.
        DWORD_PTR allHeapSize = 0;
        DWORD_PTR wasted = 0;    
        DacpAppDomainStoreData adsData;
        if ((Status=adsData.Request(g_sos))!=S_OK)
        {
            ExtOut("Unable to get AppDomain information\n");
            return Status;
        }

        // The first one is the system domain.
        ExtOut("Loader Heap:\n");
        IfFailRet(PrintDomainHeapInfo("System Domain", adsData.systemDomain, &allHeapSize, &wasted));
        IfFailRet(PrintDomainHeapInfo("Shared Domain", adsData.sharedDomain, &allHeapSize, &wasted));
        
        ArrayHolder<CLRDATA_ADDRESS> pArray = new NOTHROW CLRDATA_ADDRESS[adsData.DomainCount];

        if (pArray==NULL)
        {
            ReportOOM();            
            return Status;
        }

        if ((Status=g_sos->GetAppDomainList(adsData.DomainCount, pArray, NULL))!=S_OK)
        {
            ExtOut("Unable to get the array of all AppDomains.\n");
            return Status;
        }

        for (int n=0;n<adsData.DomainCount;n++)
        {
            if (IsInterrupt())
                break;

            char domain[16];
            sprintf_s(domain, _countof(domain), "Domain %d", n+1);

            IfFailRet(PrintDomainHeapInfo(domain, pArray[n], &allHeapSize, &wasted));

        }

        // Jit code heap
        ExtOut("--------------------------------------\n");
        ExtOut("Jit code heap:\n");

        if (IsMiniDumpFile())
        {
            ExtOut("<no information>\n");
        }
        else
        {
            allHeapSize += JitHeapInfo();
        }

    
        // Module Data
        {
            int numModule;
            ArrayHolder<DWORD_PTR> moduleList = ModuleFromName(NULL, &numModule);   
            if (moduleList == NULL)
            {
                ExtOut("Failed to request module list.\n");
            }
            else
            {
                // Module Thunk Heaps
                ExtOut("--------------------------------------\n");
                ExtOut("Module Thunk heaps:\n");
                allHeapSize += PrintModuleHeapInfo(moduleList, numModule, ModuleHeapType_ThunkHeap, &wasted);

                // Module Lookup Table Heaps
                ExtOut("--------------------------------------\n");
                ExtOut("Module Lookup Table heaps:\n");
                allHeapSize += PrintModuleHeapInfo(moduleList, numModule, ModuleHeapType_LookupTableHeap, &wasted);
            }
        }

        ExtOut("--------------------------------------\n");
        ExtOut("Total LoaderHeap size:   ");
        PrintHeapSize(allHeapSize, wasted);
        ExtOut("=======================================\n");
    }

    if (showgc || !showloader)
    {   
        // GC Heap
        DWORD dwNHeaps = 1;

        if (!GetGcStructuresValid())
        {
            DisplayInvalidStructuresMessage();
        }
        
        DacpGcHeapData gcheap;
        if (gcheap.Request(g_sos) != S_OK)
        {
            ExtOut("Error requesting GC Heap data\n");
            return Status;
        }

        if (gcheap.bServerMode)
        {
            dwNHeaps = gcheap.HeapCount;
        }

        ExtOut("Number of GC Heaps: %d\n", dwNHeaps);
        DWORD_PTR totalSize = 0;
        if (!gcheap.bServerMode)
        {
            DacpGcHeapDetails heapDetails;
            if (heapDetails.Request(g_sos) != S_OK)
            {
                ExtOut("Error requesting details\n");
                return Status;
            }

            GCHeapInfo (heapDetails, totalSize);
            ExtOut("Total Size:              ");
            PrintHeapSize(totalSize, 0);
        }
        else
        {
            DWORD dwAllocSize;
            if (!ClrSafeInt<DWORD>::multiply(sizeof(CLRDATA_ADDRESS), dwNHeaps, dwAllocSize))
            {
                ExtOut("Failed to get GCHeaps: integer overflow\n");
                return Status;
            }

            CLRDATA_ADDRESS *heapAddrs = (CLRDATA_ADDRESS*)alloca(dwAllocSize);
            if (g_sos->GetGCHeapList(dwNHeaps, heapAddrs, NULL) != S_OK)
            {
                ExtOut("Failed to get GCHeaps\n");
                return Status;
            }
                        
            DWORD n;
            for (n = 0; n < dwNHeaps; n ++)
            {
                DacpGcHeapDetails heapDetails;
                if (heapDetails.Request(g_sos, heapAddrs[n]) != S_OK)
                {
                    ExtOut("Error requesting details\n");
                    return Status;
                }
                ExtOut("------------------------------\n");
                ExtOut("Heap %d (%p)\n", n, SOS_PTR(heapAddrs[n]));
                DWORD_PTR heapSize = 0;
                GCHeapInfo (heapDetails, heapSize);
                totalSize += heapSize;
                ExtOut("Heap Size:       " WIN86_8SPACES);
                PrintHeapSize(heapSize, 0);
            }
        }
        ExtOut("------------------------------\n");
        ExtOut("GC Heap Size:    " WIN86_8SPACES);
        PrintHeapSize(totalSize, 0);
    }
    return Status;
}

void PrintGCStat(HeapStat *inStat, const char* label=NULL)
{
    if (inStat)
    {
        bool sorted = false;
        try
        {
            inStat->Sort();
            sorted = true;
            inStat->Print(label);
        }
        catch(...)
        {
            ExtOut("Exception occurred while trying to %s the GC stats.\n", sorted ? "print" : "sort");
        }

        inStat->Delete();
    }
}

#ifndef FEATURE_PAL

DECLARE_API(TraverseHeap)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    BOOL bXmlFormat = FALSE;
    BOOL bVerify = FALSE;
    StringHolder Filename;

    CMDOption option[] = 
    {   // name, vptr,        type, hasValue
        {"-xml", &bXmlFormat, COBOOL, FALSE},
        {"-verify", &bVerify, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&Filename.data, COSTRING},
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    if (nArg != 1)
    {
        ExtOut("usage: HeapTraverse [-xml] filename\n");
        return Status;
    }

    if (!g_snapshot.Build())
    {
        ExtOut("Unable to build snapshot of the garbage collector state\n");
        return Status;
    }

    FILE* file = NULL;
    if (fopen_s(&file, Filename.data, "w") != 0) {
        ExtOut("Unable to open file\n");
        return Status;
    }

    if (!bVerify)
        ExtOut("Assuming a uncorrupted GC heap.  If this is a crash dump consider -verify option\n"); 

    HeapTraverser traverser(bVerify != FALSE);

    ExtOut("Writing %s format to file %s\n", bXmlFormat ? "Xml" : "CLRProfiler", Filename.data);    
    ExtOut("Gathering types...\n");

    // TODO: there may be a canonical list of methodtables in the runtime that we can
    // traverse instead of exploring the gc heap for that list. We could then simplify the
    // tree structure to a sorted list of methodtables, and the index is the ID.

    // TODO: "Traversing object members" code should be generalized and shared between
    // !gcroot and !traverseheap. Also !dumpheap can begin using GCHeapsTraverse.

    if (!traverser.Initialize())
    {
        ExtOut("Error initializing heap traversal\n");
        fclose(file);
        return Status;
    }

    if (!traverser.CreateReport (file, bXmlFormat ? FORMAT_XML : FORMAT_CLRPROFILER))
    {
        ExtOut("Unable to write heap report\n");
        fclose(file);
        return Status;
    }

    fclose(file);                
    ExtOut("\nfile %s saved\n", Filename.data);
    
    return Status;
}

#endif // FEATURE_PAL

struct PrintRuntimeTypeArgs
{
    DWORD_PTR mtOfRuntimeType;
    int handleFieldOffset;
    DacpAppDomainStoreData adstore;
};

void PrintRuntimeTypes(DWORD_PTR objAddr,size_t Size,DWORD_PTR methodTable,LPVOID token)
{
    PrintRuntimeTypeArgs *pArgs = (PrintRuntimeTypeArgs *)token;

    if (pArgs->mtOfRuntimeType == NULL)
    {
        NameForMT_s(methodTable, g_mdName, mdNameLen);

        if (_wcscmp(g_mdName, W("System.RuntimeType")) == 0)
        {
            pArgs->mtOfRuntimeType = methodTable;
            pArgs->handleFieldOffset = GetObjFieldOffset(objAddr, methodTable, W("m_handle"));
            if (pArgs->handleFieldOffset <= 0)
                ExtOut("Error getting System.RuntimeType.m_handle offset\n");

            pArgs->adstore.Request(g_sos);
        }
    }

    if ((methodTable == pArgs->mtOfRuntimeType) && (pArgs->handleFieldOffset > 0))
    {
        // Get the method table and display the information.
        DWORD_PTR mtPtr;
        if (MOVE(mtPtr, objAddr + pArgs->handleFieldOffset) == S_OK)
        {
            DMLOut(DMLObject(objAddr));

            CLRDATA_ADDRESS appDomain = GetAppDomainForMT(mtPtr);
            if (appDomain != NULL)
            {
                if (appDomain == pArgs->adstore.sharedDomain)
                    ExtOut(" %" POINTERSIZE "s", "Shared");

                else if (appDomain == pArgs->adstore.systemDomain)
                    ExtOut(" %" POINTERSIZE "s", "System");
                else
                    DMLOut(" %s", DMLDomain(appDomain));
            }
            else
            {
                ExtOut(" %" POINTERSIZE "s", "?");
            }
        
            NameForMT_s(mtPtr, g_mdName, mdNameLen);
            DMLOut(" %s %S\n", DMLMethodTable(mtPtr), g_mdName);
        }
    }
}


DECLARE_API(DumpRuntimeTypes)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };

    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL))
        return Status;

    EnableDMLHolder dmlHolder(dml);

    ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s Type Name              \n",
           "Address", "Domain", "MT");
    ExtOut("------------------------------------------------------------------------------\n");

    PrintRuntimeTypeArgs pargs;
    ZeroMemory(&pargs, sizeof(PrintRuntimeTypeArgs));

    GCHeapsTraverse(PrintRuntimeTypes, (LPVOID)&pargs);
    return Status;
}

#define MIN_FRAGMENTATIONBLOCK_BYTES (1024*512)
namespace sos
{
    class FragmentationBlock
    {
    public:
        FragmentationBlock(TADDR addr, size_t size, TADDR next, TADDR mt)
            : mAddress(addr), mSize(size), mNext(next), mNextMT(mt)
        {
        }

        inline TADDR GetAddress() const
        {
            return mAddress;
        }
        inline size_t GetSize() const
        {
            return mSize;
        }

        inline TADDR GetNextObject() const
        {
            return mNext;
        }

        inline TADDR GetNextMT() const
        {
            return mNextMT;
        }

    private:
        TADDR mAddress;
        size_t mSize;
        TADDR mNext;
        TADDR mNextMT;
    };
}

class DumpHeapImpl
{
public:
    DumpHeapImpl(PCSTR args)
        : mStart(0), mStop(0), mMT(0),  mMinSize(0), mMaxSize(~0),
          mStat(FALSE), mStrings(FALSE), mVerify(FALSE),
          mThinlock(FALSE), mShort(FALSE), mDML(FALSE),
          mLive(FALSE), mDead(FALSE), mType(NULL)
    {
        ArrayHolder<char> type = NULL;

        TADDR minTemp = 0;
        CMDOption option[] = 
        {   // name, vptr, type, hasValue
            {"-mt", &mMT, COHEX, TRUE},              // dump objects with a given MethodTable
            {"-type", &type, COSTRING, TRUE},        // list objects of specified type
            {"-stat", &mStat, COBOOL, FALSE},        // dump a summary of types and the number of instances of each
            {"-strings", &mStrings, COBOOL, FALSE},  // dump a summary of string objects
            {"-verify", &mVerify, COBOOL, FALSE},    // verify heap objects (!heapverify)
            {"-thinlock", &mThinlock, COBOOL, FALSE},// list only thinlocks
            {"-short", &mShort, COBOOL, FALSE},      // list only addresses
            {"-min", &mMinSize, COHEX, TRUE},        // min size of objects to display
            {"-max", &mMaxSize, COHEX, TRUE},        // max size of objects to display
            {"-live", &mLive, COHEX, FALSE},         // only print live objects
            {"-dead", &mDead, COHEX, FALSE},         // only print dead objects
#ifndef FEATURE_PAL
            {"/d", &mDML, COBOOL, FALSE},            // Debugger Markup Language
#endif
        };

        CMDValue arg[] = 
        {   // vptr, type
            {&mStart, COHEX},
            {&mStop, COHEX}
        };

        size_t nArgs = 0;
        if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArgs))
            sos::Throw<sos::Exception>("Failed to parse command line arguments.");

        if (mStart == 0)
            mStart = minTemp;

        if (mStop == 0)
            mStop = sos::GCHeap::HeapEnd;

        if (type && mMT)
        {
            sos::Throw<sos::Exception>("Cannot specify both -mt and -type");
        }
        
        if (mLive && mDead)
        {
            sos::Throw<sos::Exception>("Cannot specify both -live and -dead.");
        }

        if (mMinSize > mMaxSize)
        {
            sos::Throw<sos::Exception>("wrong argument");
        }
        
        // If the user gave us a type, convert it to unicode and clean up "type".
        if (type && !mStrings)
        {
            size_t iLen = strlen(type) + 1;
            mType = new WCHAR[iLen];
            MultiByteToWideChar(CP_ACP, 0, type, -1, mType, (int)iLen);
        }
    }

    ~DumpHeapImpl()
    {
        if (mType)
            delete [] mType;
    }

    void Run()
    {
        // enable Debugger Markup Language
        EnableDMLHolder dmlholder(mDML); 
        sos::GCHeap gcheap;

        if (!gcheap.AreGCStructuresValid())
            DisplayInvalidStructuresMessage();
        
        if (IsMiniDumpFile())
        {
            ExtOut("In a minidump without full memory, most gc heap structures will not be valid.\n");
            ExtOut("If you need this functionality, get a full memory dump with \".dump /ma mydump.dmp\"\n");
        }

#ifndef FEATURE_PAL
        if (mLive || mDead)
        {
            GCRootImpl gcroot;
            mLiveness = gcroot.GetLiveObjects();
        }
#endif

        // Some of the "specialty" versions of DumpHeap have slightly
        // different implementations than the standard version of DumpHeap.
        // We seperate them out to not clutter the standard DumpHeap function.
        if (mShort)
            DumpHeapShort(gcheap);
        else if (mThinlock)
            DumpHeapThinlock(gcheap);
        else if (mStrings)
            DumpHeapStrings(gcheap);
        else
            DumpHeap(gcheap);

        if (mVerify)
            ValidateSyncTable(gcheap);
    }

    static bool ValidateSyncTable(sos::GCHeap &gcheap)
    {
        bool succeeded = true;
        for (sos::SyncBlkIterator itr; itr; ++itr)
        {
            sos::CheckInterrupt();

            if (!itr->IsFree())
            {
                if (!sos::IsObject(itr->GetObject(), true))
                {
                    ExtOut("SyncBlock %d corrupted, points to invalid object %p\n", 
                            itr->GetIndex(), SOS_PTR(itr->GetObject()));
                        succeeded = false;
                }
                else
                {
                    // Does the object header point to this syncblock index?
                    sos::Object obj = itr->GetObject();
                    ULONG header = 0;

                    if (!obj.TryGetHeader(header))
                    {
                        ExtOut("Failed to get object header for object %p while inspecting syncblock at index %d.\n",
                                SOS_PTR(itr->GetObject()), itr->GetIndex());
                        succeeded = false;
                    }
                    else
                    {
                        bool valid = false;
                        if ((header & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0 && (header & BIT_SBLK_IS_HASHCODE) == 0)
                        {
                            ULONG index = header & MASK_SYNCBLOCKINDEX;
                            valid = (ULONG)itr->GetIndex() == index;
                        }
                        
                        if (!valid)
                        {
                            ExtOut("Object header for %p should have a SyncBlock index of %d.\n",
                                    SOS_PTR(itr->GetObject()), itr->GetIndex());
                            succeeded = false;
                        }
                    }
                }
            }
        }

        return succeeded;
    }
private:
    DumpHeapImpl(const DumpHeapImpl &);

    bool Verify(const sos::ObjectIterator &itr)
    {
        if (mVerify)
        {
            char buffer[1024];
            if (!itr.Verify(buffer, _countof(buffer)))
            {
                ExtOut(buffer);
                return false;
            }
        }
        
        return true;
    }

    bool IsCorrectType(const sos::Object &obj)
    {
        if (mMT != NULL)
            return mMT == obj.GetMT();

        if (mType != NULL)
        {
            WString name = obj.GetTypeName();
            return _wcsstr(name.c_str(), mType) != NULL;
        }

        return true;
    }

    bool IsCorrectSize(const sos::Object &obj)
    {
        size_t size = obj.GetSize();
        return size >= mMinSize && size <= mMaxSize;
    }

    bool IsCorrectLiveness(const sos::Object &obj)
    {
#ifndef FEATURE_PAL
        if (mLive && mLiveness.find(obj.GetAddress()) == mLiveness.end())
            return false;

        if (mDead && (mLiveness.find(obj.GetAddress()) != mLiveness.end() || obj.IsFree()))
            return false;
#endif
        return true;
    }



    inline void PrintHeader()
    {
        ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %8s\n", "Address", "MT", "Size");
    }

    void DumpHeap(sos::GCHeap &gcheap)
    {
        HeapStat stats;

        // For heap fragmentation tracking.
        TADDR lastFreeObj = NULL;
        size_t lastFreeSize = 0;

        if (!mStat)
            PrintHeader();

        for (sos::ObjectIterator itr = gcheap.WalkHeap(mStart, mStop); itr; ++itr)
        {
            if (!Verify(itr))
                return;

            bool onLOH = itr.IsCurrObjectOnLOH();

            // Check for free objects to report fragmentation
            if (lastFreeObj != NULL)
                ReportFreeObject(lastFreeObj, lastFreeSize, itr->GetAddress(), itr->GetMT());

            if (!onLOH && itr->IsFree())
            {
                lastFreeObj = *itr;
                lastFreeSize = itr->GetSize();
            }
            else
            {
                lastFreeObj = NULL;
            }

            if (IsCorrectType(*itr) && IsCorrectSize(*itr) && IsCorrectLiveness(*itr))
            {
                stats.Add((DWORD_PTR)itr->GetMT(), (DWORD)itr->GetSize());
                if (!mStat)
                    DMLOut("%s %s %8d%s\n", DMLObject(itr->GetAddress()), DMLDumpHeapMT(itr->GetMT()), itr->GetSize(), 
                                            itr->IsFree() ? " Free":"     ");
            }
        }

        if (!mStat)
            ExtOut("\n");

        stats.Sort();
        stats.Print();

        PrintFragmentationReport();
    }

    struct StringSetEntry
    {
        StringSetEntry() : count(0), size(0)
        {
            str[0] = 0;
        }
        
        StringSetEntry(__in_ecount(64) WCHAR tmp[64], size_t _size)
            : count(1), size(_size)
        {
            memcpy(str, tmp, sizeof(str));
        }
        
        void Add(size_t _size) const
        {
            count++;
            size += _size;
        }
        
        mutable size_t count;
        mutable size_t size;
        WCHAR str[64];
        
        bool operator<(const StringSetEntry &rhs) const
        {
            return _wcscmp(str, rhs.str) < 0;
        }
    };

    
    static bool StringSetCompare(const StringSetEntry &a1, const StringSetEntry &a2)
    {
        return a1.size < a2.size;
    }

    void DumpHeapStrings(sos::GCHeap &gcheap)
    {
#ifdef FEATURE_PAL
        ExtOut("Not implemented.\n");
#else
        const int offset = sos::Object::GetStringDataOffset();
        typedef std::set<StringSetEntry> Set;
        Set set;            // A set keyed off of the string's text
        
        StringSetEntry tmp;  // Temp string used to keep track of the set
        ULONG fetched = 0;

        TableOutput out(3, POINTERSIZE_HEX, AlignRight);
        for (sos::ObjectIterator itr = gcheap.WalkHeap(mStart, mStop); itr; ++itr)
        {
            if (IsInterrupt())
                break;
                
            if (itr->IsString() && IsCorrectSize(*itr) && IsCorrectLiveness(*itr))
            {
                CLRDATA_ADDRESS addr = itr->GetAddress();
                size_t size = itr->GetSize();
                
                if (!mStat)
                    out.WriteRow(ObjectPtr(addr), Pointer(itr->GetMT()), Decimal(size));

                // Don't bother calculating the size of the string, just read the full 64 characters of the buffer.  The null
                // terminator we read will terminate the string.
                HRESULT hr = g_ExtData->ReadVirtual(TO_CDADDR(addr+offset), tmp.str, sizeof(WCHAR)*(_countof(tmp.str)-1), &fetched);
                if (SUCCEEDED(hr))
                {
                    // Ensure we null terminate the string.  Note that this will not overrun the buffer as we only
                    // wrote a max of 63 characters into the 64 character buffer.
                    tmp.str[fetched/sizeof(WCHAR)] = 0;
                    Set::iterator sitr = set.find(tmp);
                    if (sitr == set.end())
                    {
                        tmp.size = size;
                        tmp.count = 1;
                        set.insert(tmp);
                    }
                    else
                    {
                        sitr->Add(size);
                    }
                }
            }
        }

        ExtOut("\n");

        // Now flatten the set into a vector.  This is much faster than keeping two sets, or using a multimap.
        typedef std::vector<StringSetEntry> Vect;
        Vect v(set.begin(), set.end());
        std::sort(v.begin(), v.end(), &DumpHeapImpl::StringSetCompare);

        // Now print out the data.  The call to Flatten ensures that we don't print newlines to break up the
        // output in strange ways.
        for (Vect::iterator vitr = v.begin(); vitr != v.end(); ++vitr)
        {
            if (IsInterrupt())
                break;
                
            Flatten(vitr->str, (unsigned int)_wcslen(vitr->str));
            out.WriteRow(Decimal(vitr->size), Decimal(vitr->count), vitr->str);
        }
#endif // FEATURE_PAL
    }

    void DumpHeapShort(sos::GCHeap &gcheap)
    {
        for (sos::ObjectIterator itr = gcheap.WalkHeap(mStart, mStop); itr; ++itr)
        {
            if (!Verify(itr))
                return;

            if (IsCorrectType(*itr) && IsCorrectSize(*itr) && IsCorrectLiveness(*itr))
                DMLOut("%s\n", DMLObject(itr->GetAddress()));
        }
    }

    void DumpHeapThinlock(sos::GCHeap &gcheap)
    {
        int count = 0;

        PrintHeader();
        for (sos::ObjectIterator itr = gcheap.WalkHeap(mStart, mStop); itr; ++itr)
        {
            if (!Verify(itr))
                return;

            sos::ThinLockInfo lockInfo; 
            if (IsCorrectType(*itr) && itr->GetThinLock(lockInfo))
            {
                DMLOut("%s %s %8d", DMLObject(itr->GetAddress()), DMLDumpHeapMT(itr->GetMT()), itr->GetSize());
                ExtOut(" ThinLock owner %x (%p) Recursive %x\n", lockInfo.ThreadId,
                                        SOS_PTR(lockInfo.ThreadPtr), lockInfo.Recursion);

                count++;
            }
        }

        ExtOut("Found %d objects.\n", count);
    }

private:
    TADDR mStart,
          mStop,
          mMT,
          mMinSize,
          mMaxSize;

    BOOL mStat,
         mStrings,
         mVerify,
         mThinlock,
         mShort,
         mDML,
         mLive,
         mDead;


    WCHAR *mType;

private:
#if !defined(FEATURE_PAL)
    // Windows only
    std::unordered_set<TADDR> mLiveness;
    typedef std::list<sos::FragmentationBlock> FragmentationList;
    FragmentationList mFrag;

    void InitFragmentationList()
    {
        mFrag.clear();
    }

    void ReportFreeObject(TADDR addr, size_t size, TADDR next, TADDR mt)
    {
        if (size >= MIN_FRAGMENTATIONBLOCK_BYTES)
            mFrag.push_back(sos::FragmentationBlock(addr, size, next, mt));
    }

    void PrintFragmentationReport()
    {
        if (mFrag.size() > 0)
        {
            ExtOut("Fragmented blocks larger than 0.5 MB:\n");
            ExtOut("%" POINTERSIZE "s %8s %16s\n", "Addr", "Size", "Followed by");
 
            for (FragmentationList::const_iterator itr = mFrag.begin(); itr != mFrag.end(); ++itr)
            {
                sos::MethodTable mt = itr->GetNextMT();
                ExtOut("%p %6.1fMB " WIN64_8SPACES "%p %S\n",
                            SOS_PTR(itr->GetAddress()),
                            ((double)itr->GetSize()) / 1024.0 / 1024.0,
                            SOS_PTR(itr->GetNextObject()),
                            mt.GetName());
            }
        }
    }
#else
    void InitFragmentationList() {}
    void ReportFreeObject(TADDR, TADDR, size_t, TADDR) {}
    void PrintFragmentationReport() {}
#endif
};

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function dumps all objects on GC heap. It also displays      *  
*    statistics of objects.  If GC heap is corrupted, it will stop at 
*    the bad place.  (May not work if GC is in progress.)              *
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpHeap)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();

    if (!g_snapshot.Build())
    {
        ExtOut("Unable to build snapshot of the garbage collector state\n");
        return E_FAIL;
    }

    try
    {
        DumpHeapImpl dumpHeap(args);
        dumpHeap.Run();

        return S_OK;
    }
    catch(const sos::Exception &e)
    {
        ExtOut("%s\n", e.what());
        return E_FAIL;
    }
}

DECLARE_API(VerifyHeap)
{    
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    
    if (!g_snapshot.Build())
    {
        ExtOut("Unable to build snapshot of the garbage collector state\n");
        return E_FAIL;
    }
    
    try
    {
        bool succeeded = true;
        char buffer[1024];
        sos::GCHeap gcheap;
        sos::ObjectIterator itr = gcheap.WalkHeap();

        while (itr)
        {
            if (itr.Verify(buffer, _countof(buffer)))
            {
                ++itr;
            }
            else
            {
                succeeded = false;
                ExtOut(buffer);
                itr.MoveToNextObjectCarefully();
            }
        }

        if (!DumpHeapImpl::ValidateSyncTable(gcheap))
            succeeded = false;

        if (succeeded)
            ExtOut("No heap corruption detected.\n");

        return S_OK;
    }
    catch(const sos::Exception &e)
    {
        ExtOut("%s\n", e.what());
        return E_FAIL;
    }
}

#ifndef FEATURE_PAL

enum failure_get_memory
{
    fgm_no_failure = 0,
    fgm_reserve_segment = 1,
    fgm_commit_segment_beg = 2,
    fgm_commit_eph_segment = 3,
    fgm_grow_table = 4,
    fgm_commit_table = 5
};

enum oom_reason
{
    oom_no_failure = 0,
    oom_budget = 1,
    oom_cant_commit = 2,
    oom_cant_reserve = 3,
    oom_loh = 4,
    oom_low_mem = 5,
    oom_unproductive_full_gc = 6
};

static const char *const str_oom[] = 
{
    "There was no managed OOM due to allocations on the GC heap", // oom_no_failure 
    "This is likely to be a bug in GC", // oom_budget
    "Didn't have enough memory to commit", // oom_cant_commit
    "This is likely to be a bug in GC", // oom_cant_reserve 
    "Didn't have enough memory to allocate an LOH segment", // oom_loh 
    "Low on memory during GC", // oom_low_mem 
    "Could not do a full GC" // oom_unproductive_full_gc
};

static const char *const str_fgm[] = 
{
    "There was no failure to allocate memory", // fgm_no_failure 
    "Failed to reserve memory", // fgm_reserve_segment
    "Didn't have enough memory to commit beginning of the segment", // fgm_commit_segment_beg
    "Didn't have enough memory to commit the new ephemeral segment", // fgm_commit_eph_segment
    "Didn't have enough memory to grow the internal GC datastructures", // fgm_grow_table
    "Didn't have enough memory to commit the internal GC datastructures", // fgm_commit_table
};

void PrintOOMInfo(DacpOomData* oomData)
{
    ExtOut("Managed OOM occurred after GC #%d (Requested to allocate %d bytes)\n", 
        oomData->gc_index, oomData->alloc_size);

    if ((oomData->reason == oom_budget) ||
        (oomData->reason == oom_cant_reserve))
    {
        // TODO: This message needs to be updated with more precious info.
        ExtOut("%s, please contact PSS\n", str_oom[oomData->reason]);
    }
    else
    {
        ExtOut("Reason: %s\n", str_oom[oomData->reason]);
    }

    // Now print out the more detailed memory info if any.
    if (oomData->fgm != fgm_no_failure)
    {
        ExtOut("Detail: %s: %s (%d bytes)", 
            (oomData->loh_p ? "LOH" : "SOH"), 
            str_fgm[oomData->fgm],
            oomData->size);
    
        if ((oomData->fgm == fgm_commit_segment_beg) ||
            (oomData->fgm == fgm_commit_eph_segment) ||
            (oomData->fgm == fgm_grow_table) ||
            (oomData->fgm == fgm_commit_table))
        {
            // If it's a commit error (fgm_grow_table can indicate a reserve
            // or a commit error since we make one VirtualAlloc call to
            // reserve and commit), we indicate the available commit
            // space if we recorded it.
            if (oomData->available_pagefile_mb)
            {
                ExtOut(" - on GC entry available commit space was %d MB",
                    oomData->available_pagefile_mb);
            }
        }

        ExtOut("\n");
    }
}

DECLARE_API(AnalyzeOOM)
{    
    INIT_API();    
    MINIDUMP_NOT_SUPPORTED();    
    
#ifndef FEATURE_PAL

    if (!InitializeHeapData ())
    {
        ExtOut("GC Heap not initialized yet.\n");
        return S_OK;
    }

    BOOL bHasManagedOOM = FALSE;
    DacpOomData oomData;
    memset (&oomData, 0, sizeof(oomData));
    if (!IsServerBuild())
    {
        if (oomData.Request(g_sos) != S_OK)
        {
            ExtOut("Error requesting OOM data\n");
            return E_FAIL;
        }
        if (oomData.reason != oom_no_failure)
        {
            bHasManagedOOM = TRUE;
            PrintOOMInfo(&oomData);
        }
    }
    else
    {   
        DWORD dwNHeaps = GetGcHeapCount();
        DWORD dwAllocSize;
        if (!ClrSafeInt<DWORD>::multiply(sizeof(CLRDATA_ADDRESS), dwNHeaps, dwAllocSize))
        {
            ExtOut("Failed to get GCHeaps:  integer overflow\n");
            return Status;
        }

        CLRDATA_ADDRESS *heapAddrs = (CLRDATA_ADDRESS*)alloca(dwAllocSize);
        if (g_sos->GetGCHeapList(dwNHeaps, heapAddrs, NULL) != S_OK)
        {
            ExtOut("Failed to get GCHeaps\n");
            return Status;
        }
        
        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            if (oomData.Request(g_sos, heapAddrs[n]) != S_OK)
            {
                ExtOut("Heap %d: Error requesting OOM data\n", n);
                return E_FAIL;
            }
            if (oomData.reason != oom_no_failure)
            {
                if (!bHasManagedOOM)
                {
                    bHasManagedOOM = TRUE;
                }
                ExtOut("---------Heap %#-2d---------\n", n);
                PrintOOMInfo(&oomData);
            }
        }
    }

    if (!bHasManagedOOM)
    {
        ExtOut("%s\n", str_oom[oomData.reason]);
    }

    return S_OK;
#else
    _ASSERTE(false);
    return E_FAIL;
#endif // FEATURE_PAL
}

DECLARE_API(VerifyObj)
{
    INIT_API();    
    MINIDUMP_NOT_SUPPORTED();

    TADDR  taddrObj = 0;
    TADDR  taddrMT;
    size_t objSize;

    BOOL bValid = FALSE;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&taddrObj, COHEX}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    BOOL bContainsPointers;

    if (FAILED(GetMTOfObject(taddrObj, &taddrMT)) ||
        !GetSizeEfficient(taddrObj, taddrMT, FALSE, objSize, bContainsPointers))
    {
        ExtOut("object %#p does not have valid method table\n", SOS_PTR(taddrObj));
        goto Exit;
    }

    // we need to build g_snapshot as it is later used in GetGeneration
    if (!g_snapshot.Build())
    {
        ExtOut("Unable to build snapshot of the garbage collector state\n");
        goto Exit;
    }
    {
        DacpGcHeapDetails *pheapDetails = g_snapshot.GetHeap(taddrObj);
        bValid = VerifyObject(*pheapDetails, taddrObj, taddrMT, objSize, TRUE);
    }

Exit:
    if (bValid)
    {
        ExtOut("object %#p is a valid object\n", SOS_PTR(taddrObj));
    }

    return Status;
}

void LNODisplayOutput(LPCWSTR tag, TADDR pMT, TADDR currentObj, size_t size) 
{
    sos::Object obj(currentObj, pMT);
    DMLOut("%S %s %12d (0x%x)\t%S\n", tag, DMLObject(currentObj), size, size, obj.GetTypeName());
}

DECLARE_API(ListNearObj)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

#if !defined(FEATURE_PAL)

    TADDR taddrArg = 0;
    TADDR taddrObj = 0;
    // we may want to provide a more exact version of searching for the 
    // previous object in the heap, using the brick table, instead of 
    // looking for what may be valid method tables...
    //BOOL bExact;
    //CMDOption option[] = 
    //{
    //    // name, vptr, type, hasValue
    //    {"-exact", &bExact, COBOOL, FALSE}
    //};

    BOOL dml = FALSE;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {
        // vptr, type
        {&taddrArg, COHEX}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg) || nArg != 1)
    {
        ExtOut("Usage: !ListNearObj <obj_address>\n");
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);

    if (!g_snapshot.Build())
    {
        ExtOut("Unable to build snapshot of the garbage collector state\n");
        return Status;    
    }

    taddrObj = Align(taddrArg);

    DacpGcHeapDetails *heap = g_snapshot.GetHeap(taddrArg);
    if (heap == NULL)
    {
        ExtOut("Address %p does not lie in the managed heap\n", SOS_PTR(taddrObj));
        return Status;
    }

    TADDR_SEGINFO trngSeg  = {0, 0, 0};
    TADDR_RANGE   allocCtx = {0, 0};
    BOOL          bLarge;
    int           gen;
    if (!GCObjInHeap(taddrObj, *heap, trngSeg, gen, allocCtx, bLarge))
    {
        ExtOut("Failed to find the segment of the managed heap where the object %p resides\n", 
            SOS_PTR(taddrObj));
        return Status;
    }

    TADDR  objMT = NULL;
    size_t objSize = 0;
    BOOL   bObj    = FALSE;
    TADDR  taddrCur;
    TADDR  curMT   = 0;
    size_t curSize = 0;
    BOOL   bCur    = FALSE;
    TADDR  taddrNxt;
    TADDR  nxtMT   = 0;
    size_t nxtSize = 0;
    BOOL   bNxt    = FALSE;
    BOOL   bContainsPointers;

    std::vector<TADDR> candidate;
    candidate.reserve(10);

    // since we'll be reading back I'll prime the read cache to a buffer before the current address
    MOVE(taddrCur, _max(trngSeg.start, taddrObj-DT_OS_PAGE_SIZE));

    // ===== Look for a good candidate preceeding taddrObj

    for (taddrCur = taddrObj - sizeof(TADDR); taddrCur >= trngSeg.start; taddrCur -= sizeof(TADDR))
    {
        // currently we don't pay attention to allocation contexts.  if this
        // proves to be an issue we need to reconsider the code below
        if (SUCCEEDED(GetMTOfObject(taddrCur, &curMT)) &&
            GetSizeEfficient(taddrCur, curMT, bLarge, curSize, bContainsPointers))
        {
            // remember this as one of the possible "good" objects preceeding taddrObj
            candidate.push_back(taddrCur);

            std::vector<TADDR>::iterator it = 
                std::find(candidate.begin(), candidate.end(), taddrCur+curSize);
            if (it != candidate.end())
            {
                // We found a chain of two objects preceeding taddrObj.  We'll
                // trust this is a good indication that the two objects are valid.
                // What is not valid is possibly the object following the second 
                // one...
                taddrCur = *it;
                GetMTOfObject(taddrCur, &curMT);
                GetSizeEfficient(taddrCur, curMT, bLarge, curSize, bContainsPointers);
                bCur = TRUE;
                break;
            }
        }
    }

    if (!bCur && !candidate.empty())
    {
        // pick the closest object to taddrObj
        taddrCur = *(candidate.begin());
        GetMTOfObject(taddrCur, &curMT);
        GetSizeEfficient(taddrCur, curMT, bLarge, curSize, bContainsPointers);
        // we have a candidate, even if not confirmed
        bCur = TRUE;
    }

    taddrNxt = taddrObj;
    if (taddrArg == taddrObj) 
    {
        taddrNxt += sizeof(TADDR);
    }

    // ===== Now look at taddrObj
    if (taddrObj == taddrArg) 
    {
        // only look at taddrObj if it's the same as what user passed in, meaning it's aligned.  
        if (SUCCEEDED(GetMTOfObject(taddrObj, &objMT)) &&
            GetSizeEfficient(taddrObj, objMT, bLarge, objSize, bContainsPointers))
        {
            bObj = TRUE;
            taddrNxt = taddrObj+objSize;
        }
    }

    if ((taddrCur + curSize > taddrArg) && taddrCur + curSize < trngSeg.end)
    {
        if (SUCCEEDED(GetMTOfObject(taddrCur + curSize, &nxtMT)) &&
            GetSizeEfficient(taddrObj, objMT, bLarge, objSize, bContainsPointers))
        {
            taddrNxt = taddrCur+curSize;
        }
    }

    // ===== And finally move on to elements following taddrObj
    
    for (; taddrNxt < trngSeg.end; taddrNxt += sizeof(TADDR))
    {
        if (SUCCEEDED(GetMTOfObject(taddrNxt, &nxtMT)) &&
            GetSizeEfficient(taddrNxt, nxtMT, bLarge, nxtSize, bContainsPointers))
        {
            bNxt = TRUE;
            break;
        }
    }

    if (bCur)
        LNODisplayOutput(W("Before: "), curMT, taddrCur, curSize);
    else
        ExtOut("Before: couldn't find any object between %#p and %#p\n",
            SOS_PTR(trngSeg.start), SOS_PTR(taddrArg));

    if (bObj)
        LNODisplayOutput(W("Current:"), objMT, taddrObj, objSize);

    if (bNxt)
        LNODisplayOutput(W("After:  "), nxtMT, taddrNxt, nxtSize);
    else
        ExtOut("After:  couldn't find any object between %#p and %#p\n",
            SOS_PTR(taddrArg), SOS_PTR(trngSeg.end));

    if (bCur && bNxt && 
        (((taddrCur+curSize == taddrObj) && (taddrObj+objSize == taddrNxt)) || (taddrCur+curSize == taddrNxt)))
    {
        ExtOut("Heap local consistency confirmed.\n");
    }
    else
    {
        ExtOut("Heap local consistency not confirmed.\n");
    }

    return Status;    

#else

    _ASSERTE(false);
    return E_FAIL;

#endif // FEATURE_PAL
}


DECLARE_API(GCHeapStat)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    

#ifndef FEATURE_PAL

    BOOL bIncUnreachable = FALSE;
    BOOL dml = FALSE;

    CMDOption option[] = {
        // name, vptr, type, hasValue
        {"-inclUnrooted", &bIncUnreachable, COBOOL, FALSE},
        {"-iu",           &bIncUnreachable, COBOOL, FALSE},
        {"/d",            &dml, COBOOL, FALSE}
    };
    
    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    ExtOut("%-8s %12s %12s %12s %12s\n", "Heap", "Gen0", "Gen1", "Gen2", "LOH");

    if (!IsServerBuild())
    {
        float tempf;
        DacpGcHeapDetails heapDetails;
        if (heapDetails.Request(g_sos) != S_OK)
        {
            ExtErr("Error requesting gc heap details\n");
            return Status;
        }

        HeapUsageStat hpUsage;
        if (GCHeapUsageStats(heapDetails, bIncUnreachable, &hpUsage))
        {
            ExtOut("Heap%-4d %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u\n", 0, 
                hpUsage.genUsage[0].allocd, hpUsage.genUsage[1].allocd, 
                hpUsage.genUsage[2].allocd, hpUsage.genUsage[3].allocd);
            ExtOut("\nFree space:                                                 Percentage\n");
            ExtOut("Heap%-4d %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u", 0, 
                hpUsage.genUsage[0].freed, hpUsage.genUsage[1].freed, 
                hpUsage.genUsage[2].freed, hpUsage.genUsage[3].freed);
            tempf = ((float)(hpUsage.genUsage[0].freed+hpUsage.genUsage[1].freed+hpUsage.genUsage[2].freed)) /
                (hpUsage.genUsage[0].allocd+hpUsage.genUsage[1].allocd+hpUsage.genUsage[2].allocd);
            ExtOut("SOH:%3d%% LOH:%3d%%\n", (int)(100 * tempf), 
                (int)(100*((float)hpUsage.genUsage[3].freed) / (hpUsage.genUsage[3].allocd)));
            if (bIncUnreachable)
            {
            ExtOut("\nUnrooted objects:                                           Percentage\n");
            ExtOut("Heap%-4d %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u", 0, 
                hpUsage.genUsage[0].unrooted, hpUsage.genUsage[1].unrooted, 
                hpUsage.genUsage[2].unrooted, hpUsage.genUsage[3].unrooted);
            tempf = ((float)(hpUsage.genUsage[0].unrooted+hpUsage.genUsage[1].unrooted+hpUsage.genUsage[2].unrooted)) / 
                (hpUsage.genUsage[0].allocd+hpUsage.genUsage[1].allocd+hpUsage.genUsage[2].allocd);
            ExtOut("SOH:%3d%% LOH:%3d%%\n", (int)(100 * tempf),
                (int)(100*((float)hpUsage.genUsage[3].unrooted) / (hpUsage.genUsage[3].allocd)));
            }
        }
    }
    else
    {
        float tempf;
        DacpGcHeapData gcheap;
        if (gcheap.Request(g_sos) != S_OK)
        {
            ExtErr("Error requesting GC Heap data\n");
            return Status;
        }

        DWORD dwAllocSize;
        DWORD dwNHeaps = gcheap.HeapCount;
        if (!ClrSafeInt<DWORD>::multiply(sizeof(CLRDATA_ADDRESS), dwNHeaps, dwAllocSize))
        {
            ExtErr("Failed to get GCHeaps:  integer overflow\n");
            return Status;
        }

        CLRDATA_ADDRESS *heapAddrs = (CLRDATA_ADDRESS*)alloca(dwAllocSize);
        if (g_sos->GetGCHeapList(dwNHeaps, heapAddrs, NULL) != S_OK)
        {
            ExtErr("Failed to get GCHeaps\n");
            return Status;
        }

        ArrayHolder<HeapUsageStat> hpUsage = new NOTHROW HeapUsageStat[dwNHeaps];
        if (hpUsage == NULL)
        {
            ReportOOM();
            return Status;
        }

        // aggregate stats accross heaps / generation
        GenUsageStat genUsageStat[4] = {0, 0, 0, 0};

        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            DacpGcHeapDetails heapDetails;
            if (heapDetails.Request(g_sos, heapAddrs[n]) != S_OK)
            {
                ExtErr("Error requesting gc heap details\n");
                return Status;
            }

            if (GCHeapUsageStats(heapDetails, bIncUnreachable, &hpUsage[n]))
            {
                for (int i = 0; i < 4; ++i)
                {
                    genUsageStat[i].allocd   += hpUsage[n].genUsage[i].allocd;
                    genUsageStat[i].freed    += hpUsage[n].genUsage[i].freed;
                    if (bIncUnreachable)
                    {
                    genUsageStat[i].unrooted += hpUsage[n].genUsage[i].unrooted;
                    }
                }
            }
        }

        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            ExtOut("Heap%-4d %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u\n", n, 
                hpUsage[n].genUsage[0].allocd, hpUsage[n].genUsage[1].allocd, 
                hpUsage[n].genUsage[2].allocd, hpUsage[n].genUsage[3].allocd);
        }
        ExtOut("Total    %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u\n",
            genUsageStat[0].allocd, genUsageStat[1].allocd, 
            genUsageStat[2].allocd, genUsageStat[3].allocd);

        ExtOut("\nFree space:                                                 Percentage\n");
        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            ExtOut("Heap%-4d %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u", n, 
                hpUsage[n].genUsage[0].freed, hpUsage[n].genUsage[1].freed, 
                hpUsage[n].genUsage[2].freed, hpUsage[n].genUsage[3].freed);

            tempf = ((float)(hpUsage[n].genUsage[0].freed+hpUsage[n].genUsage[1].freed+hpUsage[n].genUsage[2].freed)) /
                (hpUsage[n].genUsage[0].allocd+hpUsage[n].genUsage[1].allocd+hpUsage[n].genUsage[2].allocd);
            ExtOut("SOH:%3d%% LOH:%3d%%\n", (int)(100 * tempf), 
                (int)(100*((float)hpUsage[n].genUsage[3].freed) / (hpUsage[n].genUsage[3].allocd))
            );
        }
        ExtOut("Total    %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u\n",
            genUsageStat[0].freed, genUsageStat[1].freed, 
            genUsageStat[2].freed, genUsageStat[3].freed);

        if (bIncUnreachable)
        {
            ExtOut("\nUnrooted objects:                                           Percentage\n");
            for (DWORD n = 0; n < dwNHeaps; n ++)
            {
                ExtOut("Heap%-4d %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u", n, 
                    hpUsage[n].genUsage[0].unrooted, hpUsage[n].genUsage[1].unrooted, 
                    hpUsage[n].genUsage[2].unrooted, hpUsage[n].genUsage[3].unrooted);

                tempf = ((float)(hpUsage[n].genUsage[0].unrooted+hpUsage[n].genUsage[1].unrooted+hpUsage[n].genUsage[2].unrooted)) / 
                    (hpUsage[n].genUsage[0].allocd+hpUsage[n].genUsage[1].allocd+hpUsage[n].genUsage[2].allocd);
                ExtOut("SOH:%3d%% LOH:%3d%%\n", (int)(100 * tempf),
                    (int)(100*((float)hpUsage[n].genUsage[3].unrooted) / (hpUsage[n].genUsage[3].allocd)));
            }
            ExtOut("Total    %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u %12" POINTERSIZE_TYPE "u\n",
                genUsageStat[0].unrooted, genUsageStat[1].unrooted, 
                genUsageStat[2].unrooted, genUsageStat[3].unrooted);
        }

    }

    return Status;
    
#else

    _ASSERTE(false);
    return E_FAIL;

#endif // FEATURE_PAL
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function dumps what is in the syncblock cache.  By default   *  
*    it dumps all active syncblocks.  Using -all to dump all syncblocks
*                                                                      *
\**********************************************************************/
DECLARE_API(SyncBlk)
{
    INIT_API();    
    MINIDUMP_NOT_SUPPORTED();    
    
    BOOL bDumpAll = FALSE;
    size_t nbAsked = 0;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-all", &bDumpAll, COBOOL, FALSE},
        {"/d", &dml, COBOOL, FALSE}
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&nbAsked, COSIZE_T}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    DacpSyncBlockData syncBlockData;
    if (syncBlockData.Request(g_sos,1) != S_OK)
    {
        ExtOut("Error requesting SyncBlk data\n");
        return Status;
    }

    DWORD dwCount = syncBlockData.SyncBlockCount;
    
    ExtOut("Index" WIN64_8SPACES " SyncBlock MonitorHeld Recursion Owning Thread Info" WIN64_8SPACES "  SyncBlock Owner\n");
    ULONG freeCount = 0;
    ULONG CCWCount = 0;
    ULONG RCWCount = 0;
    ULONG CFCount = 0;
    for (DWORD nb = 1; nb <= dwCount; nb++)
    {
        if (IsInterrupt())
            return Status;
        
        if (nbAsked && nb != nbAsked) 
        {
            continue;
        }

        if (syncBlockData.Request(g_sos,nb) != S_OK)
        {
            ExtOut("SyncBlock %d is invalid%s\n", nb,
                (nb != nbAsked) ? ", continuing..." : "");
            continue;
        }

        BOOL bPrint = (bDumpAll || nb == nbAsked || (syncBlockData.MonitorHeld > 0 && !syncBlockData.bFree));

        if (bPrint)
        {
            ExtOut("%5d ", nb);
            if (!syncBlockData.bFree || nb != nbAsked)
            {            
                ExtOut("%p  ", syncBlockData.SyncBlockPointer); 
                ExtOut("%11d ", syncBlockData.MonitorHeld);
                ExtOut("%9d ", syncBlockData.Recursion);
                ExtOut("%p ", syncBlockData.HoldingThread);

                if (syncBlockData.HoldingThread == ~0ul)
                {
                    ExtOut(" orphaned ");
                }
                else if (syncBlockData.HoldingThread != NULL)
                {
                    DacpThreadData Thread;
                    if ((Status = Thread.Request(g_sos, syncBlockData.HoldingThread)) != S_OK)
                    {
                        ExtOut("Failed to request Thread at %p\n", syncBlockData.HoldingThread);
                        return Status;
                    }

                    DMLOut(DMLThreadID(Thread.osThreadId));
                    ULONG id;
                    if (g_ExtSystem->GetThreadIdBySystemId(Thread.osThreadId, &id) == S_OK)
                    {
                        ExtOut("%4d ", id);
                    }
                    else
                    {
                        ExtOut(" XXX ");
                    }
                }
                else
                {
                    ExtOut("    none  ");
                }

                if (syncBlockData.bFree)
                {
                    ExtOut("  %8d", 0);    // TODO: do we need to print the free synctable list?
                }
                else
                {
                    sos::Object obj = TO_TADDR(syncBlockData.Object);
                    DMLOut("  %s %S", DMLObject(syncBlockData.Object), obj.GetTypeName());
                }
            }
        }
                                    
        if (syncBlockData.bFree) 
        {
            freeCount ++;
            if (bPrint) {
                ExtOut(" Free");
            }
        }
        else 
        {
#ifdef FEATURE_COMINTEROP            
            if (syncBlockData.COMFlags) {
                switch (syncBlockData.COMFlags) {
                case SYNCBLOCKDATA_COMFLAGS_CCW:
                    CCWCount ++;
                    break;
                case SYNCBLOCKDATA_COMFLAGS_RCW:
                    RCWCount ++;
                    break;
                case SYNCBLOCKDATA_COMFLAGS_CF:
                    CFCount ++;
                    break;
                }
            }
#endif // FEATURE_COMINTEROP            
        }

        if (syncBlockData.MonitorHeld > 1)            
        {
            // TODO: implement this
            /*
            ExtOut(" ");
            DWORD_PTR pHead = (DWORD_PTR)vSyncBlock.m_Link.m_pNext;
            DWORD_PTR pNext = pHead;
            Thread vThread;
    
            while (1)
            {
                if (IsInterrupt())
                    return Status;
                DWORD_PTR pWaitEventLink = pNext - offsetLinkSB;
                WaitEventLink vWaitEventLink;
                vWaitEventLink.Fill(pWaitEventLink);
                if (!CallStatus) {
                    break;
                }
                DWORD_PTR dwAddr = (DWORD_PTR)vWaitEventLink.m_Thread;
                ExtOut("%x ", dwAddr);
                vThread.Fill (dwAddr);
                if (!CallStatus) {
                    break;
                }
                if (bPrint)
                    DMLOut("%s,", DMLThreadID(vThread.m_OSThreadId));
                pNext = (DWORD_PTR)vWaitEventLink.m_LinkSB.m_pNext;
                if (pNext == 0)
                    break;
            }  
            */
        }
        
        if (bPrint)
            ExtOut("\n");
    }
    
    ExtOut("-----------------------------\n");
    ExtOut("Total           %d\n", dwCount);
    ExtOut("CCW             %d\n", CCWCount);
    ExtOut("RCW             %d\n", RCWCount);
    ExtOut("ComClassFactory %d\n", CFCount);
    ExtOut("Free            %d\n", freeCount);
   
    return Status;
}

#ifdef FEATURE_COMINTEROP
struct VisitRcwArgs
{
    BOOL bDetail;
    UINT MTACount;
    UINT STACount;
    ULONG FTMCount;
};

void VisitRcw(CLRDATA_ADDRESS RCW,CLRDATA_ADDRESS Context,CLRDATA_ADDRESS Thread, BOOL bIsFreeThreaded, LPVOID token)
{
    VisitRcwArgs *pArgs = (VisitRcwArgs *) token;

    if (pArgs->bDetail)
    {
        if (pArgs->MTACount == 0 && pArgs->STACount == 0 && pArgs->FTMCount == 0)
        {
            // First time, print a header
            ExtOut("RuntimeCallableWrappers (RCW) to be cleaned:\n");
            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s Apartment\n",
                "RCW", "CONTEXT", "THREAD");
        }        
        LPCSTR szThreadApartment;
        if (bIsFreeThreaded)
        {
            szThreadApartment = "(FreeThreaded)";
            pArgs->FTMCount++;
        }
        else if (Thread == NULL)
        {
            szThreadApartment = "(MTA)";
            pArgs->MTACount++;
        }
        else
        {
            szThreadApartment = "(STA)";
            pArgs->STACount++;
        }        
        
        ExtOut("%" POINTERSIZE "p %" POINTERSIZE "p %" POINTERSIZE "p %9s\n",
            SOS_PTR(RCW), 
            SOS_PTR(Context), 
            SOS_PTR(Thread),
            szThreadApartment);
    }
}

DECLARE_API(RCWCleanupList)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    DWORD_PTR p_CleanupList = GetExpression(args);

    VisitRcwArgs travArgs;
    ZeroMemory(&travArgs,sizeof(VisitRcwArgs));  
    travArgs.bDetail = TRUE;

    // We need to detect when !RCWCleanupList is called with an expression which evaluates to 0
    // (to print out an Invalid parameter message), but at the same time we need to allow an
    // empty argument list which would result in p_CleanupList equaling 0.
    if (p_CleanupList || strlen(args) == 0)
    {
        HRESULT hr = g_sos->TraverseRCWCleanupList(p_CleanupList, (VISITRCWFORCLEANUP)VisitRcw, &travArgs);
    
        if (SUCCEEDED(hr))
        {
            ExtOut("Free-Threaded Interfaces to be released: %d\n", travArgs.FTMCount);
            ExtOut("MTA Interfaces to be released: %d\n", travArgs.MTACount);
            ExtOut("STA Interfaces to be released: %d\n", travArgs.STACount);
        }
        else
        {
            ExtOut("An error occurred while traversing the cleanup list.\n");
        }
    }
    else
    {
        ExtOut("Invalid parameter %s\n", args);
    }
    
    return Status;
}
#endif // FEATURE_COMINTEROP


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of the finalizer     *
*    queue.                                                            *  
*                                                                      *
\**********************************************************************/
DECLARE_API(FinalizeQueue)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    BOOL bDetail = FALSE;
    BOOL bAllReady = FALSE;
    BOOL bShort    = FALSE;
    BOOL dml = FALSE;
    TADDR taddrMT  = 0;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-detail",   &bDetail,   COBOOL, FALSE},
        {"-allReady", &bAllReady, COBOOL, FALSE},
        {"-short",    &bShort,    COBOOL, FALSE},
        {"/d",        &dml,       COBOOL, FALSE},
        {"-mt",       &taddrMT,   COHEX,  TRUE},
    };

    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (!bShort)
    {
        DacpSyncBlockCleanupData dsbcd;
        CLRDATA_ADDRESS sbCurrent = NULL;
        ULONG cleanCount = 0;
        while ((dsbcd.Request(g_sos,sbCurrent) == S_OK) && dsbcd.SyncBlockPointer)
        {
            if (bDetail)
            {
                if (cleanCount == 0) // print first time only
                {
                    ExtOut("SyncBlocks to be cleaned by the finalizer thread:\n");
                    ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                        "SyncBlock", "RCW", "CCW", "ComClassFactory");                
                }
                
                ExtOut("%" POINTERSIZE "p %" POINTERSIZE "p %" POINTERSIZE "p %" POINTERSIZE "p\n", 
                    (ULONG64) dsbcd.SyncBlockPointer,
                    (ULONG64) dsbcd.blockRCW,
                    (ULONG64) dsbcd.blockCCW,
                    (ULONG64) dsbcd.blockClassFactory);
            }

            cleanCount++;
            sbCurrent = dsbcd.nextSyncBlock;
            if (sbCurrent == NULL)
            {
                break;
            }
        }

        ExtOut("SyncBlocks to be cleaned up: %d\n", cleanCount);

#ifdef FEATURE_COMINTEROP
        VisitRcwArgs travArgs;
        ZeroMemory(&travArgs,sizeof(VisitRcwArgs));  
        travArgs.bDetail = bDetail;
        g_sos->TraverseRCWCleanupList(0, (VISITRCWFORCLEANUP) VisitRcw, &travArgs);
        ExtOut("Free-Threaded Interfaces to be released: %d\n", travArgs.FTMCount);
        ExtOut("MTA Interfaces to be released: %d\n", travArgs.MTACount);
        ExtOut("STA Interfaces to be released: %d\n", travArgs.STACount);    
#endif // FEATURE_COMINTEROP    

// noRCW:
        ExtOut("----------------------------------\n");
    }

    // GC Heap
    DWORD dwNHeaps = GetGcHeapCount();

    HeapStat hpStat;

    if (!IsServerBuild())
    {
        DacpGcHeapDetails heapDetails;
        if (heapDetails.Request(g_sos) != S_OK)
        {
            ExtOut("Error requesting details\n");
            return Status;
        }

        GatherOneHeapFinalization(heapDetails, &hpStat, bAllReady, bShort);
    }
    else
    {   
        DWORD dwAllocSize;
        if (!ClrSafeInt<DWORD>::multiply(sizeof(CLRDATA_ADDRESS), dwNHeaps, dwAllocSize))
        {
            ExtOut("Failed to get GCHeaps:  integer overflow\n");
            return Status;
        }

        CLRDATA_ADDRESS *heapAddrs = (CLRDATA_ADDRESS*)alloca(dwAllocSize);
        if (g_sos->GetGCHeapList(dwNHeaps, heapAddrs, NULL) != S_OK)
        {
            ExtOut("Failed to get GCHeaps\n");
            return Status;
        }
        
        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            DacpGcHeapDetails heapDetails;
            if (heapDetails.Request(g_sos, heapAddrs[n]) != S_OK)
            {
                ExtOut("Error requesting details\n");
                return Status;
            }

            ExtOut("------------------------------\n");
            ExtOut("Heap %d\n", n);
            GatherOneHeapFinalization(heapDetails, &hpStat, bAllReady, bShort);
        }        
    }
    
    if (!bShort)
    {
        if (bAllReady)
        {
            PrintGCStat(&hpStat, "Statistics for all finalizable objects that are no longer rooted:\n");
        }
        else
        {
            PrintGCStat(&hpStat, "Statistics for all finalizable objects (including all objects ready for finalization):\n");
        }
    }

    return Status;
}

#endif // FEATURE_PAL

enum {
    // These are the values set in m_dwTransientFlags.
    // Note that none of these flags survive a prejit save/restore.

    M_CRST_NOTINITIALIZED       = 0x00000001,   // Used to prevent destruction of garbage m_crst
    M_LOOKUPCRST_NOTINITIALIZED = 0x00000002,

    SUPPORTS_UPDATEABLE_METHODS = 0x00000020,
    CLASSES_FREED               = 0x00000040,
    HAS_PHONY_IL_RVAS           = 0x00000080,
    IS_EDIT_AND_CONTINUE        = 0x00000200,
};

void ModuleMapTraverse(UINT index, CLRDATA_ADDRESS methodTable, LPVOID token)
{
    ULONG32 rid = (ULONG32)(size_t)token;
    NameForMT_s(TO_TADDR(methodTable), g_mdName, mdNameLen);

    DMLOut("%s 0x%08x %S\n", DMLMethodTable(methodTable), (ULONG32)TokenFromRid(rid, index), g_mdName);
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a Module          *
*    for a given address                                               *  
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpModule)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    
    DWORD_PTR p_ModuleAddr = NULL;
    BOOL bMethodTables = FALSE;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-mt", &bMethodTables, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE}
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&p_ModuleAddr, COHEX}
    };

    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (nArg != 1)
    {
        ExtOut("Usage: DumpModule [-mt] <Module Address>\n");
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    DacpModuleData module;
    if ((Status=module.Request(g_sos, TO_CDADDR(p_ModuleAddr)))!=S_OK)
    {
        ExtOut("Fail to fill Module %p\n", SOS_PTR(p_ModuleAddr));
        return Status;
    }
    
    WCHAR FileName[MAX_LONGPATH];
    FileNameForModule (&module, FileName);
    ExtOut("Name:       %S\n", FileName[0] ? FileName : W("Unknown Module"));

    ExtOut("Attributes: ");
    if (module.bIsPEFile)
        ExtOut("PEFile ");
    if (module.bIsReflection)
        ExtOut("Reflection ");
    if (module.dwTransientFlags & SUPPORTS_UPDATEABLE_METHODS)
        ExtOut("SupportsUpdateableMethods");
    ExtOut("\n");
    
    DMLOut("Assembly:   %s\n", DMLAssembly(module.Assembly));

    ExtOut("LoaderHeap:              %p\n", SOS_PTR(module.pLookupTableHeap));
    ExtOut("TypeDefToMethodTableMap: %p\n", SOS_PTR(module.TypeDefToMethodTableMap));
    ExtOut("TypeRefToMethodTableMap: %p\n", SOS_PTR(module.TypeRefToMethodTableMap));
    ExtOut("MethodDefToDescMap:      %p\n", SOS_PTR(module.MethodDefToDescMap));
    ExtOut("FieldDefToDescMap:       %p\n", SOS_PTR(module.FieldDefToDescMap));
    ExtOut("MemberRefToDescMap:      %p\n", SOS_PTR(module.MemberRefToDescMap));
    ExtOut("FileReferencesMap:       %p\n", SOS_PTR(module.FileReferencesMap));
    ExtOut("AssemblyReferencesMap:   %p\n", SOS_PTR(module.ManifestModuleReferencesMap));

    if (module.ilBase && module.metadataStart)
        ExtOut("MetaData start address:  %p (%d bytes)\n", SOS_PTR(module.metadataStart), module.metadataSize);

    if (bMethodTables)
    {
        ExtOut("\nTypes defined in this module\n\n");
        ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %s\n", "MT", "TypeDef", "Name");
                
        ExtOut("------------------------------------------------------------------------------\n");
        g_sos->TraverseModuleMap(TYPEDEFTOMETHODTABLE, TO_CDADDR(p_ModuleAddr), ModuleMapTraverse, (LPVOID)mdTypeDefNil);        

        ExtOut("\nTypes referenced in this module\n\n");
        ExtOut("%" POINTERSIZE "s   %" POINTERSIZE "s %s\n", "MT", "TypeRef", "Name");
        
        ExtOut("------------------------------------------------------------------------------\n");
        g_sos->TraverseModuleMap(TYPEREFTOMETHODTABLE, TO_CDADDR(p_ModuleAddr), ModuleMapTraverse, (LPVOID)mdTypeDefNil);     
    }
    
    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a Domain          *
*    for a given address                                               *  
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpDomain)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    
    DWORD_PTR p_DomainAddr = 0;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&p_DomainAddr, COHEX},
    };
    size_t nArg;

    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);

    DacpAppDomainStoreData adsData;
    if ((Status=adsData.Request(g_sos))!=S_OK)
    {
        ExtOut("Unable to get AppDomain information\n");
        return Status;
    }
    
    if (p_DomainAddr)
    {
        DacpAppDomainData appDomain1;
        if ((Status=appDomain1.Request(g_sos, TO_CDADDR(p_DomainAddr)))!=S_OK)
        {
            ExtOut("Fail to fill AppDomain\n");
            return Status;
        }

        ExtOut("--------------------------------------\n");

        if (p_DomainAddr == adsData.sharedDomain)
        {
            DMLOut("Shared Domain:      %s\n", DMLDomain(adsData.sharedDomain));
        }
        else if (p_DomainAddr == adsData.systemDomain)
        {
            DMLOut("System Domain:      %s\n", DMLDomain(adsData.systemDomain));
        }
        else
        {
            DMLOut("Domain %d:%s          %s\n", appDomain1.dwId, (appDomain1.dwId >= 10) ? "" : " ", DMLDomain(p_DomainAddr));
        }

        DomainInfo(&appDomain1);
        return Status;
    }
        
    ExtOut("--------------------------------------\n");
    DMLOut("System Domain:      %s\n", DMLDomain(adsData.systemDomain));
    DacpAppDomainData appDomain;
    if ((Status=appDomain.Request(g_sos,adsData.systemDomain))!=S_OK)
    {
        ExtOut("Unable to get system domain info.\n");
        return Status;
    }
    DomainInfo(&appDomain);
    
    ExtOut("--------------------------------------\n");
    DMLOut("Shared Domain:      %s\n", DMLDomain(adsData.sharedDomain));
    if ((Status=appDomain.Request(g_sos, adsData.sharedDomain))!=S_OK)
    {
        ExtOut("Unable to get shared domain info\n");
        return Status;
    }
    DomainInfo(&appDomain);

    ArrayHolder<CLRDATA_ADDRESS> pArray = new NOTHROW CLRDATA_ADDRESS[adsData.DomainCount];
    if (pArray==NULL)
    {
        ReportOOM();
        return Status;
    }

    if ((Status=g_sos->GetAppDomainList(adsData.DomainCount, pArray, NULL))!=S_OK)
    {
        ExtOut("Unable to get array of AppDomains\n");
        return Status;
    }

    for (int n=0;n<adsData.DomainCount;n++)
    {
        if (IsInterrupt())
            break;

        if ((Status=appDomain.Request(g_sos, pArray[n])) != S_OK)
        {
            ExtOut("Failed to get appdomain %p, error %lx\n", SOS_PTR(pArray[n]), Status);
            return Status;
        }

        ExtOut("--------------------------------------\n");
        DMLOut("Domain %d:%s          %s\n", appDomain.dwId, (appDomain.dwId >= 10) ? "" : " ", DMLDomain(pArray[n]));
        DomainInfo(&appDomain);
    }

    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a Assembly        *
*    for a given address                                               *  
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpAssembly)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    DWORD_PTR p_AssemblyAddr = 0;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&p_AssemblyAddr, COHEX},
    };
    size_t nArg;

    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);

    if (p_AssemblyAddr == 0)
    {
        ExtOut("Invalid Assembly %s\n", args);
        return Status;
    }
    
    DacpAssemblyData Assembly;
    if ((Status=Assembly.Request(g_sos, TO_CDADDR(p_AssemblyAddr)))!=S_OK)
    {
        ExtOut("Fail to fill Assembly\n");
        return Status;
    }
    DMLOut("Parent Domain:      %s\n", DMLDomain(Assembly.ParentDomain));
    if (g_sos->GetAssemblyName(TO_CDADDR(p_AssemblyAddr), mdNameLen, g_mdName, NULL)==S_OK)
        ExtOut("Name:               %S\n", g_mdName);
    else
        ExtOut("Name:               Unknown\n");

    AssemblyInfo(&Assembly);
    return Status;
}


String GetHostingCapabilities(DWORD hostConfig)
{
    String result;

    bool bAnythingPrinted = false;

#define CHK_AND_PRINT(hType,hStr)                                \
    if (hostConfig & (hType)) {                                  \
        if (bAnythingPrinted) result += ", ";                    \
        result += hStr;                                          \
        bAnythingPrinted = true;                                 \
    }

    CHK_AND_PRINT(CLRMEMORYHOSTED, "Memory");
    CHK_AND_PRINT(CLRTASKHOSTED, "Task");
    CHK_AND_PRINT(CLRSYNCHOSTED, "Sync");
    CHK_AND_PRINT(CLRTHREADPOOLHOSTED, "Threadpool");
    CHK_AND_PRINT(CLRIOCOMPLETIONHOSTED, "IOCompletion");
    CHK_AND_PRINT(CLRASSEMBLYHOSTED, "Assembly");
    CHK_AND_PRINT(CLRGCHOSTED, "GC");
    CHK_AND_PRINT(CLRSECURITYHOSTED, "Security");

#undef CHK_AND_PRINT

    return result;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the managed threads               *
*                                                                      *
\**********************************************************************/
HRESULT PrintThreadsFromThreadStore(BOOL bMiniDump, BOOL bPrintLiveThreadsOnly)
{
    HRESULT Status;
    
    DacpThreadStoreData ThreadStore;
    if ((Status = ThreadStore.Request(g_sos)) != S_OK)
    {
        Print("Failed to request ThreadStore\n");
        return Status;
    }

    TableOutput table(2, 17);

    table.WriteRow("ThreadCount:", Decimal(ThreadStore.threadCount));
    table.WriteRow("UnstartedThread:", Decimal(ThreadStore.unstartedThreadCount));
    table.WriteRow("BackgroundThread:", Decimal(ThreadStore.backgroundThreadCount));
    table.WriteRow("PendingThread:", Decimal(ThreadStore.pendingThreadCount));
    table.WriteRow("DeadThread:", Decimal(ThreadStore.deadThreadCount));

    if (ThreadStore.fHostConfig & ~CLRHOSTED)
    {
        String hosting = "yes";

        hosting += " (";
        hosting += GetHostingCapabilities(ThreadStore.fHostConfig);
        hosting += ")";

        table.WriteRow("Hosted Runtime:", hosting);
    }
    else
    {
        table.WriteRow("Hosted Runtime:", "no");
    }

    const bool hosted = (ThreadStore.fHostConfig & CLRTASKHOSTED) != 0;
    table.ReInit(hosted ? 12 : 11, POINTERSIZE_HEX);
    table.SetWidths(10, 4, 4, 4, _max(9, POINTERSIZE_HEX), 
                      8, 11, 1+POINTERSIZE_HEX*2, POINTERSIZE_HEX,
                      5, 3, POINTERSIZE_HEX);

    table.SetColAlignment(0, AlignRight);
    table.SetColAlignment(1, AlignRight);
    table.SetColAlignment(2, AlignRight);
    table.SetColAlignment(4, AlignRight);

    table.WriteColumn(8, "Lock");
    table.WriteRow("", "ID", "OSID", "ThreadOBJ", "State", "GC Mode", "GC Alloc Context", "Domain", "Count", "Apt");
    
    if (hosted)
        table.WriteColumn("Fiber");

    table.WriteColumn("Exception");
    
    DacpThreadData Thread;
    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread)
    {
        if (IsInterrupt())
            break;

        if ((Status = Thread.Request(g_sos, CurThread)) != S_OK)
        {
            PrintLn("Failed to request Thread at ", Pointer(CurThread));
            return Status;
        }

        BOOL bSwitchedOutFiber = Thread.osThreadId == SWITCHED_OUT_FIBER_OSID;
        if (!IsKernelDebugger())
        {
            ULONG id = 0;          
            
            if (bSwitchedOutFiber)
            {
                table.WriteColumn(0, "<<<< ");
            }
            else if (g_ExtSystem->GetThreadIdBySystemId(Thread.osThreadId, &id) == S_OK)
            {
                table.WriteColumn(0, Decimal(id));
            }
            else if (bPrintLiveThreadsOnly)
            {
                CurThread = Thread.nextThread;
                continue;
            }
            else
            {
                table.WriteColumn(0, "XXXX ");
            }
        }

        table.WriteColumn(1, Decimal(Thread.corThreadId));
        table.WriteColumn(2, ThreadID(bSwitchedOutFiber ? 0 : Thread.osThreadId));
        table.WriteColumn(3, Pointer(CurThread));
        table.WriteColumn(4, ThreadState(Thread.state));
        table.WriteColumn(5,  Thread.preemptiveGCDisabled == 1 ? "Cooperative" : "Preemptive");
        table.WriteColumnFormat(6, "%p:%p", Thread.allocContextPtr, Thread.allocContextLimit);

        if (Thread.domain)
        {
            table.WriteColumn(7, AppDomainPtr(Thread.domain));
        }
        else
        {
            CLRDATA_ADDRESS domain = 0;
            if (FAILED(g_sos->GetDomainFromContext(Thread.context, &domain)))
                table.WriteColumn(7, "<error>");
            else
                table.WriteColumn(7, AppDomainPtr(domain));
        }
        
        table.WriteColumn(8, Decimal(Thread.lockCount));

        // Apartment state
#ifndef FEATURE_PAL           
        DWORD_PTR OleTlsDataAddr;
        if (!bSwitchedOutFiber 
                && SafeReadMemory(Thread.teb + offsetof(TEB, ReservedForOle),
                            &OleTlsDataAddr,
                            sizeof(OleTlsDataAddr), NULL) && OleTlsDataAddr != 0)
        {
            DWORD AptState;
            if (SafeReadMemory(OleTlsDataAddr+offsetof(SOleTlsData,dwFlags),
                               &AptState,
                               sizeof(AptState), NULL))
            {
                if (AptState & OLETLS_APARTMENTTHREADED)
                    table.WriteColumn(9, "STA");
                else if (AptState & OLETLS_MULTITHREADED)
                    table.WriteColumn(9, "MTA");
                else if (AptState & OLETLS_INNEUTRALAPT)
                    table.WriteColumn(9, "NTA");
                else
                    table.WriteColumn(9, "Ukn");
            }
            else
            {
                table.WriteColumn(9, "Ukn");
            }
        }
        else
#endif // FEATURE_PAL
            table.WriteColumn(9, "Ukn");

        if (hosted)
            table.WriteColumn(10, Thread.fiberData);
        
        WString lastCol;
        if (CurThread == ThreadStore.finalizerThread)
            lastCol += W("(Finalizer) ");
        if (CurThread == ThreadStore.gcThread)
            lastCol += W("(GC) ");

        const int TS_TPWorkerThread         = 0x01000000;    // is this a threadpool worker thread?
        const int TS_CompletionPortThread   = 0x08000000;    // is this is a completion port thread?
        
        if (Thread.state & TS_TPWorkerThread)
            lastCol += W("(Threadpool Worker) ");
        else if (Thread.state & TS_CompletionPortThread)
            lastCol += W("(Threadpool Completion Port) ");
        
        
        TADDR taLTOH;
        if (Thread.lastThrownObjectHandle && SafeReadMemory(TO_TADDR(Thread.lastThrownObjectHandle),
                                                            &taLTOH, sizeof(taLTOH), NULL) && taLTOH)
        {
            TADDR taMT;
            if (SafeReadMemory(taLTOH, &taMT, sizeof(taMT), NULL))
            {
                if (NameForMT_s(taMT, g_mdName, mdNameLen))
                    lastCol += WString(g_mdName) + W(" ") + ExceptionPtr(taLTOH);
                else
                    lastCol += WString(W("<Invalid Object> (")) + Pointer(taLTOH) + W(")");

                // Print something if there are nested exceptions on the thread
                if (Thread.firstNestedException)
                    lastCol += W(" (nested exceptions)");
            }
        }

        table.WriteColumn(lastCol);
        CurThread = Thread.nextThread;
    }

    return Status;
}

#ifndef FEATURE_PAL
HRESULT PrintSpecialThreads()
{
    Print("\n");

    DWORD dwCLRTLSDataIndex = 0;
    HRESULT Status = g_sos->GetTLSIndex(&dwCLRTLSDataIndex);
    
    if (!SUCCEEDED (Status))
    {
        Print("Failed to retrieve Tls Data index\n");
        return Status;
    }


    ULONG ulOriginalThreadID = 0;
    Status = g_ExtSystem->GetCurrentThreadId (&ulOriginalThreadID);
    if (!SUCCEEDED (Status))
    {
        Print("Failed to require current Thread ID\n");
        return Status;
    }

    ULONG ulTotalThreads = 0;
    Status = g_ExtSystem->GetNumberThreads (&ulTotalThreads);
    if (!SUCCEEDED (Status))
    {
        Print("Failed to require total thread number\n");
        return Status;
    }

    TableOutput table(3, 4, AlignRight, 5);
    table.WriteRow("", "OSID", "Special thread type");

    for (ULONG ulThread = 0; ulThread < ulTotalThreads; ulThread++)
    {
        ULONG Id = 0;
        ULONG SysId = 0;        
        HRESULT threadStatus = g_ExtSystem->GetThreadIdsByIndex(ulThread, 1, &Id, &SysId);
        if (!SUCCEEDED (threadStatus))
        {
            PrintLn("Failed to get thread ID for thread ", Decimal(ulThread));        
            continue;
        }    

        threadStatus = g_ExtSystem->SetCurrentThreadId(Id);
        if (!SUCCEEDED (threadStatus))
        {
            PrintLn("Failed to switch to thread ", ThreadID(SysId));        
            continue;
        }    

        CLRDATA_ADDRESS cdaTeb = 0;        
        threadStatus = g_ExtSystem->GetCurrentThreadTeb(&cdaTeb);
        if (!SUCCEEDED (threadStatus))
        {
            PrintLn("Failed to get Teb for Thread ", ThreadID(SysId));        
            continue;
        } 

        TADDR CLRTLSDataAddr = 0;

#ifdef FEATURE_IMPLICIT_TLS
        TADDR tlsArrayAddr = NULL;
        if (!SafeReadMemory (TO_TADDR(cdaTeb) + WINNT_OFFSETOF__TEB__ThreadLocalStoragePointer , &tlsArrayAddr, sizeof (void**), NULL))
        {
            PrintLn("Failed to get Tls expansion slots for thread ", ThreadID(SysId));        
            continue;
        }

        TADDR moduleTlsDataAddr = 0;

        if (!SafeReadMemory (tlsArrayAddr + sizeof (void*) * dwCLRTLSDataIndex, &moduleTlsDataAddr, sizeof (void**), NULL))
        {
            PrintLn("Failed to get Tls expansion slots for thread ", ThreadID(SysId));        
            continue;
        }

        CLRTLSDataAddr = moduleTlsDataAddr + OFFSETOF__TLS__tls_EETlsData;
#else
        if (dwCLRTLSDataIndex < TLS_MINIMUM_AVAILABLE)
        {
            CLRTLSDataAddr = TO_TADDR(cdaTeb) + offsetof(TEB, TlsSlots) + sizeof (void*) * dwCLRTLSDataIndex;
        }
        else
        {
            //if TLS index is bigger than TLS_MINIMUM_AVAILABLE, the TLS slot lives in ExpansionSlots
            TADDR TebExpsionAddr = NULL;
            if (!SafeReadMemory (TO_TADDR(cdaTeb) + offsetof(TEB, TlsExpansionSlots) , &TebExpsionAddr, sizeof (void**), NULL))
            {
                PrintLn("Failed to get Tls expansion slots for thread ", ThreadID(SysId));        
                continue;
            }

            if (TebExpsionAddr == NULL)
            {
                continue;
            }
            
            CLRTLSDataAddr = TebExpsionAddr + sizeof (void*) * (dwCLRTLSDataIndex - TLS_MINIMUM_AVAILABLE);
        }
#endif // FEATURE_IMPLICIT_TLS

        TADDR CLRTLSData = NULL;
        if (!SafeReadMemory (CLRTLSDataAddr, &CLRTLSData, sizeof (TADDR), NULL))
        {
            PrintLn("Failed to get CLR Tls data for thread ", ThreadID(SysId));        
            continue;
        }

        if (CLRTLSData == NULL)
        {
            continue;
        }

        size_t ThreadType = 0;
        if (!SafeReadMemory (CLRTLSData + sizeof (TADDR) * TlsIdx_ThreadType, &ThreadType, sizeof (size_t), NULL))
        {
            PrintLn("Failed to get thread type info not found for thread ", ThreadID(SysId));        
            continue;
        }
        
        if (ThreadType == 0)
        {
            continue;
        }

        table.WriteColumn(0, Decimal(Id));
        table.WriteColumn(1, ThreadID(SysId));

        String type;
        if (ThreadType & ThreadType_GC)
        {
            type += "GC ";
        }
        if (ThreadType & ThreadType_Timer)
        {
            type += "Timer ";
        }
        if (ThreadType & ThreadType_Gate)
        {
            type += "Gate ";
        }
        if (ThreadType & ThreadType_DbgHelper)
        {
            type += "DbgHelper ";
        }
        if (ThreadType & ThreadType_Shutdown)
        {
            type += "Shutdown ";
        }
        if (ThreadType & ThreadType_DynamicSuspendEE)
        {
            type += "SuspendEE ";
        }
        if (ThreadType & ThreadType_Finalizer)
        {
            type += "Finalizer ";
        }
        if (ThreadType & ThreadType_ADUnloadHelper)
        {
            type += "ADUnloadHelper ";
        }
        if (ThreadType & ThreadType_ShutdownHelper)
        {
            type += "ShutdownHelper ";
        }
        if (ThreadType & ThreadType_Threadpool_IOCompletion)
        {
            type += "IOCompletion ";
        }
        if (ThreadType & ThreadType_Threadpool_Worker)
        {
            type += "ThreadpoolWorker ";
        }
        if (ThreadType & ThreadType_Wait)
        {
            type += "Wait ";
        }
        if (ThreadType & ThreadType_ProfAPI_Attach)
        {
            type += "ProfilingAPIAttach ";
        }
        if (ThreadType & ThreadType_ProfAPI_Detach)
        {
            type += "ProfilingAPIDetach ";
        }

        table.WriteColumn(2, type);
    }

    Status = g_ExtSystem->SetCurrentThreadId (ulOriginalThreadID);
    if (!SUCCEEDED (Status))
    {
        ExtOut("Failed to switch to original thread\n");        
        return Status;
    }    

    return Status;
}
#endif //FEATURE_PAL

HRESULT SwitchToExceptionThread()
{
    HRESULT Status;
    
    DacpThreadStoreData ThreadStore;
    if ((Status = ThreadStore.Request(g_sos)) != S_OK)
    {
        Print("Failed to request ThreadStore\n");
        return Status;
    }

    DacpThreadData Thread;
    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread)
    {
        if (IsInterrupt())
            break;

        if ((Status = Thread.Request(g_sos, CurThread)) != S_OK)
        {
            PrintLn("Failed to request Thread at ", Pointer(CurThread));
            return Status;
        }
        
        TADDR taLTOH;
        if (Thread.lastThrownObjectHandle != NULL)
        {
            if (SafeReadMemory(TO_TADDR(Thread.lastThrownObjectHandle), &taLTOH, sizeof(taLTOH), NULL))
            {
                if (taLTOH != NULL)
                {
                    ULONG id;
                    if (g_ExtSystem->GetThreadIdBySystemId(Thread.osThreadId, &id) == S_OK)
                    {
                        if (g_ExtSystem->SetCurrentThreadId(id) == S_OK)
                        {
                            PrintLn("Found managed exception on thread ", ThreadID(Thread.osThreadId));
                            break;
                        }
                    }
                }
            }
        }

        CurThread = Thread.nextThread;
    }

    return Status;
}

struct ThreadStateTable
{
    unsigned int State;
    const char * Name;
};
static const struct ThreadStateTable ThreadStates[] =
{
    {0x1, "Thread Abort Requested"},
    {0x2, "GC Suspend Pending"},
    {0x4, "User Suspend Pending"},
    {0x8, "Debug Suspend Pending"},
    {0x10, "GC On Transitions"},
    {0x20, "Legal to Join"},
    {0x40, "Yield Requested"},
    {0x80, "Hijacked by the GC"},
    {0x100, "Blocking GC for Stack Overflow"},
    {0x200, "Background"},
    {0x400, "Unstarted"},
    {0x800, "Dead"},
    {0x1000, "CLR Owns"},
    {0x2000, "CoInitialized"},
    {0x4000, "In Single Threaded Apartment"},
    {0x8000, "In Multi Threaded Apartment"},
    {0x10000, "Reported Dead"},
    {0x20000, "Fully initialized"},
    {0x40000, "Task Reset"},
    {0x80000, "Sync Suspended"},
    {0x100000, "Debug Will Sync"},
    {0x200000, "Stack Crawl Needed"},
    {0x400000, "Suspend Unstarted"},
    {0x800000, "Aborted"},
    {0x1000000, "Thread Pool Worker Thread"},
    {0x2000000, "Interruptible"},
    {0x4000000, "Interrupted"},
    {0x8000000, "Completion Port Thread"},
    {0x10000000, "Abort Initiated"},
    {0x20000000, "Finalized"},
    {0x40000000, "Failed to Start"},
    {0x80000000, "Detached"},
};

DECLARE_API(ThreadState)
{
    INIT_API_NODAC();

    size_t state = GetExpression(args);
    int count = 0;

    if (state)
    {

        for (unsigned int i = 0; i < _countof(ThreadStates); ++i)
            if (state & ThreadStates[i].State)
            {
                ExtOut("    %s\n", ThreadStates[i].Name);
                count++;
            }
    }
    
    // If we did not find any thread states, print out a message to let the user
    // know that the function is working correctly.
    if (count == 0)
        ExtOut("    No thread states for '%s'\n", args);

    return Status;
}

DECLARE_API(Threads)
{
    INIT_API();

    BOOL bPrintSpecialThreads = FALSE;
    BOOL bPrintLiveThreadsOnly = FALSE;
    BOOL bSwitchToManagedExceptionThread = FALSE;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-special", &bPrintSpecialThreads, COBOOL, FALSE},
        {"-live", &bPrintLiveThreadsOnly, COBOOL, FALSE},
        {"-managedexception", &bSwitchToManagedExceptionThread, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
    {
        return Status;
    }

    if (bSwitchToManagedExceptionThread)
    {
        return SwitchToExceptionThread();
    }
    
    // We need to support minidumps for this command.
    BOOL bMiniDump = IsMiniDumpFile();

    if (bMiniDump && bPrintSpecialThreads)
    {
        Print("Special thread information is not available in mini dumps.\n");
    }

    EnableDMLHolder dmlHolder(dml);

    try
    {
        Status = PrintThreadsFromThreadStore(bMiniDump, bPrintLiveThreadsOnly);
        if (!bMiniDump && bPrintSpecialThreads)
        {
#ifdef FEATURE_PAL
            Print("\n-special not supported.\n");
#else //FEATURE_PAL    
            HRESULT Status2 = PrintSpecialThreads(); 
            if (!SUCCEEDED(Status2))
                Status = Status2;
#endif //FEATURE_PAL            
        }
    }
    catch (sos::Exception &e)
    {
        ExtOut("%s\n", e.what());
    }
    
    return Status;
}

#ifndef FEATURE_PAL
/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the Watson Buckets.               *
*                                                                      *
\**********************************************************************/
DECLARE_API(WatsonBuckets)
{
    INIT_API();

    // We don't need to support minidumps for this command.
    if (IsMiniDumpFile())
    {
        ExtOut("Not supported on mini dumps.\n");
    }
    
    // Get the current managed thread.
    CLRDATA_ADDRESS threadAddr = GetCurrentManagedThread();
    DacpThreadData Thread;

    if ((threadAddr == NULL) || ((Status = Thread.Request(g_sos, threadAddr)) != S_OK))
    {
        ExtOut("The current thread is unmanaged\n");
        return Status;
    }
    
    // Get the definition of GenericModeBlock.
#include <msodw.h>
    GenericModeBlock gmb;

    if ((Status = g_sos->GetClrWatsonBuckets(threadAddr, &gmb)) != S_OK)
    {
        ExtOut("Can't get Watson Buckets\n");
        return Status;
    }

    ExtOut("Watson Bucket parameters:\n");
    ExtOut("b1: %S\n", gmb.wzP1);
    ExtOut("b2: %S\n", gmb.wzP2);
    ExtOut("b3: %S\n", gmb.wzP3);
    ExtOut("b4: %S\n", gmb.wzP4);
    ExtOut("b5: %S\n", gmb.wzP5);
    ExtOut("b6: %S\n", gmb.wzP6);
    ExtOut("b7: %S\n", gmb.wzP7);
    ExtOut("b8: %S\n", gmb.wzP8);
    ExtOut("b9: %S\n", gmb.wzP9);
        
    return Status;
} // WatsonBuckets()
#endif // FEATURE_PAL

struct PendingBreakpoint
{
    WCHAR szModuleName[MAX_LONGPATH];
    WCHAR szFunctionName[mdNameLen];
    WCHAR szFilename[MAX_LONGPATH];
    DWORD lineNumber;
    TADDR pModule; 
    DWORD ilOffset;
    mdMethodDef methodToken;
    void SetModule(TADDR module)
    {
        pModule = module;
    }

    bool ModuleMatches(TADDR compare)
    {
        return (compare == pModule);
    }

    PendingBreakpoint *pNext;
    PendingBreakpoint() : lineNumber(0), ilOffset(0), methodToken(0), pNext(NULL) 
    {
        szModuleName[0] = L'\0';
        szFunctionName[0] = L'\0';
        szFilename[0] = L'\0';
    }
};

void IssueDebuggerBPCommand ( CLRDATA_ADDRESS addr )
{
    const int MaxBPsCached = 1024;
    static CLRDATA_ADDRESS alreadyPlacedBPs[MaxBPsCached];
    static int curLimit = 0;

    // on ARM the debugger requires breakpoint addresses to be sanitized
    if (IsDbgTargetArm())
#ifndef FEATURE_PAL
      addr &= ~THUMB_CODE;
#else
      addr |= THUMB_CODE; // lldb expects thumb code bit set
#endif      

    // if we overflowed our cache consider all new BPs unique...
    BOOL bUnique = curLimit >= MaxBPsCached;
    if (!bUnique)
    {
        bUnique = TRUE;
        for (int i = 0; i < curLimit; ++i)
        {
            if (alreadyPlacedBPs[i] == addr)
            {
                bUnique = FALSE;
                break;
            }
        }
    }
    if (bUnique)
    {
        char buffer[64]; // sufficient for "bp <pointersize>"
        static WCHAR wszNameBuffer[1024]; // should be large enough

        // get the MethodDesc name
        CLRDATA_ADDRESS pMD;
        if (g_sos->GetMethodDescPtrFromIP(addr, &pMD) != S_OK
            || g_sos->GetMethodDescName(pMD, 1024, wszNameBuffer, NULL) != S_OK)
        {
            wcscpy_s(wszNameBuffer, _countof(wszNameBuffer), W("UNKNOWN"));        
        }

#ifndef FEATURE_PAL
        sprintf_s(buffer, _countof(buffer), "bp %p", (void*) (size_t) addr);
#else
        sprintf_s(buffer, _countof(buffer), "breakpoint set --address 0x%p", (void*) (size_t) addr);
#endif
        ExtOut("Setting breakpoint: %s [%S]\n", buffer, wszNameBuffer);
        g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);

        if (curLimit < MaxBPsCached)
        {
            alreadyPlacedBPs[curLimit++] = addr;
        }
    }
}

class Breakpoints
{
    PendingBreakpoint* m_breakpoints;
public:
    Breakpoints()
    {
        m_breakpoints = NULL;
    }
    ~Breakpoints()
    {
        PendingBreakpoint *pCur = m_breakpoints;
        while(pCur)
        {
            PendingBreakpoint *pNext = pCur->pNext;
            delete pCur;
            pCur = pNext;
        }
        m_breakpoints = NULL;
    }

    void Add(__in_z LPWSTR szModule, __in_z LPWSTR szName, TADDR mod, DWORD ilOffset)
    {
        if (!IsIn(szModule, szName, mod))
        {
            PendingBreakpoint *pNew = new PendingBreakpoint();
            wcscpy_s(pNew->szModuleName, MAX_LONGPATH, szModule);
            wcscpy_s(pNew->szFunctionName, mdNameLen, szName);
            pNew->SetModule(mod);
            pNew->ilOffset = ilOffset;
            pNew->pNext = m_breakpoints;
            m_breakpoints = pNew;
        }
    }

    void Add(__in_z LPWSTR szModule, __in_z LPWSTR szName, mdMethodDef methodToken, TADDR mod, DWORD ilOffset)
    {
        if (!IsIn(methodToken, mod, ilOffset))
        {
            PendingBreakpoint *pNew = new PendingBreakpoint();
            wcscpy_s(pNew->szModuleName, MAX_LONGPATH, szModule);
            wcscpy_s(pNew->szFunctionName, mdNameLen, szName);
            pNew->methodToken = methodToken;
            pNew->SetModule(mod);
            pNew->ilOffset = ilOffset;
            pNew->pNext = m_breakpoints;
            m_breakpoints = pNew;
        }
    }

    void Add(__in_z LPWSTR szFilename, DWORD lineNumber, TADDR mod)
    {
        if (!IsIn(szFilename, lineNumber, mod))
        {
            PendingBreakpoint *pNew = new PendingBreakpoint();
            wcscpy_s(pNew->szFilename, MAX_LONGPATH, szFilename);
            pNew->lineNumber = lineNumber;
            pNew->SetModule(mod);
            pNew->pNext = m_breakpoints;
            m_breakpoints = pNew;
        }
    }

    void Add(__in_z LPWSTR szFilename, DWORD lineNumber, mdMethodDef methodToken, TADDR mod, DWORD ilOffset)
    {
        if (!IsIn(methodToken, mod, ilOffset))
        {
            PendingBreakpoint *pNew = new PendingBreakpoint();
            wcscpy_s(pNew->szFilename, MAX_LONGPATH, szFilename);
            pNew->lineNumber = lineNumber;
            pNew->methodToken = methodToken;
            pNew->SetModule(mod);
            pNew->ilOffset = ilOffset;
            pNew->pNext = m_breakpoints;
            m_breakpoints = pNew;
        }
    }

    //returns true if updates are still needed for this module, FALSE if all BPs are now bound
    BOOL Update(TADDR mod, BOOL isNewModule)
    {
        BOOL bNeedUpdates = FALSE;
        PendingBreakpoint *pCur = NULL;

        if(isNewModule)
        {
            SymbolReader symbolReader;
            SymbolReader* pSymReader = &symbolReader;
            if(LoadSymbolsForModule(mod, &symbolReader) != S_OK)
                pSymReader = NULL;

            // Get tokens for any modules that match. If there was a change,
            // update notifications.                
            pCur = m_breakpoints;
            while(pCur)
            {
                PendingBreakpoint *pNext = pCur->pNext;
                ResolvePendingNonModuleBoundBreakpoint(mod, pCur, pSymReader);
                pCur = pNext;
            }
        }

        pCur = m_breakpoints;
        while(pCur)
        {
            PendingBreakpoint *pNext = pCur->pNext;
            if (ResolvePendingBreakpoint(mod, pCur))
            {
                bNeedUpdates = TRUE;
            }
            pCur = pNext;
        }
        return bNeedUpdates;
    }

    void RemovePendingForModule(TADDR mod)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        while(pCur)
        {
            PendingBreakpoint *pNext = pCur->pNext;
            if (pCur->ModuleMatches(mod))
            {
                // Delete the current node, and keep going
                Delete(pCur);
            }

            pCur = pNext;
        }                
    }
    
    void ListBreakpoints()
    {
        PendingBreakpoint *pCur = m_breakpoints;
        size_t iBreakpointIndex = 1;
        ExtOut(SOSPrefix "bpmd pending breakpoint list\n Breakpoint index - Location, ModuleID, Method Token\n");
        while(pCur)
        {
            //windbg likes to format %p as always being 64 bits
            ULONG64 modulePtr = (ULONG64)pCur->pModule;

            if(pCur->szModuleName[0] != L'\0')
                ExtOut("%d - %ws!%ws+%d, 0x%p, 0x%08x\n", iBreakpointIndex, pCur->szModuleName, pCur->szFunctionName, pCur->ilOffset, modulePtr, pCur->methodToken);
            else
                ExtOut("%d - %ws:%d, 0x%p, 0x%08x\n",  iBreakpointIndex, pCur->szFilename, pCur->lineNumber, modulePtr, pCur->methodToken);
            iBreakpointIndex++;
            pCur = pCur->pNext;
        }
    }

#ifndef FEATURE_PAL
    void SaveBreakpoints(FILE* pFile)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        while(pCur)
        {
            if(pCur->szModuleName[0] != L'\0')
                fprintf_s(pFile, "!bpmd %ws %ws %d\n", pCur->szModuleName, pCur->szFunctionName, pCur->ilOffset);
            else
                fprintf_s(pFile, "!bpmd %ws:%d\n",  pCur->szFilename, pCur->lineNumber);
            pCur = pCur->pNext;
        }
    }
#endif

    void CleanupNotifications()
    {
#ifdef FEATURE_PAL
        if (m_breakpoints == NULL)
        {
            g_ExtServices->ClearExceptionCallback();
        }
#endif
    }

    void ClearBreakpoint(size_t breakPointToClear)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        size_t iBreakpointIndex = 1;
        while(pCur)
        {
            if (breakPointToClear == iBreakpointIndex)
            {
                ExtOut("%d - %ws, %ws, %p\n", iBreakpointIndex, pCur->szModuleName, pCur->szFunctionName, pCur->pModule);
                ExtOut("Cleared\n");
                Delete(pCur);
                break;
            }
            iBreakpointIndex++;
            pCur = pCur->pNext;
        }

        if (pCur == NULL)
        {
            ExtOut("Invalid pending breakpoint index.\n");
        }
        CleanupNotifications();
    }

    void ClearAllBreakpoints()
    {
        size_t iBreakpointIndex = 1;
        for (PendingBreakpoint *pCur = m_breakpoints; pCur != NULL; )
        {
            PendingBreakpoint* pNext = pCur->pNext;
            Delete(pCur);
            iBreakpointIndex++;
            pCur = pNext;
        }
        CleanupNotifications();

        ExtOut("All pending breakpoints cleared.\n");
    }

    HRESULT LoadSymbolsForModule(TADDR mod, SymbolReader* pSymbolReader)
    {
        HRESULT Status = S_OK;
        ToRelease<IXCLRDataModule> pModule;
        IfFailRet(g_sos->GetModule(mod, &pModule));

        ToRelease<IMetaDataImport> pMDImport = NULL;
        IfFailRet(pModule->QueryInterface(IID_IMetaDataImport, (LPVOID *) &pMDImport));

        IfFailRet(pSymbolReader->LoadSymbols(pMDImport, pModule));

        return S_OK;
    }

    HRESULT ResolvePendingNonModuleBoundBreakpoint(__in_z WCHAR* pFilename, DWORD lineNumber, TADDR mod, SymbolReader* pSymbolReader)
    {
        HRESULT Status = S_OK;
        if(pSymbolReader == NULL)
            return S_FALSE; // no symbols, can't bind here

        mdMethodDef methodDef;
        ULONG32 ilOffset;
        if(FAILED(Status = pSymbolReader->ResolveSequencePoint(pFilename, lineNumber, mod, &methodDef, &ilOffset)))
        {
            return S_FALSE; // not binding in a module is typical
        }

        Add(pFilename, lineNumber, methodDef, mod, ilOffset);
        return Status;
    }

    HRESULT ResolvePendingNonModuleBoundBreakpoint(__in_z WCHAR* pModuleName, __in_z WCHAR* pMethodName, TADDR mod, DWORD ilOffset)
    {
        HRESULT Status = S_OK;
        char szName[mdNameLen];
        int numModule;
        
        ToRelease<IXCLRDataModule> module;
        IfFailRet(g_sos->GetModule(mod, &module));

        WideCharToMultiByte(CP_ACP, 0, pModuleName, (int)(_wcslen(pModuleName) + 1), szName, mdNameLen, NULL, NULL);

        ArrayHolder<DWORD_PTR> moduleList = ModuleFromName(szName, &numModule);
        if (moduleList == NULL)
        {
            ExtOut("Failed to request module list.\n");
            return E_FAIL;
        }

        for (int i = 0; i < numModule; i++)
        {
            // If any one entry in moduleList matches, then the current PendingBreakpoint
            // is the right one.
            if(moduleList[i] != TO_TADDR(mod))
                continue;

            CLRDATA_ENUM h;
            if (module->StartEnumMethodDefinitionsByName(pMethodName, 0, &h) == S_OK)
            {
                IXCLRDataMethodDefinition *pMeth = NULL;
                while (module->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
                {
                    mdMethodDef methodToken;
                    ToRelease<IXCLRDataModule> pUnusedModule;
                    IfFailRet(pMeth->GetTokenAndScope(&methodToken, &pUnusedModule));

                    Add(pModuleName, pMethodName, methodToken, mod, ilOffset);
                    pMeth->Release();
                }
                module->EndEnumMethodDefinitionsByName(h);
            }
        }
        return S_OK;
    }

    // Return TRUE if there might be more instances that will be JITTED later
    static BOOL ResolveMethodInstances(IXCLRDataMethodDefinition *pMeth, DWORD ilOffset)
    {
        BOOL bFoundCode = FALSE;
        BOOL bNeedDefer = FALSE;
        CLRDATA_ENUM h1;
        
        if (pMeth->StartEnumInstances (NULL, &h1) == S_OK)
        {
            IXCLRDataMethodInstance *inst = NULL;
            while (pMeth->EnumInstance (&h1, &inst) == S_OK)
            {
                BOOL foundByIlOffset = FALSE;
                ULONG32 rangesNeeded = 0;
                if(inst->GetAddressRangesByILOffset(ilOffset, 0, &rangesNeeded, NULL) == S_OK)
                {
                    ArrayHolder<CLRDATA_ADDRESS_RANGE> ranges = new NOTHROW CLRDATA_ADDRESS_RANGE[rangesNeeded];
                    if (ranges != NULL)
                    {
                        if (inst->GetAddressRangesByILOffset(ilOffset, rangesNeeded, NULL, ranges) == S_OK)
                        {
                            for (DWORD i = 0; i < rangesNeeded; i++)
                            {
                                IssueDebuggerBPCommand(ranges[i].startAddress);
                                bFoundCode = TRUE;
                                foundByIlOffset = TRUE;
                            }
                        }
                    }
                }
                
                if (!foundByIlOffset && ilOffset == 0)
                {
                    CLRDATA_ADDRESS addr = 0;
                    if (inst->GetRepresentativeEntryAddress(&addr) == S_OK)
                    {
                        IssueDebuggerBPCommand(addr);
                        bFoundCode = TRUE;
                    }
                }
            }
            pMeth->EndEnumInstances (h1);
        }

        // if this is a generic method we need to add a defered bp
        BOOL bGeneric = FALSE;
        pMeth->HasClassOrMethodInstantiation(&bGeneric);

        bNeedDefer = !bFoundCode || bGeneric;
        // This is down here because we only need to call SetCodeNofiication once.
        if (bNeedDefer)
        {
            if (pMeth->SetCodeNotification (CLRDATA_METHNOTIFY_GENERATED) != S_OK)
            {
                bNeedDefer = FALSE;
                ExtOut("Failed to set code notification\n");
            }
        }
        return bNeedDefer;
    }

private:    
    BOOL IsIn(__in_z LPWSTR szModule, __in_z LPWSTR szName, TADDR mod)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        while(pCur)
        {
            if (pCur->ModuleMatches(mod) && 
                _wcsicmp(pCur->szModuleName, szModule) == 0 &&
                _wcscmp(pCur->szFunctionName, szName) == 0)
            {
                return TRUE;
            }
            pCur = pCur->pNext;
        }
        return FALSE;
    }

    BOOL IsIn(__in_z LPWSTR szFilename, DWORD lineNumber, TADDR mod)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        while(pCur)
        {
            if (pCur->ModuleMatches(mod) && 
                _wcsicmp(pCur->szFilename, szFilename) == 0 &&
                pCur->lineNumber == lineNumber)
            {
                return TRUE;
            }
            pCur = pCur->pNext;
        }
        return FALSE;
    }

    BOOL IsIn(mdMethodDef token, TADDR mod, DWORD ilOffset)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        while(pCur)
        {
            if (pCur->ModuleMatches(mod) && 
                pCur->methodToken == token &&
                pCur->ilOffset == ilOffset)
            {
                return TRUE;
            }
            pCur = pCur->pNext;
        }
        return FALSE;
    }

    void Delete(PendingBreakpoint *pDelete)
    {
        PendingBreakpoint *pCur = m_breakpoints;
        PendingBreakpoint *pPrev = NULL;
        while(pCur)
        {
            if (pCur == pDelete)
            {
                if (pPrev == NULL)
                {
                    m_breakpoints = pCur->pNext;
                }
                else
                {
                    pPrev->pNext = pCur->pNext;
                }
                delete pCur;
                return;
            }
            pPrev = pCur;
            pCur = pCur->pNext;
        }
    }



    HRESULT ResolvePendingNonModuleBoundBreakpoint(TADDR mod, PendingBreakpoint *pCur, SymbolReader* pSymbolReader)
    {
        // This function only works with pending breakpoints that are not module bound.
        if (pCur->pModule == NULL)
        {
            if(pCur->szModuleName[0] != L'\0')
            {
                return ResolvePendingNonModuleBoundBreakpoint(pCur->szModuleName, pCur->szFunctionName, mod, pCur->ilOffset);
            }
            else
            {
                return ResolvePendingNonModuleBoundBreakpoint(pCur->szFilename, pCur->lineNumber, mod, pSymbolReader);
            }
        }
        else
        {
            return S_OK;
        }
    }

    // Returns TRUE if further instances may be jitted, FALSE if all instances are now resolved
    BOOL ResolvePendingBreakpoint(TADDR addr, PendingBreakpoint *pCur)
    {
        // Only go forward if the module matches the current PendingBreakpoint
        if (!pCur->ModuleMatches(addr))
        {
            return FALSE;
        }

        ToRelease<IXCLRDataModule> mod;
        if (FAILED(g_sos->GetModule(addr, &mod)))
        {
            return FALSE;
        }

        if(pCur->methodToken == 0)
        {
            return FALSE;
        }

        ToRelease<IXCLRDataMethodDefinition> pMeth = NULL;
        mod->GetMethodDefinitionByToken(pCur->methodToken, &pMeth);

        // We may not need the code notification. Maybe it was ngen'd and we
        // already have the method?
        // We can delete the current entry if ResolveMethodInstances() set all BPs
        return ResolveMethodInstances(pMeth, pCur->ilOffset);
    }
};

Breakpoints g_bpoints;

// Controls whether optimizations are disabled on module load and whether NGEN can be used
BOOL g_fAllowJitOptimization = TRUE;

// Controls whether a one-shot breakpoint should be inserted the next time
// execution is about to enter a catch clause
BOOL g_stopOnNextCatch = FALSE;

// According to the latest debuggers these callbacks will not get called
// unless the user (or an extension, like SOS :-)) had previously enabled
// clrn with "sxe clrn".
class CNotification : public IXCLRDataExceptionNotification4
{
    static int s_condemnedGen;

    int m_count;
    int m_dbgStatus;
public:
    CNotification() 
        : m_count(0)
        , m_dbgStatus(DEBUG_STATUS_NO_CHANGE)
    {}

    int GetDebugStatus()
    {
        return m_dbgStatus;
    }

    STDMETHODIMP QueryInterface (REFIID iid, void **ppvObject)
    {
        if (ppvObject == NULL)
            return E_INVALIDARG;

        if (IsEqualIID(iid, IID_IUnknown)
            || IsEqualIID(iid, IID_IXCLRDataExceptionNotification)
            || IsEqualIID(iid, IID_IXCLRDataExceptionNotification2)
            || IsEqualIID(iid, IID_IXCLRDataExceptionNotification3)
            || IsEqualIID(iid, IID_IXCLRDataExceptionNotification4))
        {
            *ppvObject = static_cast<IXCLRDataExceptionNotification4*>(this);
            AddRef();
            return S_OK;
        }
        else
            return E_NOINTERFACE;

    }

    STDMETHODIMP_(ULONG) AddRef(void) { return ++m_count; }
    STDMETHODIMP_(ULONG) Release(void)
    {
        m_count--;
        if (m_count < 0)
        {
            m_count = 0;
        }
        return m_count;
    }

            
    /*
     * New code was generated or discarded for a method.:
     */
    STDMETHODIMP OnCodeGenerated(IXCLRDataMethodInstance* method)
    {
        // Some method has been generated, make a breakpoint and remove it.
        ULONG32 len = mdNameLen;
        LPWSTR szModuleName = (LPWSTR)alloca(mdNameLen * sizeof(WCHAR));
        if (method->GetName(0, mdNameLen, &len, g_mdName) == S_OK)
        {            
            ToRelease<IXCLRDataModule> pMod;
            HRESULT hr = method->GetTokenAndScope(NULL, &pMod);
            if (SUCCEEDED(hr))
            {
                len = mdNameLen;
                if (pMod->GetName(mdNameLen, &len, szModuleName) == S_OK)
                {
                    ExtOut("JITTED %S!%S\n", szModuleName, g_mdName);

                    // Add breakpoint, perhaps delete pending breakpoint
                    DacpGetModuleAddress dgma;
                    if (SUCCEEDED(dgma.Request(pMod)))
                    {
                        g_bpoints.Update(TO_TADDR(dgma.ModulePtr), FALSE);
                    }
                    else
                    {
                        ExtOut("Failed to request module address.\n");
                    }
                }
            }
        }

        m_dbgStatus = DEBUG_STATUS_GO_HANDLED;
        return S_OK;
    }

    STDMETHODIMP OnCodeDiscarded(IXCLRDataMethodInstance* method)
    {
        return E_NOTIMPL;
    }

    /*
     * The process or task reached the desired execution state.
     */
    STDMETHODIMP OnProcessExecution(ULONG32 state) { return E_NOTIMPL; }
    STDMETHODIMP OnTaskExecution(IXCLRDataTask* task,
                            ULONG32 state) { return E_NOTIMPL; }

    /*
     * The given module was loaded or unloaded.
     */
    STDMETHODIMP OnModuleLoaded(IXCLRDataModule* mod)
    {
        DacpGetModuleAddress dgma;
        if (SUCCEEDED(dgma.Request(mod)))
        {
            g_bpoints.Update(TO_TADDR(dgma.ModulePtr), TRUE);
        }

        if(!g_fAllowJitOptimization)
        {
            HRESULT hr;
            ToRelease<IXCLRDataModule2> mod2;
            if(FAILED(mod->QueryInterface(__uuidof(IXCLRDataModule2), (void**) &mod2)))
            {
                ExtOut("SOS: warning, optimizations for this module could not be suppressed because this CLR version doesn't support the functionality\n");
            }
            else if(FAILED(hr = mod2->SetJITCompilerFlags(CORDEBUG_JIT_DISABLE_OPTIMIZATION)))
            {
                if(hr == CORDBG_E_CANT_CHANGE_JIT_SETTING_FOR_ZAP_MODULE)
                    ExtOut("SOS: warning, optimizations for this module could not be surpressed because an optimized prejitted image was loaded\n");
                else
                    ExtOut("SOS: warning, optimizations for this module could not be surpressed hr=0x%x\n", hr);
            }
        }
        
        m_dbgStatus = DEBUG_STATUS_GO_HANDLED;
        return S_OK;
    }

    STDMETHODIMP OnModuleUnloaded(IXCLRDataModule* mod)
    {
        DacpGetModuleAddress dgma;
        if (SUCCEEDED(dgma.Request(mod)))
        {
            g_bpoints.RemovePendingForModule(TO_TADDR(dgma.ModulePtr));
        }

        m_dbgStatus = DEBUG_STATUS_GO_HANDLED;
        return S_OK;
    }

    /*
     * The given type was loaded or unloaded.
     */
    STDMETHODIMP OnTypeLoaded(IXCLRDataTypeInstance* typeInst) 
    { return E_NOTIMPL; }
    STDMETHODIMP OnTypeUnloaded(IXCLRDataTypeInstance* typeInst) 
    { return E_NOTIMPL; }

    STDMETHODIMP OnAppDomainLoaded(IXCLRDataAppDomain* domain)
    { return E_NOTIMPL; }
    STDMETHODIMP OnAppDomainUnloaded(IXCLRDataAppDomain* domain)
    { return E_NOTIMPL; }
    STDMETHODIMP OnException(IXCLRDataExceptionState* exception)
    { return E_NOTIMPL; }

    STDMETHODIMP OnGcEvent(GcEvtArgs gcEvtArgs)
{
        // by default don't stop on these notifications...
        m_dbgStatus = DEBUG_STATUS_GO_HANDLED;

        IXCLRDataProcess2* idp2 = NULL;
        if (SUCCEEDED(g_clrData->QueryInterface(IID_IXCLRDataProcess2, (void**) &idp2)))
        {
            if (gcEvtArgs.typ == GC_MARK_END)
            {
                // erase notification request
                GcEvtArgs gea = { GC_MARK_END, { 0 } };
                idp2->SetGcNotification(gea);

                s_condemnedGen = bitidx(gcEvtArgs.condemnedGeneration);

                ExtOut("CLR notification: GC - Performing a gen %d collection. Determined surviving objects...\n", s_condemnedGen);

                // GC_MARK_END notification means: give the user a chance to examine the debuggee
                m_dbgStatus = DEBUG_STATUS_BREAK;
            }
        }

        return S_OK;
    }

     /*
     * Catch is about to be entered
     */
    STDMETHODIMP ExceptionCatcherEnter(IXCLRDataMethodInstance* method, DWORD catcherNativeOffset)
    {
        if(g_stopOnNextCatch)
        {
            CLRDATA_ADDRESS startAddr;
            if(method->GetRepresentativeEntryAddress(&startAddr) == S_OK)
            {
                CHAR buffer[100];
#ifndef FEATURE_PAL
                sprintf_s(buffer, _countof(buffer), "bp /1 %p", (void*) (size_t) (startAddr+catcherNativeOffset));
#else
                sprintf_s(buffer, _countof(buffer), "breakpoint set --one-shot --address 0x%p", (void*) (size_t) (startAddr+catcherNativeOffset));
#endif
                g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);
            }
            g_stopOnNextCatch = FALSE;
        }

        m_dbgStatus = DEBUG_STATUS_GO_HANDLED;
        return S_OK;
    }

    static int GetCondemnedGen()
    {
        return s_condemnedGen;
    }

};

int CNotification::s_condemnedGen = -1;

BOOL CheckCLRNotificationEvent(DEBUG_LAST_EVENT_INFO_EXCEPTION* pdle)
{
    ISOSDacInterface4 *psos4 = NULL;
    CLRDATA_ADDRESS arguments[3];
    HRESULT Status;

    if (SUCCEEDED(Status = g_sos->QueryInterface(__uuidof(ISOSDacInterface4), (void**) &psos4)))
    {
        int count = _countof(arguments);
        int countNeeded = 0;

        Status = psos4->GetClrNotification(arguments, count, &countNeeded);
        psos4->Release();

        if (SUCCEEDED(Status))
        {
            memset(&pdle->ExceptionRecord, 0, sizeof(pdle->ExceptionRecord));
            pdle->FirstChance = TRUE;
            pdle->ExceptionRecord.ExceptionCode = CLRDATA_NOTIFY_EXCEPTION;

            _ASSERTE(count <= EXCEPTION_MAXIMUM_PARAMETERS);
            for (int i = 0; i < count; i++)
            {
                pdle->ExceptionRecord.ExceptionInformation[i] = arguments[i];
            }
            // The rest of the ExceptionRecord isn't used by TranslateExceptionRecordToNotification
            return TRUE;
        }
        // No pending exception notification
        return FALSE;
    }

    // The new DAC based interface doesn't exists so ask the debugger for the last exception 
    // information. NOTE: this function doesn't work on xplat version when the coreclr symbols
    // have been stripped.

    ULONG Type, ProcessId, ThreadId;
    ULONG ExtraInformationUsed;
    Status = g_ExtControl->GetLastEventInformation(
        &Type,
        &ProcessId,
        &ThreadId,
        pdle,
        sizeof(DEBUG_LAST_EVENT_INFO_EXCEPTION),
        &ExtraInformationUsed,
        NULL,
        0,
        NULL);

    if (Status != S_OK || Type != DEBUG_EVENT_EXCEPTION)
    {
        return FALSE;
    }

    if (!pdle->FirstChance || pdle->ExceptionRecord.ExceptionCode != CLRDATA_NOTIFY_EXCEPTION)
    {
        return FALSE;
    }

    return TRUE;
}

HRESULT HandleCLRNotificationEvent()
{
    /*
     * Did we get module load notification? If so, check if any in our pending list
     * need to be registered for jit notification.
     *
     * Did we get a jit notification? If so, check if any can be removed and
     * real breakpoints be set.
     */
    DEBUG_LAST_EVENT_INFO_EXCEPTION dle;
    CNotification Notification;

    if (!CheckCLRNotificationEvent(&dle))
    {
#ifndef FEATURE_PAL
        ExtOut("Expecting first chance CLRN exception\n");
        return E_FAIL;
#else
        g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, "process continue", 0);
        return S_OK;
#endif
    }

    // Notification only needs to live for the lifetime of the call below, so it's a non-static
    // local.
    HRESULT Status = g_clrData->TranslateExceptionRecordToNotification(&dle.ExceptionRecord, &Notification);
    if (Status != S_OK)
    {
        ExtErr("Error processing exception notification\n");
        return Status;
    }
    else
    {
        switch (Notification.GetDebugStatus())
        {
            case DEBUG_STATUS_GO:
            case DEBUG_STATUS_GO_HANDLED:
            case DEBUG_STATUS_GO_NOT_HANDLED:
#ifndef FEATURE_PAL
                g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, "g", 0);
#else
                g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, "process continue", 0);
#endif
                break;
            default:
                break;
        }
    }

    return S_OK;
}

#ifndef FEATURE_PAL

DECLARE_API(HandleCLRN)
{
    INIT_API();    
    MINIDUMP_NOT_SUPPORTED();    

    return HandleCLRNotificationEvent();
}

#else // FEATURE_PAL

HRESULT HandleExceptionNotification(ILLDBServices *client)
{
    INIT_API();
    return HandleCLRNotificationEvent();
}

#endif // FEATURE_PAL

DECLARE_API(bpmd)
{
    INIT_API_NOEE();    
    MINIDUMP_NOT_SUPPORTED();    
    int i;
    char buffer[1024];    
    
    if (IsDumpFile())
    {
        ExtOut(SOSPrefix "bpmd is not supported on a dump file.\n");
        return Status;
    }


    // We keep a list of managed breakpoints the user wants to set, and display pending bps
    // bpmd. If you call bpmd <module name> <method> we will set or update an existing bp.
    // bpmd acts as a feeder of breakpoints to bp when the time is right.
    //

    StringHolder DllName,TypeName;
    int lineNumber = 0;
    size_t Offset = 0;

    DWORD_PTR pMD = NULL;
    BOOL fNoFutureModule = FALSE;
    BOOL fList = FALSE;
    size_t clearItem = 0; 
    BOOL fClearAll = FALSE;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-md", &pMD, COHEX, TRUE},
        {"-nofuturemodule", &fNoFutureModule, COBOOL, FALSE},
        {"-list", &fList, COBOOL, FALSE},
        {"-clear", &clearItem, COSIZE_T, TRUE},
        {"-clearall", &fClearAll, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&DllName.data, COSTRING},
        {&TypeName.data, COSTRING},
        {&Offset, COSIZE_T},
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    bool fBadParam = false;
    bool fIsFilename = false;
    int commandsParsed = 0;

    if (pMD != NULL)
    {
        if (nArg != 0)
        {
            fBadParam = true;
        }
        commandsParsed++;
    }
    if (fList)
    {
        commandsParsed++;
        if (nArg != 0)
        {
            fBadParam = true;
        }
    }
    if (fClearAll)
    {
        commandsParsed++;
        if (nArg != 0)
        {
            fBadParam = true;
        }
    }
    if (clearItem != 0)
    {
        commandsParsed++;
        if (nArg != 0)
        {
            fBadParam = true;
        }
    }
    if (1 <= nArg && nArg <= 3)
    {
        commandsParsed++;
        // did we get dll and type name or file:line#? Search for a colon in the first arg
        // to see if it is in fact a file:line#
        CHAR* pColon = strchr(DllName.data, ':');
#ifndef FEATURE_PAL 
        if (FAILED(g_ExtSymbols->GetModuleByModuleName(MAIN_CLR_MODULE_NAME_A, 0, NULL, NULL))) {
#else
        if (FAILED(g_ExtSymbols->GetModuleByModuleName(MAIN_CLR_DLL_NAME_A, 0, NULL, NULL))) {
#endif
           ExtOut("%s not loaded yet\n", MAIN_CLR_DLL_NAME_A);
           return Status;
        }

        if(NULL != pColon)
        {
            fIsFilename = true;
            *pColon = '\0';
            pColon++;
            if(1 != sscanf_s(pColon, "%d", &lineNumber))
            {
                ExtOut("Unable to parse line number\n");
                fBadParam = true;
            }
            else if(lineNumber < 0)
            {
                ExtOut("Line number must be positive\n");
                fBadParam = true;
            }
            if(nArg != 1) fBadParam = 1;
        }
    }

    if (fBadParam || (commandsParsed != 1))
    {
        ExtOut("Usage: " SOSPrefix "bpmd -md <MethodDesc pointer>\n");
        ExtOut("Usage: " SOSPrefix "bpmd [-nofuturemodule] <module name> <managed function name> [<il offset>]\n");
        ExtOut("Usage: " SOSPrefix "bpmd <filename>:<line number>\n");
        ExtOut("Usage: " SOSPrefix "bpmd -list\n");
        ExtOut("Usage: " SOSPrefix "bpmd -clear <pending breakpoint number>\n");
        ExtOut("Usage: " SOSPrefix "bpmd -clearall\n");
#ifdef FEATURE_PAL
        ExtOut("See \"soshelp bpmd\" for more details.\n");
#else
        ExtOut("See \"!help bpmd\" for more details.\n");
#endif
        return Status;
    }

    if (fList)
    {
        g_bpoints.ListBreakpoints();
        return Status;
    }
    if (clearItem != 0)
    {
        g_bpoints.ClearBreakpoint(clearItem);
        return Status;
    }
    if (fClearAll)
    {
        g_bpoints.ClearAllBreakpoints();
        return Status;
    }
    // Add a breakpoint
    // Do we already have this breakpoint?
    // Or, before setting it, is the module perhaps already loaded and code
    // is available? If so, don't add to our pending list, just go ahead and
    // set the real breakpoint.    
    
    LPWSTR ModuleName = (LPWSTR)alloca(mdNameLen * sizeof(WCHAR));
    LPWSTR FunctionName = (LPWSTR)alloca(mdNameLen * sizeof(WCHAR));
    LPWSTR Filename = (LPWSTR)alloca(MAX_LONGPATH * sizeof(WCHAR));

    BOOL bNeedNotificationExceptions = FALSE;

    if (pMD == NULL)
    {
        int numModule = 0;
        int numMethods = 0;

        ArrayHolder<DWORD_PTR> moduleList = NULL;

        if(!fIsFilename)
        {
            MultiByteToWideChar(CP_ACP, 0, DllName.data, -1, ModuleName, mdNameLen);
            MultiByteToWideChar(CP_ACP, 0, TypeName.data, -1, FunctionName, mdNameLen);
        }
        else
        {
            MultiByteToWideChar(CP_ACP, 0, DllName.data, -1, Filename, MAX_LONGPATH);
        }

        // Get modules that may need a breakpoint bound
        if ((Status = CheckEEDll()) == S_OK)
        {
            if ((Status = LoadClrDebugDll()) != S_OK)
            {
                // if the EE is loaded but DAC isn't we should stop.
                DACMessage(Status);
                return Status;
            }
            g_bDacBroken = FALSE;                                       \

            // Get the module list
            moduleList = ModuleFromName(fIsFilename ? NULL : DllName.data, &numModule);

            // Its OK if moduleList is NULL
            // There is a very normal case when checking for modules after clr is loaded
            // but before any AppDomains or assemblies are created
            // for example:
            // >sxe ld:clr
            // >g
            // ...
            // ModLoad: clr.dll
            // >!bpmd Foo.dll Foo.Bar
        }
        // If LoadClrDebugDll() succeeded make sure we release g_clrData
        ToRelease<IXCLRDataProcess> spIDP(g_clrData);
        ToRelease<ISOSDacInterface> spISD(g_sos);
        ResetGlobals();
        
        // we can get here with EE not loaded => 0 modules
        //                      EE is loaded => 0 or more modules
        ArrayHolder<DWORD_PTR> pMDs = NULL;
        for (int iModule = 0; iModule < numModule; iModule++)
        {
            ToRelease<IXCLRDataModule> ModDef;
            if (g_sos->GetModule(moduleList[iModule], &ModDef) != S_OK)
            {
                continue;
            }

            HRESULT symbolsLoaded = S_FALSE;
            if(!fIsFilename)
            {
                g_bpoints.ResolvePendingNonModuleBoundBreakpoint(ModuleName, FunctionName, moduleList[iModule], (DWORD)Offset);
            }
            else
            {
                SymbolReader symbolReader;
                symbolsLoaded = g_bpoints.LoadSymbolsForModule(moduleList[iModule], &symbolReader);
                if(symbolsLoaded == S_OK &&
                   g_bpoints.ResolvePendingNonModuleBoundBreakpoint(Filename, lineNumber, moduleList[iModule], &symbolReader) == S_OK)
                {
                    // if we have symbols then get the function name so we can lookup the MethodDescs
                    mdMethodDef methodDefToken;
                    ULONG32 ilOffset;
                    if(SUCCEEDED(symbolReader.ResolveSequencePoint(Filename, lineNumber, moduleList[iModule], &methodDefToken, &ilOffset)))
                    {
                        ToRelease<IXCLRDataMethodDefinition> pMethodDef = NULL;
                        if (SUCCEEDED(ModDef->GetMethodDefinitionByToken(methodDefToken, &pMethodDef)))
                        {
                            ULONG32 nameLen = 0;
                            pMethodDef->GetName(0, mdNameLen, &nameLen, FunctionName);
                            
                            // get the size of the required buffer
                            int buffSize = WideCharToMultiByte(CP_ACP, 0, FunctionName, -1, TypeName.data, 0, NULL, NULL);
                            
                            TypeName.data = new NOTHROW char[buffSize];
                            if (TypeName.data != NULL)
                            {
                                int bytesWritten = WideCharToMultiByte(CP_ACP, 0, FunctionName, -1, TypeName.data, buffSize, NULL, NULL);
                                _ASSERTE(bytesWritten == buffSize);
                            }
                        }
                    }
                }
            }

            HRESULT gotMethodDescs = GetMethodDescsFromName(moduleList[iModule], ModDef, TypeName.data, &pMDs, &numMethods);
            if (FAILED(gotMethodDescs) && (!fIsFilename))
            {
                // BPs via file name will enumerate through modules so there will be legitimate failures.
                // for module/type name we already found a match so this shouldn't fail (this is the original behavior).
                ExtOut("Error getting MethodDescs for module %p\n", moduleList[iModule]);
                return Status;
            }

            // for filename+line number only print extra info if symbols for this module are loaded (it can get quite noisy otherwise).
            if ((!fIsFilename) || (fIsFilename && symbolsLoaded == S_OK))
            {
                for (int i = 0; i < numMethods; i++)
                {
                    if (pMDs[i] == MD_NOT_YET_LOADED)
                    {
                        continue;
                    }
                    ExtOut("MethodDesc = %p\n", SOS_PTR(pMDs[i]));
                }
            }

            if (g_bpoints.Update(moduleList[iModule], FALSE))
            {
                bNeedNotificationExceptions = TRUE;
            }
        }

        if (!fNoFutureModule)
        {
            // add a pending breakpoint that will find future loaded modules, and
            // wait for the module load notification.
            if (!fIsFilename)
            {
                g_bpoints.Add(ModuleName, FunctionName, NULL, (DWORD)Offset);
            }
            else
            {
                g_bpoints.Add(Filename, lineNumber, NULL);
            }
            bNeedNotificationExceptions = TRUE;

            ULONG32 flags = 0;
            g_clrData->GetOtherNotificationFlags(&flags);
            flags |= (CLRDATA_NOTIFY_ON_MODULE_LOAD | CLRDATA_NOTIFY_ON_MODULE_UNLOAD);
            g_clrData->SetOtherNotificationFlags(flags);
        }
    }
    else /* We were given a MethodDesc already */
    {
        // if we've got an explicit MD, then we better have CLR and mscordacwks loaded
        INIT_API_EE()
        INIT_API_DAC();

        DacpMethodDescData MethodDescData;
        ExtOut("MethodDesc = %p\n", SOS_PTR(pMD));
        if (MethodDescData.Request(g_sos, TO_CDADDR(pMD)) != S_OK)
        {
            ExtOut("%p is not a valid MethodDesc\n", SOS_PTR(pMD));
            return Status;
        }
        
        if (MethodDescData.bHasNativeCode)
        {
            IssueDebuggerBPCommand((size_t) MethodDescData.NativeCodeAddr);
        }
        else if (MethodDescData.bIsDynamic)
        {
#ifndef FEATURE_PAL
            // Dynamic methods don't have JIT notifications. This is something we must
            // fix in the next release. Until then, you have a cumbersome user experience.
            ExtOut("This DynamicMethodDesc is not yet JITTED. Placing memory breakpoint at %p\n",
                MethodDescData.AddressOfNativeCodeSlot);
            
            sprintf_s(buffer, _countof(buffer),
#ifdef _TARGET_WIN64_
                "ba w8"
#else
                "ba w4" 
#endif // _TARGET_WIN64_

                " /1 %p \"bp poi(%p); g\"",
                (void*) (size_t) MethodDescData.AddressOfNativeCodeSlot,
                (void*) (size_t) MethodDescData.AddressOfNativeCodeSlot);

            Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);
            if (FAILED(Status))
            {
                ExtOut("Unable to set breakpoint with IDebugControl::Execute: %x\n",Status);
                ExtOut("Attempted to run: %s\n", buffer);                
            }            
#else
            ExtErr("This DynamicMethodDesc is not yet JITTED %p\n", MethodDescData.AddressOfNativeCodeSlot);
#endif // FEATURE_PAL
        }
        else
        {
            // Must issue a pending breakpoint.
            if (g_sos->GetMethodDescName(pMD, mdNameLen, FunctionName, NULL) != S_OK)
            {
                ExtOut("Unable to get method name for MethodDesc %p\n", SOS_PTR(pMD));
                return Status;
            }

            FileNameForModule ((DWORD_PTR) MethodDescData.ModulePtr, ModuleName);

            // We didn't find code, add a breakpoint.
            g_bpoints.ResolvePendingNonModuleBoundBreakpoint(ModuleName, FunctionName, TO_TADDR(MethodDescData.ModulePtr), 0);
            g_bpoints.Update(TO_TADDR(MethodDescData.ModulePtr), FALSE);
            bNeedNotificationExceptions = TRUE;            
        }
    }

    if (bNeedNotificationExceptions)
    {
        ExtOut("Adding pending breakpoints...\n");
#ifndef FEATURE_PAL
        sprintf_s(buffer, _countof(buffer), "sxe -c \"!HandleCLRN\" clrn");
        Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);        
#else
        Status = g_ExtServices->SetExceptionCallback(HandleExceptionNotification);
#endif // FEATURE_PAL
    }

    return Status;
}

#ifndef FEATURE_PAL

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the managed threadpool            *
*                                                                      *
\**********************************************************************/
DECLARE_API(ThreadPool)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();

    DacpThreadpoolData threadpool;

    if ((Status = threadpool.Request(g_sos)) == S_OK)
    {
        BOOL doHCDump = FALSE;

        CMDOption option[] = 
        {   // name, vptr, type, hasValue
            {"-ti", &doHCDump, COBOOL, FALSE}
        };    

        if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
        {
            return Status;
        }

        ExtOut ("CPU utilization: %d%%\n", threadpool.cpuUtilization);            
        ExtOut ("Worker Thread:");
        ExtOut (" Total: %d", threadpool.NumWorkingWorkerThreads + threadpool.NumIdleWorkerThreads + threadpool.NumRetiredWorkerThreads);
        ExtOut (" Running: %d", threadpool.NumWorkingWorkerThreads);
        ExtOut (" Idle: %d", threadpool.NumIdleWorkerThreads);
        ExtOut (" MaxLimit: %d", threadpool.MaxLimitTotalWorkerThreads);        
        ExtOut (" MinLimit: %d", threadpool.MinLimitTotalWorkerThreads);        
        ExtOut ("\n");        

        int numWorkRequests = 0;
        CLRDATA_ADDRESS workRequestPtr = threadpool.FirstUnmanagedWorkRequest;
        DacpWorkRequestData workRequestData;
        while (workRequestPtr)
        {
            if ((Status = workRequestData.Request(g_sos,workRequestPtr))!=S_OK)
            {
                ExtOut("    Failed to examine a WorkRequest\n");
                return Status;
            }
            numWorkRequests++;
            workRequestPtr = workRequestData.NextWorkRequest;
        }

        ExtOut ("Work Request in Queue: %d\n", numWorkRequests);    
        workRequestPtr = threadpool.FirstUnmanagedWorkRequest;
        while (workRequestPtr)
        {
            if ((Status = workRequestData.Request(g_sos,workRequestPtr))!=S_OK)
            {
                ExtOut("    Failed to examine a WorkRequest\n");
                return Status;
            }

            if (workRequestData.Function == threadpool.AsyncTimerCallbackCompletionFPtr)
                ExtOut ("    AsyncTimerCallbackCompletion TimerInfo@%p\n", SOS_PTR(workRequestData.Context));
            else
                ExtOut ("    Unknown Function: %p  Context: %p\n", SOS_PTR(workRequestData.Function),
                    SOS_PTR(workRequestData.Context));

            workRequestPtr = workRequestData.NextWorkRequest;
        }

        if (doHCDump)
        {
            ExtOut ("--------------------------------------\n");
            ExtOut ("\nThread Injection History\n");
            if (threadpool.HillClimbingLogSize > 0)
            {
                static char const * const TransitionNames[] = 
                {
                    "Warmup", 
                    "Initializing",
                    "RandomMove",
                    "ClimbingMove",
                    "ChangePoint",
                    "Stabilizing",
                    "Starvation",
                    "ThreadTimedOut",
                    "Undefined"
                };

                ExtOut("\n    Time Transition     New #Threads      #Samples   Throughput\n");
                DacpHillClimbingLogEntry entry;

                // get the most recent entry first, so we can calculate time offsets
                
                int index = (threadpool.HillClimbingLogFirstIndex + threadpool.HillClimbingLogSize-1) % HillClimbingLogCapacity;
                CLRDATA_ADDRESS entryPtr = threadpool.HillClimbingLog + (index * sizeof(HillClimbingLogEntry));
                if ((Status = entry.Request(g_sos,entryPtr))!=S_OK)
                {
                    ExtOut("    Failed to examine a HillClimbing log entry\n");
                    return Status;
                }
                DWORD endTime = entry.TickCount;

                for (int i = 0; i < threadpool.HillClimbingLogSize; i++)
                {
                    index = (i + threadpool.HillClimbingLogFirstIndex) % HillClimbingLogCapacity;
                    entryPtr = threadpool.HillClimbingLog + (index * sizeof(HillClimbingLogEntry));

                    if ((Status = entry.Request(g_sos,entryPtr))!=S_OK)
                    {
                        ExtOut("    Failed to examine a HillClimbing log entry\n");
                        return Status;
                    }

                    ExtOut("%8.2lf %-14s %12d  %12d  %11.2lf\n",
                        (double)(int)(entry.TickCount - endTime) / 1000.0,
                        TransitionNames[entry.Transition],
                        entry.NewControlSetting,
                        entry.LastHistoryCount,
                        entry.LastHistoryMean);
                }
            }
        }
            
        ExtOut ("--------------------------------------\n");
        ExtOut ("Number of Timers: %d\n", threadpool.NumTimers);
        ExtOut ("--------------------------------------\n");
        
        ExtOut ("Completion Port Thread:");
        ExtOut ("Total: %d", threadpool.NumCPThreads);    
        ExtOut (" Free: %d", threadpool.NumFreeCPThreads);    
        ExtOut (" MaxFree: %d", threadpool.MaxFreeCPThreads);    
        ExtOut (" CurrentLimit: %d", threadpool.CurrentLimitTotalCPThreads);
        ExtOut (" MaxLimit: %d", threadpool.MaxLimitTotalCPThreads);
        ExtOut (" MinLimit: %d", threadpool.MinLimitTotalCPThreads);        
        ExtOut ("\n");
    }
    else
    {
        ExtOut("Failed to request ThreadpoolMgr information\n");
    }
    return Status;
}

#endif // FEATURE_PAL

DECLARE_API(FindAppDomain)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    DWORD_PTR p_Object = NULL;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&p_Object, COHEX},
    };
    size_t nArg;

    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    
    if ((p_Object == 0) || !sos::IsObject(p_Object))
    {
        ExtOut("%p is not a valid object\n", SOS_PTR(p_Object));
        return Status;
    }
    
    DacpAppDomainStoreData adstore;
    if (adstore.Request(g_sos) != S_OK)
    {
        ExtOut("Error getting AppDomain information\n");
        return Status;
    }    

    CLRDATA_ADDRESS appDomain = GetAppDomain (TO_CDADDR(p_Object));

    if (appDomain != NULL)
    {
        DMLOut("AppDomain: %s\n", DMLDomain(appDomain));
        if (appDomain == adstore.sharedDomain)
        {
            ExtOut("Name:      Shared Domain\n");
            ExtOut("ID:        (shared domain)\n");            
        }
        else if (appDomain == adstore.systemDomain)
        {
            ExtOut("Name:      System Domain\n");
            ExtOut("ID:        (system domain)\n");
        }
        else
        {
            DacpAppDomainData domain;
            if ((domain.Request(g_sos, appDomain) != S_OK) ||
                (g_sos->GetAppDomainName(appDomain,mdNameLen,g_mdName, NULL)!=S_OK))
            {
                ExtOut("Error getting AppDomain %p.\n", SOS_PTR(appDomain));
                return Status;
            }

            ExtOut("Name:      %S\n", (g_mdName[0]!=L'\0') ? g_mdName : W("None"));
            ExtOut("ID:        %d\n", domain.dwId);
        }
    }
    else
    {
        ExtOut("The type is declared in the shared domain and other\n");
        ExtOut("methods of finding the AppDomain failed. Try running\n");
        if (IsDMLEnabled())
            DMLOut("<exec cmd=\"!gcroot /d %p\">!gcroot %p</exec>, and if you find a root on a\n", p_Object, p_Object);
        else
            ExtOut("!gcroot %p, and if you find a root on a\n", p_Object);
        ExtOut("stack, check the AppDomain of that stack with !threads.\n");
        ExtOut("Note that the Thread could have transitioned between\n");
        ExtOut("multiple AppDomains.\n");
    }
    
    return Status;
}

#ifndef FEATURE_PAL

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to get the COM state (e.g. APT,contexe    *
*    activity.                                                         *  
*                                                                      *
\**********************************************************************/
#ifdef FEATURE_COMINTEROP
DECLARE_API(COMState)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    

    ULONG numThread;
    ULONG maxId;
    g_ExtSystem->GetTotalNumberThreads(&numThread,&maxId);

    ULONG curId;
    g_ExtSystem->GetCurrentThreadId(&curId);

    SIZE_T AllocSize;
    if (!ClrSafeInt<SIZE_T>::multiply(sizeof(ULONG), numThread, AllocSize))
    {
        ExtOut("  Error!  integer overflow on numThread 0x%08x\n", numThread);
        return Status;
    }
    ULONG *ids = (ULONG*)alloca(AllocSize);
    ULONG *sysIds = (ULONG*)alloca(AllocSize);
    g_ExtSystem->GetThreadIdsByIndex(0,numThread,ids,sysIds);
#if defined(_TARGET_WIN64_)
    ExtOut("      ID             TEB  APT    APTId CallerTID          Context\n");
#else
    ExtOut("     ID     TEB   APT    APTId CallerTID Context\n");
#endif
    for (ULONG i = 0; i < numThread; i ++) {
        g_ExtSystem->SetCurrentThreadId(ids[i]);
        CLRDATA_ADDRESS cdaTeb;
        g_ExtSystem->GetCurrentThreadTeb(&cdaTeb);
        ExtOut("%3d %4x %p", ids[i], sysIds[i], SOS_PTR(CDA_TO_UL64(cdaTeb)));
        // Apartment state
        TADDR OleTlsDataAddr;
        if (SafeReadMemory(TO_TADDR(cdaTeb) + offsetof(TEB,ReservedForOle),
                            &OleTlsDataAddr,
                            sizeof(OleTlsDataAddr), NULL) && OleTlsDataAddr != 0) {
            DWORD AptState;
            if (SafeReadMemory(OleTlsDataAddr+offsetof(SOleTlsData,dwFlags),
                               &AptState,
                               sizeof(AptState), NULL)) {
                if (AptState & OLETLS_APARTMENTTHREADED) {
                    ExtOut(" STA");
                }
                else if (AptState & OLETLS_MULTITHREADED) {
                    ExtOut(" MTA");
                }
                else if (AptState & OLETLS_INNEUTRALAPT) {
                    ExtOut(" NTA");
                }
                else {
                    ExtOut(" Ukn");
                }

                // Read these fields only if we were able to read anything of the SOleTlsData structure
                DWORD dwApartmentID;
                if (SafeReadMemory(OleTlsDataAddr+offsetof(SOleTlsData,dwApartmentID),
                                   &dwApartmentID,
                                   sizeof(dwApartmentID), NULL)) {
                    ExtOut(" %8x", dwApartmentID);
                }
                else
                    ExtOut(" %8x", 0);
                
                DWORD dwTIDCaller;
                if (SafeReadMemory(OleTlsDataAddr+offsetof(SOleTlsData,dwTIDCaller),
                                   &dwTIDCaller,
                                   sizeof(dwTIDCaller), NULL)) {
                    ExtOut("  %8x", dwTIDCaller);
                }
                else
                    ExtOut("  %8x", 0);
                
                size_t Context;
                if (SafeReadMemory(OleTlsDataAddr+offsetof(SOleTlsData,pCurrentCtx),
                                   &Context,
                                   sizeof(Context), NULL)) {
                    ExtOut(" %p", SOS_PTR(Context));
                }
                else
                    ExtOut(" %p", SOS_PTR(0));

            }
            else
                ExtOut(" Ukn");            
        }
        else
            ExtOut(" Ukn");
        ExtOut("\n");
    }

    g_ExtSystem->SetCurrentThreadId(curId);
    return Status;
}
#endif // FEATURE_COMINTEROP

#endif // FEATURE_PAL

BOOL traverseEh(UINT clauseIndex,UINT totalClauses,DACEHInfo *pEHInfo,LPVOID token)
{
    size_t methodStart = (size_t) token;
    
    if (IsInterrupt())
    {
        return FALSE;
    }

    ExtOut("EHHandler %d: %s ", clauseIndex, EHTypeName(pEHInfo->clauseType));

    LPCWSTR typeName = EHTypedClauseTypeName(pEHInfo);
    if (typeName != NULL)
    {
        ExtOut("catch(%S) ", typeName);
    }

    if (IsClonedFinally(pEHInfo))
        ExtOut("(cloned finally)");
    else if (pEHInfo->isDuplicateClause)
        ExtOut("(duplicate)");

    ExtOut("\n");
    ExtOut("Clause:  ");

    ULONG64 addrStart = pEHInfo->tryStartOffset + methodStart;
    ULONG64 addrEnd   = pEHInfo->tryEndOffset   + methodStart;

#ifdef _WIN64
    ExtOut("[%08x`%08x, %08x`%08x]",
            (ULONG)(addrStart >> 32), (ULONG)addrStart,
            (ULONG)(addrEnd   >> 32), (ULONG)addrEnd);
#else
    ExtOut("[%08x, %08x]", (ULONG)addrStart, (ULONG)addrEnd);
#endif

    ExtOut(" [%x, %x]\n", 
        (UINT32) pEHInfo->tryStartOffset,
        (UINT32) pEHInfo->tryEndOffset);

    ExtOut("Handler: ");

    addrStart = pEHInfo->handlerStartOffset + methodStart;
    addrEnd   = pEHInfo->handlerEndOffset   + methodStart;

#ifdef _WIN64
    ExtOut("[%08x`%08x, %08x`%08x]",
            (ULONG)(addrStart >> 32), (ULONG)addrStart,
            (ULONG)(addrEnd   >> 32), (ULONG)addrEnd);
#else
    ExtOut("[%08x, %08x]", (ULONG)addrStart, (ULONG)addrEnd);
#endif

    ExtOut(" [%x, %x]\n", 
        (UINT32) pEHInfo->handlerStartOffset,
        (UINT32) pEHInfo->handlerEndOffset);
    
    if (pEHInfo->clauseType == EHFilter)
    {
        ExtOut("Filter: ");

        addrStart = pEHInfo->filterOffset + methodStart;

#ifdef _WIN64
        ExtOut("[%08x`%08x]", (ULONG)(addrStart >> 32), (ULONG)addrStart);
#else
        ExtOut("[%08x]", (ULONG)addrStart);
#endif

        ExtOut(" [%x]\n",
            (UINT32) pEHInfo->filterOffset);
    }
    
    ExtOut("\n");        
    return TRUE;
}

DECLARE_API(EHInfo)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    DWORD_PTR dwStartAddr = NULL;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };

    CMDValue arg[] = 
    {   // vptr, type
        {&dwStartAddr, COHEX},
    };

    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg) || (0 == nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    DWORD_PTR tmpAddr = dwStartAddr;

    if (!IsMethodDesc(dwStartAddr)) 
    {
        JITTypes jitType;
        DWORD_PTR methodDesc;
        DWORD_PTR gcinfoAddr;
        IP2MethodDesc (dwStartAddr, methodDesc, jitType, gcinfoAddr);
        tmpAddr = methodDesc;
    }

    DacpMethodDescData MD;
    if ((tmpAddr == 0) || (MD.Request(g_sos, TO_CDADDR(tmpAddr)) != S_OK))
    {
        ExtOut("%p is not a MethodDesc\n", SOS_PTR(tmpAddr));
        return Status;
    }

    if (1 == nArg && !MD.bHasNativeCode)
    {
        ExtOut("No EH info available\n");
        return Status;
    }

    DacpCodeHeaderData codeHeaderData;
    if (codeHeaderData.Request(g_sos, TO_CDADDR(MD.NativeCodeAddr)) != S_OK)
    {
        ExtOut("Unable to get codeHeader information\n");
        return Status;
    }        
    
    DMLOut("MethodDesc:   %s\n", DMLMethodDesc(MD.MethodDescPtr));
    DumpMDInfo(TO_TADDR(MD.MethodDescPtr));

    ExtOut("\n");
    Status = g_sos->TraverseEHInfo(TO_CDADDR(MD.NativeCodeAddr), traverseEh, (LPVOID)MD.NativeCodeAddr);

    if (Status == E_ABORT)
    {
        ExtOut("<user aborted>\n");
    }
    else if (Status != S_OK)
    {
        ExtOut("Failed to perform EHInfo traverse\n");
    }
    
    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the GC encoding of a managed      *
*    function.                                                         *  
*                                                                      *
\**********************************************************************/
DECLARE_API(GCInfo)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();
    

    TADDR taStartAddr = NULL;
    TADDR taGCInfoAddr;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&taStartAddr, COHEX},
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg) || (0 == nArg))
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    TADDR tmpAddr = taStartAddr;

    if (!IsMethodDesc(taStartAddr)) 
    {
        JITTypes jitType;
        TADDR methodDesc;
        TADDR gcinfoAddr;
        IP2MethodDesc(taStartAddr, methodDesc, jitType, gcinfoAddr);
        tmpAddr = methodDesc;
    }

    DacpMethodDescData MD;
    if ((tmpAddr == 0) || (MD.Request(g_sos, TO_CDADDR(tmpAddr)) != S_OK))
    {
        ExtOut("%p is not a valid MethodDesc\n", SOS_PTR(taStartAddr));
        return Status;
    }

    if (1 == nArg && !MD.bHasNativeCode)
    {
        ExtOut("No GC info available\n");
        return Status;
    }

    DacpCodeHeaderData codeHeaderData;

    if (
        // Try to get code header data from taStartAddr.  This will get the code
        // header corresponding to the IP address, even if the function was rejitted
        (codeHeaderData.Request(g_sos, TO_CDADDR(taStartAddr)) != S_OK) &&

        // If that didn't work, just try to use the code address that the MD
        // points to.  If the function was rejitted, this will only give you the
        // original JITted code, but that's better than nothing
        (codeHeaderData.Request(g_sos, TO_CDADDR(MD.NativeCodeAddr)) != S_OK)
        )
    {
        // We always used to emit this (before rejit support), even if we couldn't get
        // the code header, so keep on doing so.
        ExtOut("entry point %p\n", SOS_PTR(MD.NativeCodeAddr));

        // And now the error....
        ExtOut("Unable to get codeHeader information\n");
        return Status;
    }

    // We have the code header, so use it to determine the method start

    ExtOut("entry point %p\n", SOS_PTR(codeHeaderData.MethodStart));

    if (codeHeaderData.JITType == TYPE_UNKNOWN)
    {
        ExtOut("unknown Jit\n");
        return Status;
    }
    else if (codeHeaderData.JITType == TYPE_JIT)
    {
        ExtOut("Normal JIT generated code\n");
    }
    else if (codeHeaderData.JITType == TYPE_PJIT)
    {
        ExtOut("preJIT generated code\n");
    }

    taGCInfoAddr = TO_TADDR(codeHeaderData.GCInfo);

    ExtOut("GC info %p\n", SOS_PTR(taGCInfoAddr));

    // assume that GC encoding table is never more than
    // 40 + methodSize * 2
    int tableSize = 0;
    if (!ClrSafeInt<int>::multiply(codeHeaderData.MethodSize, 2, tableSize) ||
        !ClrSafeInt<int>::addition(tableSize, 40, tableSize))
    {
        ExtOut("<integer overflow>\n");
        return E_FAIL;
    }
    ArrayHolder<BYTE> table = new NOTHROW BYTE[tableSize];
    if (table == NULL)
    {
        ExtOut("Could not allocate memory to read the gc info.\n");
        return E_OUTOFMEMORY;
    }
    
    memset(table, 0, tableSize);
    // We avoid using move here, because we do not want to return
    if (!SafeReadMemory(taGCInfoAddr, table, tableSize, NULL))
    {
        ExtOut("Could not read memory %p\n", SOS_PTR(taGCInfoAddr));
        return Status;
    }

    // Mutable table pointer since we need to pass the appropriate
    // offset into the table to DumpGCTable.
    GCInfoToken gcInfoToken = { table, GCINFO_VERSION };
    unsigned int methodSize = (unsigned int)codeHeaderData.MethodSize;

    g_targetMachine->DumpGCInfo(gcInfoToken, methodSize, ExtOut, true /*encBytes*/, true /*bPrintHeader*/);

    return Status;
}

#if !defined(FEATURE_PAL)

void DecodeGCTableEntry (const char *fmt, ...)
{
    GCEncodingInfo *pInfo = (GCEncodingInfo*)GetFiberData();
    va_list va;

    //
    // Append the new data to the buffer
    //

    va_start(va, fmt);

    int cch = _vsnprintf_s(&pInfo->buf[pInfo->cch], _countof(pInfo->buf) - pInfo->cch, _countof(pInfo->buf) - pInfo->cch - 1, fmt, va);
    if (cch >= 0)
        pInfo->cch += cch;

    va_end(va);

    pInfo->buf[pInfo->cch] = '\0';

    //
    // If there are complete lines in the buffer, decode them.
    //

    for (;;)
    {
        char *pNewLine = strchr(pInfo->buf, '\n');

        if (!pNewLine)
            break;

        //
        // The line should start with a 16-bit (x86) or 32-bit (non-x86) hex
        // offset.  strtoul returns ULONG_MAX or 0 on failure.  0 is a valid
        // offset for the first encoding, or while the last offset was 0.
        //

        if (isxdigit(pInfo->buf[0]))
        {
            char *pEnd;
            ULONG ofs = strtoul(pInfo->buf, &pEnd, 16);

            if (   isspace(*pEnd)
                && -1 != ofs 
                && (   -1 == pInfo->ofs
                    || 0 == pInfo->ofs
                    || ofs > 0))
            {
                pInfo->ofs = ofs;
                *pNewLine = '\0';

                SwitchToFiber(pInfo->pvMainFiber);
            }
        }
        else if (0 == strncmp(pInfo->buf, "Untracked:", 10))
        {
            pInfo->ofs = 0;
            *pNewLine = '\0';

            SwitchToFiber(pInfo->pvMainFiber);
        }

        //
        // Shift the remaining data to the start of the buffer
        //

        strcpy_s(pInfo->buf, _countof(pInfo->buf), pNewLine+1);
        pInfo->cch = (int)strlen(pInfo->buf);
    }
}


VOID CALLBACK DumpGCTableFiberEntry (LPVOID pvGCEncodingInfo)
{
    GCEncodingInfo *pInfo = (GCEncodingInfo*)pvGCEncodingInfo;
    GCInfoToken gcInfoToken = { pInfo->table, GCINFO_VERSION };
    g_targetMachine->DumpGCInfo(gcInfoToken, pInfo->methodSize, DecodeGCTableEntry, false /*encBytes*/, false /*bPrintHeader*/);

    pInfo->fDoneDecoding = true;
    SwitchToFiber(pInfo->pvMainFiber);
}
#endif // !FEATURE_PAL

BOOL gatherEh(UINT clauseIndex,UINT totalClauses,DACEHInfo *pEHInfo,LPVOID token)
{
    SOSEHInfo *pInfo = (SOSEHInfo *) token;

    if (pInfo == NULL)
    {
        return FALSE;
    }
    
    if (pInfo->m_pInfos == NULL)
    {
        // First time, initialize structure
        pInfo->EHCount = totalClauses;
        pInfo->m_pInfos = new NOTHROW DACEHInfo[totalClauses];
        if (pInfo->m_pInfos == NULL)
        {
            ReportOOM();            
            return FALSE;
        }
    }

    pInfo->m_pInfos[clauseIndex] = *((DACEHInfo*)pEHInfo);
    return TRUE;
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to unassembly a managed function.         *
*    It tries to print symbolic info for function call, contants...    *  
*                                                                      *
\**********************************************************************/
DECLARE_API(u)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    
    DWORD_PTR dwStartAddr = NULL;
    BOOL fWithGCInfo = FALSE;
    BOOL fWithEHInfo = FALSE;
    BOOL bSuppressLines = FALSE;
    BOOL bDisplayOffsets = FALSE;
    BOOL dml = FALSE;
    size_t nArg;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"-gcinfo", &fWithGCInfo, COBOOL, FALSE},
#endif
        {"-ehinfo", &fWithEHInfo, COBOOL, FALSE},
        {"-n", &bSuppressLines, COBOOL, FALSE},
        {"-o", &bDisplayOffsets, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&dwStartAddr, COHEX},
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg) || (nArg < 1))
    {
        return Status;
    }
    // symlines will be non-zero only if SYMOPT_LOAD_LINES was set in the symbol options
    ULONG symlines = 0;
    if (!bSuppressLines && SUCCEEDED(g_ExtSymbols->GetSymbolOptions(&symlines)))
    {
        symlines &= SYMOPT_LOAD_LINES;
    }
    bSuppressLines = bSuppressLines || (symlines == 0);

    EnableDMLHolder dmlHolder(dml);
    // dwStartAddr is either some IP address or a MethodDesc.  Start off assuming it's a
    // MethodDesc.
    DWORD_PTR methodDesc = dwStartAddr;
    if (!IsMethodDesc(methodDesc))
    {
        // Not a methodDesc, so gotta find it ourselves
        DWORD_PTR tmpAddr = dwStartAddr;
        JITTypes jt;
        DWORD_PTR gcinfoAddr;
        IP2MethodDesc (tmpAddr, methodDesc, jt,
                       gcinfoAddr);
        if (!methodDesc || jt == TYPE_UNKNOWN)
        {
            // It is not managed code.
            ExtOut("Unmanaged code\n");
            UnassemblyUnmanaged(dwStartAddr, bSuppressLines);
            return Status;
        }
    }

    DacpMethodDescData MethodDescData;
    if ((Status=MethodDescData.Request(g_sos, TO_CDADDR(methodDesc))) != S_OK)
    {
        ExtOut("Failed to get method desc for %p.\n", SOS_PTR(dwStartAddr));
        return Status;
    }    

    if (!MethodDescData.bHasNativeCode)
    {
        ExtOut("Not jitted yet\n");
        return Status;
    }

    // Get the appropriate code header. If we were passed an MD, then use
    // MethodDescData.NativeCodeAddr to find the code header; if we were passed an IP, use
    // that IP to find the code header. This ensures that, for rejitted functions, we
    // disassemble the rejit version that the user explicitly specified with their IP.
    DacpCodeHeaderData codeHeaderData;
    if (codeHeaderData.Request(
        g_sos, 
        TO_CDADDR(
            (dwStartAddr == methodDesc) ? MethodDescData.NativeCodeAddr : dwStartAddr)
            ) != S_OK)

    {
        ExtOut("Unable to get codeHeader information\n");
        return Status;
    }                
    
    if (codeHeaderData.MethodStart == 0)
    {
        ExtOut("not a valid MethodDesc\n");
        return Status;
    }
    
    if (codeHeaderData.JITType == TYPE_UNKNOWN)
    {
        ExtOut("unknown Jit\n");
        return Status;
    }
    else if (codeHeaderData.JITType == TYPE_JIT)
    {
        ExtOut("Normal JIT generated code\n");
    }
    else if (codeHeaderData.JITType == TYPE_PJIT)
    {
        ExtOut("preJIT generated code\n");
    }

    NameForMD_s(methodDesc, g_mdName, mdNameLen);
    ExtOut("%S\n", g_mdName);   
    if (codeHeaderData.ColdRegionStart != NULL)
    {
        ExtOut("Begin %p, size %x. Cold region begin %p, size %x\n",
            SOS_PTR(codeHeaderData.MethodStart), codeHeaderData.HotRegionSize,
            SOS_PTR(codeHeaderData.ColdRegionStart), codeHeaderData.ColdRegionSize);
    }
    else
    {
        ExtOut("Begin %p, size %x\n", SOS_PTR(codeHeaderData.MethodStart), codeHeaderData.MethodSize);
    }

#if !defined(FEATURE_PAL)
    //
    // Set up to mix gc info with the code if requested
    //

    GCEncodingInfo gcEncodingInfo = {0};

    // The actual GC Encoding Table, this is updated during the course of the function.
    gcEncodingInfo.table = NULL;

    // The holder to make sure we clean up the memory for the table
    ArrayHolder<BYTE> table = NULL;

    if (fWithGCInfo)
    {
        // assume that GC encoding table is never more than 40 + methodSize * 2
        int tableSize = 0;
        if (!ClrSafeInt<int>::multiply(codeHeaderData.MethodSize, 2, tableSize) ||
            !ClrSafeInt<int>::addition(tableSize, 40, tableSize))
        {
            ExtOut("<integer overflow>\n");
            return E_FAIL;
        }


        // Assign the new array to the mutable gcEncodingInfo table and to the
        // table ArrayHolder to clean this up when the function exits.
        table = gcEncodingInfo.table = new NOTHROW BYTE[tableSize];
        
        if (gcEncodingInfo.table == NULL)
        {
            ExtOut("Could not allocate memory to read the gc info.\n");
            return E_OUTOFMEMORY;
        }
        
        memset (gcEncodingInfo.table, 0, tableSize);
        // We avoid using move here, because we do not want to return
        if (!SafeReadMemory(TO_TADDR(codeHeaderData.GCInfo), gcEncodingInfo.table, tableSize, NULL))
        {
            ExtOut("Could not read memory %p\n", SOS_PTR(codeHeaderData.GCInfo));
            return Status;
        }

        //
        // Skip the info header
        //
        gcEncodingInfo.methodSize = (unsigned int)codeHeaderData.MethodSize;

        //
        // DumpGCTable will call gcPrintf for each encoding.  We'd like a "give
        // me the next encoding" interface, but we're stuck with the callback.
        // To reconcile this without messing up too much code, we'll create a
        // fiber to dump the gc table.  When we need the next gc encoding,
        // we'll switch to this fiber.  The callback will note the next offset,
        // and switch back to the main fiber.
        //

        gcEncodingInfo.ofs = -1;
        gcEncodingInfo.hotSizeToAdd = 0;
        
        gcEncodingInfo.pvMainFiber = ConvertThreadToFiber(NULL);
        if (!gcEncodingInfo.pvMainFiber && ERROR_ALREADY_FIBER == GetLastError())
            gcEncodingInfo.pvMainFiber = GetCurrentFiber();
        
        if (!gcEncodingInfo.pvMainFiber)
            return Status;

        gcEncodingInfo.pvGCTableFiber = CreateFiber(0, DumpGCTableFiberEntry, &gcEncodingInfo);
        if (!gcEncodingInfo.pvGCTableFiber)
            return Status;

        SwitchToFiber(gcEncodingInfo.pvGCTableFiber);
    }    
#endif

    SOSEHInfo *pInfo = NULL;
    if (fWithEHInfo)
    {
        pInfo = new NOTHROW SOSEHInfo;
        if (pInfo == NULL)
        {
            ReportOOM();                
        }
        else if (g_sos->TraverseEHInfo(MethodDescData.NativeCodeAddr, gatherEh, (LPVOID)pInfo) != S_OK)
        {
            ExtOut("Failed to gather EHInfo data\n");
            delete pInfo;
            pInfo = NULL;            
        }
    }
    
    if (codeHeaderData.ColdRegionStart == NULL)
    {
        g_targetMachine->Unassembly (
                (DWORD_PTR) codeHeaderData.MethodStart,
                ((DWORD_PTR)codeHeaderData.MethodStart) + codeHeaderData.MethodSize,
                dwStartAddr,
                (DWORD_PTR) MethodDescData.GCStressCodeCopy,
#if !defined(FEATURE_PAL)
                fWithGCInfo ? &gcEncodingInfo : 
#endif            
                NULL,
                pInfo,
                bSuppressLines,
                bDisplayOffsets
                );
    }
    else
    {
        ExtOut("Hot region:\n");
        g_targetMachine->Unassembly (
                (DWORD_PTR) codeHeaderData.MethodStart,
                ((DWORD_PTR)codeHeaderData.MethodStart) + codeHeaderData.HotRegionSize,
                dwStartAddr,
                (DWORD_PTR) MethodDescData.GCStressCodeCopy,
#if !defined(FEATURE_PAL)
                fWithGCInfo ? &gcEncodingInfo : 
#endif            
                NULL,
                pInfo,
                bSuppressLines,
                bDisplayOffsets
                );

        ExtOut("Cold region:\n");
        
#if !defined(FEATURE_PAL)
        // Displaying gcinfo for a cold region requires knowing the size of
        // the hot region preceeding.
        gcEncodingInfo.hotSizeToAdd = codeHeaderData.HotRegionSize;
#endif            
        g_targetMachine->Unassembly (
                (DWORD_PTR) codeHeaderData.ColdRegionStart,
                ((DWORD_PTR)codeHeaderData.ColdRegionStart) + codeHeaderData.ColdRegionSize,
                dwStartAddr,
                ((DWORD_PTR) MethodDescData.GCStressCodeCopy) + codeHeaderData.HotRegionSize,                
#if !defined(FEATURE_PAL)
                fWithGCInfo ? &gcEncodingInfo : 
#endif            
                NULL,
                pInfo,
                bSuppressLines,
                bDisplayOffsets
                );

    }

    if (pInfo)
    {
        delete pInfo;
        pInfo = NULL;
    }
    
#if !defined(FEATURE_PAL)
    if (fWithGCInfo)
        DeleteFiber(gcEncodingInfo.pvGCTableFiber);
#endif

    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the in-memory stress log          *
*    !DumpLog [filename]                                               *
*             will dump the stress log corresponding to the clr.dll    *
*             loaded in the debuggee's VAS                             *
*    !DumpLog -addr <addr_of_StressLog::theLog> [filename]             *
*             will dump the stress log associated with any DLL linked  *
*             against utilcode.lib, most commonly mscordbi.dll         *
*             (e.g. !DumpLog -addr mscordbi!StressLog::theLog)         *
*                                                                      *
\**********************************************************************/
DECLARE_API(DumpLog)
{        
    INIT_API_NO_RET_ON_FAILURE();

    MINIDUMP_NOT_SUPPORTED();    

    const char* fileName = "StressLog.txt";

    CLRDATA_ADDRESS StressLogAddress = NULL;
    
    StringHolder sFileName, sLogAddr;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-addr", &sLogAddr.data, COSTRING, TRUE}
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&sFileName.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (nArg > 0 && sFileName.data != NULL)
    {
        fileName = sFileName.data;
    }

    // allow users to specify -addr mscordbdi!StressLog::theLog, for example.
    if (sLogAddr.data != NULL)
    {
        StressLogAddress = GetExpression(sLogAddr.data);
    }

    if (StressLogAddress == NULL)
    {
        if (g_bDacBroken)
        {
#ifdef FEATURE_PAL
            ExtOut("No stress log address. DAC is broken; can't get it\n");
            return E_FAIL;
#else
            // Try to find stress log symbols
            DWORD_PTR dwAddr = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!StressLog::theLog");
            StressLogAddress = dwAddr;        
#endif
        }
        else if (g_sos->GetStressLogAddress(&StressLogAddress) != S_OK)
        {
            ExtOut("Unable to find stress log via DAC\n");
            return E_FAIL;
        }
    }

    if (StressLogAddress == NULL)
    {
        ExtOut("Please provide the -addr argument for the address of the stress log, since no recognized runtime is loaded.\n");
        return E_FAIL;
    }

    ExtOut("Attempting to dump Stress log to file '%s'\n", fileName);

    
    
    Status = StressLog::Dump(StressLogAddress, fileName, g_ExtData);

    if (Status == S_OK)
        ExtOut("SUCCESS: Stress log dumped\n");
    else if (Status == S_FALSE)
        ExtOut("No Stress log in the image, no file written\n");
    else
        ExtOut("FAILURE: Stress log not dumped\n");

    return Status;
}

#ifdef TRACE_GC

DECLARE_API (DumpGCLog)
{
    INIT_API_NODAC();
    MINIDUMP_NOT_SUPPORTED();    
    
    if (GetEEFlavor() == UNKNOWNEE) 
    {
        ExtOut("CLR not loaded\n");
        return Status;
    }

    const char* fileName = "GCLog.txt";

    while (isspace (*args))
        args ++;

    if (*args != 0)
        fileName = args;
    
    DWORD_PTR dwAddr = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!SVR::gc_log_buffer");
    moveN (dwAddr, dwAddr);

    if (dwAddr == 0)
    {
        dwAddr = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!WKS::gc_log_buffer");
        moveN (dwAddr, dwAddr);
        if (dwAddr == 0)
        {
            ExtOut("Can't get either WKS or SVR GC's log file");
            return E_FAIL;
        }
    }
    
    ExtOut("Dumping GC log at %08x\n", dwAddr);

    g_bDacBroken = FALSE;
    
    ExtOut("Attempting to dump GC log to file '%s'\n", fileName);
    
    Status = E_FAIL;

    HANDLE hGCLog = CreateFileA(
        fileName,
        GENERIC_WRITE,
        FILE_SHARE_READ,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (hGCLog == INVALID_HANDLE_VALUE)
    {
        ExtOut("failed to create file: %d\n", GetLastError());
        goto exit;
    }

    int iLogSize = 1024*1024;
    BYTE* bGCLog = new NOTHROW BYTE[iLogSize];
    if (bGCLog == NULL)
    {
        ReportOOM();
        goto exit;
    }

    memset (bGCLog, 0, iLogSize);
    if (!SafeReadMemory(dwAddr, bGCLog, iLogSize, NULL))
    {
        ExtOut("failed to read memory from %08x\n", dwAddr);
    }

    int iRealLogSize = iLogSize - 1;
    while (iRealLogSize >= 0)
    {
        if (bGCLog[iRealLogSize] != '*')
        {
            break;
        }

        iRealLogSize--;
    }

    DWORD dwWritten = 0;
    WriteFile (hGCLog, bGCLog, iRealLogSize + 1, &dwWritten, NULL);

    Status = S_OK;

exit:

    if (hGCLog != INVALID_HANDLE_VALUE)
    {
        CloseHandle (hGCLog);
    }

    if (Status == S_OK)
        ExtOut("SUCCESS: Stress log dumped\n");
    else if (Status == S_FALSE)
        ExtOut("No Stress log in the image, no file written\n");
    else
        ExtOut("FAILURE: Stress log not dumped\n");

    return Status;
}
#endif //TRACE_GC

#ifndef FEATURE_PAL
DECLARE_API (DumpGCConfigLog)
{
    INIT_API();
#ifdef GC_CONFIG_DRIVEN    
    MINIDUMP_NOT_SUPPORTED();    

    if (GetEEFlavor() == UNKNOWNEE) 
    {
        ExtOut("CLR not loaded\n");
        return Status;
    }

    const char* fileName = "GCConfigLog.txt";

    while (isspace (*args))
        args ++;

    if (*args != 0)
        fileName = args;
    
    if (!InitializeHeapData ())
    {
        ExtOut("GC Heap not initialized yet.\n");
        return S_OK;
    }

    BOOL fIsServerGC = IsServerBuild();

    DWORD_PTR dwAddr = 0; 
    DWORD_PTR dwAddrOffset = 0;
    
    if (fIsServerGC) 
    {
        dwAddr = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!SVR::gc_config_log_buffer");
        dwAddrOffset = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!SVR::gc_config_log_buffer_offset");
    }
    else
    {
        dwAddr = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!WKS::gc_config_log_buffer");
        dwAddrOffset = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!WKS::gc_config_log_buffer_offset");
    }

    moveN (dwAddr, dwAddr);
    moveN (dwAddrOffset, dwAddrOffset);

    if (dwAddr == 0)
    {
        ExtOut("Can't get either WKS or SVR GC's config log buffer");
        return E_FAIL;
    }
    
    ExtOut("Dumping GC log at %08x\n", dwAddr);

    g_bDacBroken = FALSE;
    
    ExtOut("Attempting to dump GC log to file '%s'\n", fileName);
    
    Status = E_FAIL;
    
    HANDLE hGCLog = CreateFileA(
        fileName,
        GENERIC_WRITE,
        FILE_SHARE_READ,
        NULL,
        OPEN_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if (hGCLog == INVALID_HANDLE_VALUE)
    {
        ExtOut("failed to create file: %d\n", GetLastError());
        goto exit;
    }

    {
        int iLogSize = (int)dwAddrOffset;

        ArrayHolder<BYTE> bGCLog = new NOTHROW BYTE[iLogSize];
        if (bGCLog == NULL)
        {
            ReportOOM();
            goto exit;
        }

        memset (bGCLog, 0, iLogSize);
        if (!SafeReadMemory(dwAddr, bGCLog, iLogSize, NULL))
        {
            ExtOut("failed to read memory from %08x\n", dwAddr);
        }

        SetFilePointer (hGCLog, 0, 0, FILE_END);
        DWORD dwWritten;
        WriteFile (hGCLog, bGCLog, iLogSize, &dwWritten, NULL);
    }

    Status = S_OK;

exit:

    if (hGCLog != INVALID_HANDLE_VALUE)
    {
        CloseHandle (hGCLog);
    }

    if (Status == S_OK)
        ExtOut("SUCCESS: Stress log dumped\n");
    else if (Status == S_FALSE)
        ExtOut("No Stress log in the image, no file written\n");
    else
        ExtOut("FAILURE: Stress log not dumped\n");

    return Status;
#else
    ExtOut("Not implemented\n");
    return S_OK;
#endif //GC_CONFIG_DRIVEN
}
#endif // FEATURE_PAL

#ifdef GC_CONFIG_DRIVEN
static const char * const str_interesting_data_points[] =
{
    "pre short", // 0
    "post short", // 1
    "merged pins", // 2
    "converted pins", // 3
    "pre pin", // 4
    "post pin", // 5
    "pre and post pin", // 6
    "pre short padded", // 7
    "post short padded", // 7
};

static const char * const str_heap_compact_reasons[] = 
{
    "low on ephemeral space",
    "high fragmetation",
    "couldn't allocate gaps",
    "user specfied compact LOH",
    "last GC before OOM",
    "induced compacting GC",
    "fragmented gen0 (ephemeral GC)", 
    "high memory load (ephemeral GC)",
    "high memory load and frag",
    "very high memory load and frag",
    "no gc mode"
};

static BOOL gc_heap_compact_reason_mandatory_p[] =
{
    TRUE, //compact_low_ephemeral = 0,
    FALSE, //compact_high_frag = 1,
    TRUE, //compact_no_gaps = 2,
    TRUE, //compact_loh_forced = 3,
    TRUE, //compact_last_gc = 4
    TRUE, //compact_induced_compacting = 5,
    FALSE, //compact_fragmented_gen0 = 6, 
    FALSE, //compact_high_mem_load = 7, 
    TRUE, //compact_high_mem_frag = 8, 
    TRUE, //compact_vhigh_mem_frag = 9,
    TRUE //compact_no_gc_mode = 10
};

static const char * const str_heap_expand_mechanisms[] = 
{
    "reused seg with normal fit",
    "reused seg with best fit",
    "expand promoting eph",
    "expand with a new seg",
    "no memory for a new seg",
    "expand in next full GC"
};

static const char * const str_bit_mechanisms[] = 
{
    "using mark list",
    "demotion"
};

static const char * const str_gc_global_mechanisms[] =
{
    "concurrent GCs", 
    "compacting GCs",
    "promoting GCs",
    "GCs that did demotion",
    "card bundles",
    "elevation logic"
};

void PrintInterestingGCInfo(DacpGCInterestingInfoData* dataPerHeap)
{
    ExtOut("Interesting data points\n");
    size_t* data = dataPerHeap->interestingDataPoints;
    for (int i = 0; i < DAC_NUM_GC_DATA_POINTS; i++)
    {
        ExtOut("%20s: %d\n", str_interesting_data_points[i], data[i]);
    }

    ExtOut("\nCompacting reasons\n");
    data = dataPerHeap->compactReasons;
    for (int i = 0; i < DAC_MAX_COMPACT_REASONS_COUNT; i++)
    {
        ExtOut("[%s]%35s: %d\n", (gc_heap_compact_reason_mandatory_p[i] ? "M" : "W"), str_heap_compact_reasons[i], data[i]);
    }

    ExtOut("\nExpansion mechanisms\n");
    data = dataPerHeap->expandMechanisms;
    for (int i = 0; i < DAC_MAX_EXPAND_MECHANISMS_COUNT; i++)
    {
        ExtOut("%30s: %d\n", str_heap_expand_mechanisms[i], data[i]);
    }

    ExtOut("\nOther mechanisms enabled\n");
    data = dataPerHeap->bitMechanisms;
    for (int i = 0; i < DAC_MAX_GC_MECHANISM_BITS_COUNT; i++)
    {
        ExtOut("%20s: %d\n", str_bit_mechanisms[i], data[i]);
    }
}
#endif //GC_CONFIG_DRIVEN

DECLARE_API(DumpGCData)
{
    INIT_API();

#ifdef GC_CONFIG_DRIVEN
    MINIDUMP_NOT_SUPPORTED();    

    if (!InitializeHeapData ())
    {
        ExtOut("GC Heap not initialized yet.\n");
        return S_OK;
    }

    DacpGCInterestingInfoData interestingInfo;
    interestingInfo.RequestGlobal(g_sos);
    for (int i = 0; i < DAC_MAX_GLOBAL_GC_MECHANISMS_COUNT; i++)
    {
        ExtOut("%-30s: %d\n", str_gc_global_mechanisms[i], interestingInfo.globalMechanisms[i]);
    }

    ExtOut("\n[info per heap]\n");

    if (!IsServerBuild())
    {
        if (interestingInfo.Request(g_sos) != S_OK)
        {
            ExtOut("Error requesting interesting GC info\n");
            return E_FAIL;
        }
            
        PrintInterestingGCInfo(&interestingInfo);
    }
    else
    {   
        DWORD dwNHeaps = GetGcHeapCount();
        DWORD dwAllocSize;
        if (!ClrSafeInt<DWORD>::multiply(sizeof(CLRDATA_ADDRESS), dwNHeaps, dwAllocSize))
        {
            ExtOut("Failed to get GCHeaps:  integer overflow\n");
            return Status;
        }

        CLRDATA_ADDRESS *heapAddrs = (CLRDATA_ADDRESS*)alloca(dwAllocSize);
        if (g_sos->GetGCHeapList(dwNHeaps, heapAddrs, NULL) != S_OK)
        {
            ExtOut("Failed to get GCHeaps\n");
            return Status;
        }
        
        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            if (interestingInfo.Request(g_sos, heapAddrs[n]) != S_OK)
            {
                ExtOut("Heap %d: Error requesting interesting GC info\n", n);
                return E_FAIL;
            }

            ExtOut("--------info for heap %d--------\n", n);
            PrintInterestingGCInfo(&interestingInfo);
            ExtOut("\n");
        }
    }

    return S_OK;
#else
    ExtOut("Not implemented\n");
    return S_OK;
#endif //GC_CONFIG_DRIVEN
}

#ifndef FEATURE_PAL
/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the build number and type of the  *  
*    mscoree.dll                                                       *
*                                                                      *
\**********************************************************************/
DECLARE_API (EEVersion)
{
    INIT_API();

    EEFLAVOR eef = GetEEFlavor();
    if (eef == UNKNOWNEE) {
        ExtOut("CLR not loaded\n");
        return Status;
    }
    
    if (g_ExtSymbols2) {
        VS_FIXEDFILEINFO version;
        
        BOOL ret = GetEEVersion(&version);
            
        if (ret) 
        {
            if (version.dwFileVersionMS != (DWORD)-1)
            {
                ExtOut("%u.%u.%u.%u",
                       HIWORD(version.dwFileVersionMS),
                       LOWORD(version.dwFileVersionMS),
                       HIWORD(version.dwFileVersionLS),
                       LOWORD(version.dwFileVersionLS));
                if (version.dwFileFlags & VS_FF_DEBUG) 
                {                    
                    ExtOut(" Checked or debug build");
                }
                else
                { 
                    BOOL fRet = IsRetailBuild ((size_t)moduleInfo[eef].baseAddr);

                    if (fRet)
                        ExtOut(" retail");
                    else
                        ExtOut(" free");
                }

                ExtOut("\n");
            }
        }
    }    
    
    if (!InitializeHeapData ())
        ExtOut("GC Heap not initialized, so GC mode is not determined yet.\n");
    else if (IsServerBuild()) 
        ExtOut("Server mode with %d gc heaps\n", GetGcHeapCount()); 
    else
        ExtOut("Workstation mode\n");

    if (!GetGcStructuresValid())
    {
        ExtOut("In plan phase of garbage collection\n");
    }

    // Print SOS version
    VS_FIXEDFILEINFO sosVersion;
    if (GetSOSVersion(&sosVersion))
    {
        if (sosVersion.dwFileVersionMS != (DWORD)-1)
        {
            ExtOut("SOS Version: %u.%u.%u.%u",
                   HIWORD(sosVersion.dwFileVersionMS),
                   LOWORD(sosVersion.dwFileVersionMS),
                   HIWORD(sosVersion.dwFileVersionLS),
                   LOWORD(sosVersion.dwFileVersionLS));
            if (sosVersion.dwFileFlags & VS_FF_DEBUG) 
            {                    
                ExtOut(" Checked or debug build");                    
            }
            else
            { 
                ExtOut(" retail build");                    
            }

            ExtOut("\n");
        }
    }
    return Status;
}
#endif // FEATURE_PAL

#ifndef FEATURE_PAL
/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to print the environment setting for      *  
*    the current process.                                              *
*                                                                      *
\**********************************************************************/
DECLARE_API (ProcInfo)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();        

    if (IsDumpFile())
    {
        ExtOut("!ProcInfo is not supported on a dump file.\n");
        return Status;
    }

#define INFO_ENV        0x00000001
#define INFO_TIME       0x00000002    
#define INFO_MEM        0x00000004
#define INFO_ALL        0xFFFFFFFF

    DWORD fProcInfo = INFO_ALL;

    if (_stricmp (args, "-env") == 0) {
        fProcInfo = INFO_ENV;
    }

    if (_stricmp (args, "-time") == 0) {
        fProcInfo = INFO_TIME;
    }

    if (_stricmp (args, "-mem") == 0) {
        fProcInfo = INFO_MEM;
    }

    if (fProcInfo & INFO_ENV) {
        ExtOut("---------------------------------------\n");
        ExtOut("Environment\n");
        ULONG64 pPeb;
        g_ExtSystem->GetCurrentProcessPeb(&pPeb);

        static ULONG Offset_ProcessParam = -1;
        static ULONG Offset_Environment = -1;
        if (Offset_ProcessParam == -1)
        {
            ULONG TypeId;
            ULONG64 NtDllBase;
            if (SUCCEEDED(g_ExtSymbols->GetModuleByModuleName ("ntdll",0,NULL,
                                                               &NtDllBase)))
            {
                if (SUCCEEDED(g_ExtSymbols->GetTypeId (NtDllBase, "PEB", &TypeId)))
                {
                    if (FAILED (g_ExtSymbols->GetFieldOffset(NtDllBase, TypeId,
                                                         "ProcessParameters", &Offset_ProcessParam)))
                        Offset_ProcessParam = -1;
                }
                if (SUCCEEDED(g_ExtSymbols->GetTypeId (NtDllBase, "_RTL_USER_PROCESS_PARAMETERS", &TypeId)))
                {
                    if (FAILED (g_ExtSymbols->GetFieldOffset(NtDllBase, TypeId,
                                                         "Environment", &Offset_Environment)))
                        Offset_Environment = -1;
                }
            }
        }
        // We can not get it from PDB.  Use the fixed one.
        if (Offset_ProcessParam == -1)
            Offset_ProcessParam = offsetof (DT_PEB, ProcessParameters);

        if (Offset_Environment == -1)
            Offset_Environment = offsetof (DT_RTL_USER_PROCESS_PARAMETERS, Environment);


        ULONG64 addr = pPeb + Offset_ProcessParam;
        DWORD_PTR value;
        g_ExtData->ReadVirtual(UL64_TO_CDA(addr), &value, sizeof(PVOID), NULL);
        addr = value + Offset_Environment;
        g_ExtData->ReadVirtual(UL64_TO_CDA(addr), &value, sizeof(PVOID), NULL);

        static WCHAR buffer[DT_OS_PAGE_SIZE/2];        
        ULONG readBytes = DT_OS_PAGE_SIZE;
        ULONG64 Page;
        if ((g_ExtData->ReadDebuggerData( DEBUG_DATA_MmPageSize, &Page, sizeof(Page), NULL)) == S_OK
            && Page > 0)
        {
            ULONG uPageSize = (ULONG)(ULONG_PTR)Page;
            if (readBytes > uPageSize) {
                readBytes = uPageSize;
            }
        }        
        addr = value;
        while (1) {
            if (IsInterrupt())
                return Status;
            if (FAILED(g_ExtData->ReadVirtual(UL64_TO_CDA(addr), &buffer, readBytes, NULL)))
                break;
            addr += readBytes;
            WCHAR *pt = buffer;
            WCHAR *end = pt;
            while (pt < &buffer[DT_OS_PAGE_SIZE/2]) {
                end = _wcschr (pt, L'\0');
                if (end == NULL) {
                    char format[20];
                    sprintf_s (format,_countof (format), "%dS", &buffer[DT_OS_PAGE_SIZE/2] - pt);
                    ExtOut(format, pt);
                    break;
                }
                else if (end == pt) {
                    break;
                }
                ExtOut("%S\n", pt);
                pt = end + 1;
            }
            if (end == pt) {
                break;
            }
        }
    }
    
    HANDLE hProcess = INVALID_HANDLE_VALUE;
    if (fProcInfo & (INFO_TIME | INFO_MEM)) {
        ULONG64 handle;
        g_ExtSystem->GetCurrentProcessHandle(&handle);
        hProcess = (HANDLE)handle;
    }
    
    if (!IsDumpFile() && fProcInfo & INFO_TIME) {
        FILETIME CreationTime;
        FILETIME ExitTime;
        FILETIME KernelTime;
        FILETIME UserTime;

        typedef BOOL (WINAPI *FntGetProcessTimes)(HANDLE, LPFILETIME, LPFILETIME, LPFILETIME, LPFILETIME);
        static FntGetProcessTimes pFntGetProcessTimes = (FntGetProcessTimes)-1;
        if (pFntGetProcessTimes == (FntGetProcessTimes)-1) {
            HINSTANCE hstat = LoadLibrary ("Kernel32.dll");
            if (hstat != 0)
            {
                pFntGetProcessTimes = (FntGetProcessTimes)GetProcAddress (hstat, "GetProcessTimes");
                FreeLibrary (hstat);
            }
            else
                pFntGetProcessTimes = NULL;
        }

        if (pFntGetProcessTimes && pFntGetProcessTimes (hProcess,&CreationTime,&ExitTime,&KernelTime,&UserTime)) {
            ExtOut("---------------------------------------\n");
            ExtOut("Process Times\n");
            static const char *Month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
                        "Oct", "Nov", "Dec"};
            SYSTEMTIME SystemTime;
            FILETIME LocalFileTime;
            if (FileTimeToLocalFileTime (&CreationTime,&LocalFileTime)
                && FileTimeToSystemTime (&LocalFileTime,&SystemTime)) {
                ExtOut("Process Started at: %4d %s %2d %d:%d:%d.%02d\n",
                        SystemTime.wYear, Month[SystemTime.wMonth-1], SystemTime.wDay,
                        SystemTime.wHour, SystemTime.wMinute,
                        SystemTime.wSecond, SystemTime.wMilliseconds/10);
            }
        
            DWORD nDay = 0;
            DWORD nHour = 0;
            DWORD nMin = 0;
            DWORD nSec = 0;
            DWORD nHundred = 0;
            
            ULONG64 totalTime;
             
            totalTime = KernelTime.dwLowDateTime + (((ULONG64)KernelTime.dwHighDateTime) << 32);
            nDay = (DWORD)(totalTime/(24*3600*10000000ui64));
            totalTime %= 24*3600*10000000ui64;
            nHour = (DWORD)(totalTime/(3600*10000000ui64));
            totalTime %= 3600*10000000ui64;
            nMin = (DWORD)(totalTime/(60*10000000));
            totalTime %= 60*10000000;
            nSec = (DWORD)(totalTime/10000000);
            totalTime %= 10000000;
            nHundred = (DWORD)(totalTime/100000);
            ExtOut("Kernel CPU time   : %d days %02d:%02d:%02d.%02d\n",
                    nDay, nHour, nMin, nSec, nHundred);
            
            DWORD sDay = nDay;
            DWORD sHour = nHour;
            DWORD sMin = nMin;
            DWORD sSec = nSec;
            DWORD sHundred = nHundred;
            
            totalTime = UserTime.dwLowDateTime + (((ULONG64)UserTime.dwHighDateTime) << 32);
            nDay = (DWORD)(totalTime/(24*3600*10000000ui64));
            totalTime %= 24*3600*10000000ui64;
            nHour = (DWORD)(totalTime/(3600*10000000ui64));
            totalTime %= 3600*10000000ui64;
            nMin = (DWORD)(totalTime/(60*10000000));
            totalTime %= 60*10000000;
            nSec = (DWORD)(totalTime/10000000);
            totalTime %= 10000000;
            nHundred = (DWORD)(totalTime/100000);
            ExtOut("User   CPU time   : %d days %02d:%02d:%02d.%02d\n",
                    nDay, nHour, nMin, nSec, nHundred);
        
            sDay += nDay;
            sHour += nHour;
            sMin += nMin;
            sSec += nSec;
            sHundred += nHundred;
            if (sHundred >= 100) {
                sSec += sHundred/100;
                sHundred %= 100;
            }
            if (sSec >= 60) {
                sMin += sSec/60;
                sSec %= 60;
            }
            if (sMin >= 60) {
                sHour += sMin/60;
                sMin %= 60;
            }
            if (sHour >= 24) {
                sDay += sHour/24;
                sHour %= 24;
            }
            ExtOut("Total  CPU time   : %d days %02d:%02d:%02d.%02d\n",
                    sDay, sHour, sMin, sSec, sHundred);
        }
    }

    if (!IsDumpFile() && fProcInfo & INFO_MEM) {
        typedef
        NTSTATUS
        (NTAPI
         *FntNtQueryInformationProcess)(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);

        static FntNtQueryInformationProcess pFntNtQueryInformationProcess = (FntNtQueryInformationProcess)-1;
        if (pFntNtQueryInformationProcess == (FntNtQueryInformationProcess)-1) {
            HINSTANCE hstat = LoadLibrary ("ntdll.dll");
            if (hstat != 0)
            {
                pFntNtQueryInformationProcess = (FntNtQueryInformationProcess)GetProcAddress (hstat, "NtQueryInformationProcess");
                FreeLibrary (hstat);
            }
            else
                pFntNtQueryInformationProcess = NULL;
        }
        VM_COUNTERS memory;
        if (pFntNtQueryInformationProcess &&
            NT_SUCCESS (pFntNtQueryInformationProcess (hProcess,ProcessVmCounters,&memory,sizeof(memory),NULL))) {
            ExtOut("---------------------------------------\n");
            ExtOut("Process Memory\n");
            ExtOut("WorkingSetSize: %8d KB       PeakWorkingSetSize: %8d KB\n",
                    memory.WorkingSetSize/1024, memory.PeakWorkingSetSize/1024);
            ExtOut("VirtualSize:    %8d KB       PeakVirtualSize:    %8d KB\n", 
                    memory.VirtualSize/1024, memory.PeakVirtualSize/1024);
            ExtOut("PagefileUsage:  %8d KB       PeakPagefileUsage:  %8d KB\n", 
                    memory.PagefileUsage/1024, memory.PeakPagefileUsage/1024);
        }

        MEMORYSTATUS memstat;
        GlobalMemoryStatus (&memstat);
        ExtOut("---------------------------------------\n");
        ExtOut("%ld percent of memory is in use.\n\n",
                memstat.dwMemoryLoad);
        ExtOut("Memory Availability (Numbers in MB)\n\n");
        ExtOut("                  %8s     %8s\n", "Total", "Avail");
        ExtOut("Physical Memory   %8d     %8d\n", memstat.dwTotalPhys/1024/1024, memstat.dwAvailPhys/1024/1024);
        ExtOut("Page File         %8d     %8d\n", memstat.dwTotalPageFile/1024/1024, memstat.dwAvailPageFile/1024/1024);
        ExtOut("Virtual Memory    %8d     %8d\n", memstat.dwTotalVirtual/1024/1024, memstat.dwAvailVirtual/1024/1024);
    }

    return Status;
}
#endif // FEATURE_PAL

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find the address of EE data for a      *  
*    metadata token.                                                   *
*                                                                      *
\**********************************************************************/
DECLARE_API(Token2EE)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    StringHolder DllName;
    ULONG64 token = 0;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };

    CMDValue arg[] = 
    {   // vptr, type
        {&DllName.data, COSTRING},
        {&token, COHEX}
    };

    size_t nArg;
    if (!GetCMDOption(args,option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (nArg!=2)
    {
        ExtOut("Usage: !Token2EE module_name mdToken\n");
        ExtOut("       You can pass * for module_name to search all modules.\n");
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    int numModule;
    ArrayHolder<DWORD_PTR> moduleList = NULL;

    if (strcmp(DllName.data, "*") == 0)
    {
        moduleList = ModuleFromName(NULL, &numModule);
    }
    else
    {
        moduleList = ModuleFromName(DllName.data, &numModule);
    }
    
    if (moduleList == NULL)
    {
        ExtOut("Failed to request module list.\n");
    }
    else
    {
        for (int i = 0; i < numModule; i ++)
        {
            if (IsInterrupt())
                break;

            if (i > 0)
            {
                ExtOut("--------------------------------------\n");
            }        

            DWORD_PTR dwAddr = moduleList[i];
            WCHAR FileName[MAX_LONGPATH];
            FileNameForModule(dwAddr, FileName);

            // We'd like a short form for this output
            LPWSTR pszFilename = _wcsrchr (FileName, DIRECTORY_SEPARATOR_CHAR_W);
            if (pszFilename == NULL)
            {
                pszFilename = FileName;
            }
            else
            {
                pszFilename++; // skip past the last "\" character
            }
            
            DMLOut("Module:      %s\n", DMLModule(dwAddr));
            ExtOut("Assembly:    %S\n", pszFilename);
            
            GetInfoFromModule(dwAddr, (ULONG)token);
        }
    }
    
    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find the address of EE data for a      *  
*    metadata token.                                                   *
*                                                                      *
\**********************************************************************/
DECLARE_API(Name2EE)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();

    StringHolder DllName, TypeName; 
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    
    CMDValue arg[] = 
    {   // vptr, type
        {&DllName.data, COSTRING},
        {&TypeName.data, COSTRING}
    };
    size_t nArg;
    
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);

    if (nArg == 1)
    {
        // The input may be in the form <modulename>!<type>
        // If so, do some surgery on the input params.

        // There should be only 1 ! character
        LPSTR pszSeperator = strchr (DllName.data, '!');
        if (pszSeperator != NULL)
        {
            if (strchr (pszSeperator + 1, '!') == NULL)
            {
                size_t capacity_TypeName_data = strlen(pszSeperator + 1) + 1;
                TypeName.data = new NOTHROW char[capacity_TypeName_data];
                if (TypeName.data)
                {
                    // get the type name,
                    strcpy_s (TypeName.data, capacity_TypeName_data, pszSeperator + 1);
                    // and truncate DllName
                    *pszSeperator = '\0';

                    // Do some extra validation
                    if (strlen (DllName.data) >= 1 &&
                        strlen (TypeName.data) > 1)
                    {
                        nArg = 2;
                    }
                }
            }
        }
    }
    
    if (nArg != 2)
    {
        ExtOut("Usage: " SOSPrefix "name2ee module_name item_name\n");
        ExtOut("  or   " SOSPrefix "name2ee module_name!item_name\n");        
        ExtOut("       use * for module_name to search all loaded modules\n");
        ExtOut("Examples: " SOSPrefix "name2ee  mscorlib.dll System.String.ToString\n");
        ExtOut("          " SOSPrefix "name2ee *!System.String\n");
        return Status;
    }
    
    int numModule;
    ArrayHolder<DWORD_PTR> moduleList = NULL;
    if (strcmp(DllName.data, "*") == 0)
    {
        moduleList = ModuleFromName(NULL, &numModule);
    }
    else
    {
        moduleList = ModuleFromName(DllName.data, &numModule);
    }
            

    if (moduleList == NULL)
    {
        ExtOut("Failed to request module list.\n", DllName.data);
    }
    else
    {
        for (int i = 0; i < numModule; i ++)
        {
            if (IsInterrupt())
                break;

            if (i > 0)
            {
                ExtOut("--------------------------------------\n");
            }
            
            DWORD_PTR dwAddr = moduleList[i];
            WCHAR FileName[MAX_LONGPATH];
            FileNameForModule (dwAddr, FileName);

            // We'd like a short form for this output
            LPWSTR pszFilename = _wcsrchr (FileName, DIRECTORY_SEPARATOR_CHAR_W);
            if (pszFilename == NULL)
            {
                pszFilename = FileName;
            }
            else
            {
                pszFilename++; // skip past the last "\" character
            }
            
            DMLOut("Module:      %s\n", DMLModule(dwAddr));
            ExtOut("Assembly:    %S\n", pszFilename);
            GetInfoFromName(dwAddr, TypeName.data);
        }
    }
 
    return Status;
}


#ifndef FEATURE_PAL
DECLARE_API(PathTo)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    DWORD_PTR root = NULL;
    DWORD_PTR target = NULL;
    BOOL dml = FALSE;
    size_t nArg;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&root, COHEX},
        {&target, COHEX},
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }    
    
    if (root == 0 || target == 0)
    {
        ExtOut("Invalid argument %s\n", args);
        return Status;
    }
    
    GCRootImpl gcroot;
    bool result = gcroot.PrintPathToObject(root, target);
    
    if (!result)
        ExtOut("Did not find a path from %p to %p.\n", SOS_PTR(root), SOS_PTR(target));
    
    return Status;
}
#endif



/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function finds all roots (on stack or in handles) for a      *  
*    given object.                                                     *
*                                                                      *
\**********************************************************************/
DECLARE_API(GCRoot)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    BOOL bNoStacks = FALSE;
    DWORD_PTR obj = NULL;
    BOOL dml = FALSE;
    BOOL all = FALSE;
    size_t nArg;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-nostacks", &bNoStacks, COBOOL, FALSE},
        {"-all", &all, COBOOL, FALSE},
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 

    {   // vptr, type
        {&obj, COHEX}
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }    
    if (obj == 0)
    {
        ExtOut("Invalid argument %s\n", args);
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);      
    GCRootImpl gcroot;
    int i = gcroot.PrintRootsForObject(obj, all == TRUE, bNoStacks == TRUE);
    
    if (IsInterrupt())
        ExtOut("Interrupted, data may be incomplete.\n");
    
    if (all)
        ExtOut("Found %d roots.\n", i);
    else
        ExtOut("Found %d unique roots (run '!GCRoot -all' to see all roots).\n", i);

    return Status;
}

DECLARE_API(GCWhere)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();

    BOOL dml = FALSE;
    BOOL bGetBrick;
    BOOL bGetCard;
    TADDR taddrObj = 0;
    size_t nArg;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-brick", &bGetBrick, COBOOL, FALSE},
        {"-card", &bGetCard, COBOOL, FALSE},
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&taddrObj, COHEX}
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    // Obtain allocation context for each managed thread.    
    AllocInfo allocInfo;
    allocInfo.Init();

    TADDR_SEGINFO trngSeg  = { 0, 0, 0 };
    TADDR_RANGE   allocCtx = { 0, 0 };
    int   gen = -1;
    BOOL  bLarge = FALSE;
    BOOL  bFound = FALSE;

    size_t size = 0;
    if (sos::IsObject(taddrObj))
    {
        TADDR taddrMT; 
        BOOL  bContainsPointers;
        if(FAILED(GetMTOfObject(taddrObj, &taddrMT)) ||
           !GetSizeEfficient(taddrObj, taddrMT, FALSE, size, bContainsPointers))
        {
            ExtWarn("Couldn't get size for object %#p: possible heap corruption.\n",
                SOS_PTR(taddrObj));
        }
    }

    if (!IsServerBuild())
    {
        DacpGcHeapDetails heapDetails;
        if (heapDetails.Request(g_sos) != S_OK)
        {
            ExtOut("Error requesting gc heap details\n");
            return Status;
        }

        if (GCObjInHeap(taddrObj, heapDetails, trngSeg, gen, allocCtx, bLarge))
        {
            ExtOut("Address   " WIN64_8SPACES " Gen   Heap   segment   " WIN64_8SPACES " begin     " WIN64_8SPACES " allocated  " WIN64_8SPACES " size\n");
            ExtOut("%p   %d     %2d     %p   %p   %p    0x%x(%d)\n",
                SOS_PTR(taddrObj), gen, 0, SOS_PTR(trngSeg.segAddr), SOS_PTR(trngSeg.start), SOS_PTR(trngSeg.end), size, size);
            bFound = TRUE;
        }
    }
    else
    {
        DacpGcHeapData gcheap;
        if (gcheap.Request(g_sos) != S_OK)
        {
            ExtOut("Error requesting GC Heap data\n");
            return Status;
        }

        DWORD dwAllocSize;
        DWORD dwNHeaps = gcheap.HeapCount;
        if (!ClrSafeInt<DWORD>::multiply(sizeof(CLRDATA_ADDRESS), dwNHeaps, dwAllocSize))
        {
            ExtOut("Failed to get GCHeaps:  integer overflow\n");
            return Status;
        }

        CLRDATA_ADDRESS *heapAddrs = (CLRDATA_ADDRESS*)alloca(dwAllocSize);
        if (g_sos->GetGCHeapList(dwNHeaps, heapAddrs, NULL) != S_OK)
        {
            ExtOut("Failed to get GCHeaps\n");
            return Status;
        }
 
        for (DWORD n = 0; n < dwNHeaps; n ++)
        {
            DacpGcHeapDetails heapDetails;
            if (heapDetails.Request(g_sos, heapAddrs[n]) != S_OK)
            {
                ExtOut("Error requesting details\n");
                return Status;
            }

            if (GCObjInHeap(taddrObj, heapDetails, trngSeg, gen, allocCtx, bLarge))
            {
                ExtOut("Address " WIN64_8SPACES " Gen Heap segment " WIN64_8SPACES " begin   " WIN64_8SPACES " allocated" WIN64_8SPACES " size\n");
                ExtOut("%p   %d     %2d     %p   %p   %p    0x%x(%d)\n",
                    SOS_PTR(taddrObj), gen, n, SOS_PTR(trngSeg.segAddr), SOS_PTR(trngSeg.start), SOS_PTR(trngSeg.end), size, size);
                bFound = TRUE;
                break;
            }
        }
    }

    if (!bFound)
    {
        ExtOut("Address %#p not found in the managed heap.\n", SOS_PTR(taddrObj));
    }

    return Status;
}

#ifndef FEATURE_PAL

DECLARE_API(FindRoots)
{
#ifndef FEATURE_PAL
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();

    if (IsDumpFile())
    {
        ExtOut("!FindRoots is not supported on a dump file.\n");
        return Status;
    }
    
    LONG_PTR gen = -100; // initialized outside the legal range: [-1, 2]
    StringHolder sgen;
    TADDR taObj = NULL;
    BOOL dml = FALSE;
    size_t nArg;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-gen", &sgen.data, COSTRING, TRUE},
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&taObj, COHEX}
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (sgen.data != NULL)
    {
        if (_stricmp(sgen.data, "any") == 0)
        {
            gen = -1;
        }
        else
        {
            gen = GetExpression(sgen.data);
        }
    }
    if ((gen < -1 || gen > 2) && (taObj == 0))
    {
        ExtOut("Incorrect options.  Usage:\n\t!FindRoots -gen <N>\n\t\twhere N is 0, 1, 2, or \"any\". OR\n\t!FindRoots <obj>\n");
        return Status;
    }

    if (gen >= -1 && gen <= 2)
    {
        IXCLRDataProcess2* idp2 = NULL;
        if (FAILED(g_clrData->QueryInterface(IID_IXCLRDataProcess2, (void**) &idp2)))
        {
            ExtOut("Your version of the runtime/DAC do not support this command.\n");
            return Status;
        }

        // Request GC_MARK_END notifications from debuggee
        GcEvtArgs gea = { GC_MARK_END, { ((gen == -1) ? 7 : (1 << gen)) } };
        idp2->SetGcNotification(gea);
        // ... and register the notification handler
        g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, "sxe -c \"!HandleCLRN\" clrn", 0);
        // the above notification is removed in CNotification::OnGcEvent()
    }
    else
    {
        // verify that the last event in the debugger was indeed a CLRN exception
        DEBUG_LAST_EVENT_INFO_EXCEPTION dle;
        CNotification Notification;

        if (!CheckCLRNotificationEvent(&dle))
        {
            ExtOut("The command !FindRoots can only be used after the debugger stopped on a CLRN GC notification.\n");
            ExtOut("At this time !GCRoot should be used instead.\n");
            return Status;
        }
        // validate argument
        if (!g_snapshot.Build())
        {
            ExtOut("Unable to build snapshot of the garbage collector state\n");
            return Status;
        }

        if (g_snapshot.GetHeap(taObj) == NULL)
        {
            ExtOut("Address %#p is not in the managed heap.\n", SOS_PTR(taObj));
            return Status;
        }

        int ogen = g_snapshot.GetGeneration(taObj);
        if (ogen > CNotification::GetCondemnedGen())
        {
            DMLOut("Object %s will survive this collection:\n\tgen(%#p) = %d > %d = condemned generation.\n",
                DMLObject(taObj), SOS_PTR(taObj), ogen, CNotification::GetCondemnedGen());
            return Status;
        }

        GCRootImpl gcroot;
        int roots = gcroot.FindRoots(CNotification::GetCondemnedGen(), taObj);
        
        ExtOut("Found %d roots.\n", roots);
    }

    return Status;
#else
    return E_NOTIMPL;
#endif
}

class GCHandleStatsForDomains
{
public:
    const static int SHARED_DOMAIN_INDEX = 0;
    const static int SYSTEM_DOMAIN_INDEX = 1;
    
    GCHandleStatsForDomains() 
        : m_singleDomainMode(FALSE), m_numDomains(0), m_pStatistics(NULL), m_pDomainPointers(NULL)
    {
    }

    ~GCHandleStatsForDomains()
    {
        if (m_pStatistics)
        {
            if (m_singleDomainMode)
                delete m_pStatistics;
            else
                delete [] m_pStatistics;
        }
        
        if (m_pDomainPointers)
            delete [] m_pDomainPointers;
    }
    
    BOOL Init(BOOL singleDomainMode)
    {
        m_singleDomainMode = singleDomainMode; 
        if (m_singleDomainMode)
        {
            m_numDomains = 1;
            m_pStatistics = new NOTHROW GCHandleStatistics();
            if (m_pStatistics == NULL)
                return FALSE;
        }
        else
        {
            DacpAppDomainStoreData adsData;
            if (adsData.Request(g_sos) != S_OK)
                return FALSE;

            m_numDomains = adsData.DomainCount + 2;
            ArrayHolder<CLRDATA_ADDRESS> pArray = new NOTHROW CLRDATA_ADDRESS[adsData.DomainCount + 2];
            if (pArray == NULL)
                return FALSE;

            pArray[SHARED_DOMAIN_INDEX] = adsData.sharedDomain;
            pArray[SYSTEM_DOMAIN_INDEX] = adsData.systemDomain;
            
            if (g_sos->GetAppDomainList(adsData.DomainCount, pArray+2, NULL) != S_OK)
                return FALSE;
            
            m_pDomainPointers = pArray.Detach();
            m_pStatistics = new NOTHROW GCHandleStatistics[adsData.DomainCount + 2];
            if (m_pStatistics == NULL)
                return FALSE;
        }
        
        return TRUE;
    }

    GCHandleStatistics *LookupStatistics(CLRDATA_ADDRESS appDomainPtr) const
    {
        if (m_singleDomainMode)
        {
            // You can pass NULL appDomainPtr if you are in singleDomainMode
            return m_pStatistics;
        }
        else
        {
            for (int i=0; i < m_numDomains; i++)
                if (m_pDomainPointers[i] == appDomainPtr)
                    return m_pStatistics + i;
        }
        
        return NULL;
    }
    
    
    GCHandleStatistics *GetStatistics(int appDomainIndex) const
    {
        SOS_Assert(appDomainIndex >= 0);
        SOS_Assert(appDomainIndex < m_numDomains);
        
        return m_singleDomainMode ? m_pStatistics : m_pStatistics + appDomainIndex;
    }
    
    int GetNumDomains() const
    {
        return m_numDomains;
    }
    
    CLRDATA_ADDRESS GetDomain(int index) const
    {
        SOS_Assert(index >= 0);
        SOS_Assert(index < m_numDomains);
        return m_pDomainPointers[index];
    }
    
private:
    BOOL m_singleDomainMode;
    int m_numDomains;
    GCHandleStatistics *m_pStatistics;
    CLRDATA_ADDRESS *m_pDomainPointers;
};

class GCHandlesImpl
{
public:
    GCHandlesImpl(PCSTR args)
        : mPerDomain(FALSE), mStat(FALSE), mDML(FALSE), mType((int)~0)
    {
        ArrayHolder<char> type = NULL;
        CMDOption option[] = 
        {
            {"-perdomain", &mPerDomain, COBOOL, FALSE},
            {"-stat", &mStat, COBOOL, FALSE},
            {"-type", &type, COSTRING, TRUE},
            {"/d", &mDML, COBOOL, FALSE},
        };
        
        if (!GetCMDOption(args,option,_countof(option),NULL,0,NULL))
            sos::Throw<sos::Exception>("Failed to parse command line arguments.");
        
        if (type != NULL)
            if (_stricmp(type, "Pinned") == 0)
                mType = HNDTYPE_PINNED;
            else if (_stricmp(type, "RefCounted") == 0)
                mType = HNDTYPE_REFCOUNTED;
            else if (_stricmp(type, "WeakShort") == 0)
                mType = HNDTYPE_WEAK_SHORT;
            else if (_stricmp(type, "WeakLong") == 0)
                mType = HNDTYPE_WEAK_LONG;
            else if (_stricmp(type, "Strong") == 0)
                mType = HNDTYPE_STRONG;
            else if (_stricmp(type, "Variable") == 0)
                mType = HNDTYPE_VARIABLE;
            else if (_stricmp(type, "AsyncPinned") == 0)
                mType = HNDTYPE_ASYNCPINNED;
            else if (_stricmp(type, "SizedRef") == 0)
                mType = HNDTYPE_SIZEDREF;
            else if (_stricmp(type, "Dependent") == 0)
                mType = HNDTYPE_DEPENDENT;
            else if (_stricmp(type, "WeakWinRT") == 0)
                mType = HNDTYPE_WEAK_WINRT;
            else
                sos::Throw<sos::Exception>("Unknown handle type '%s'.", type.GetPtr());
    }
    
    void Run()
    {
        EnableDMLHolder dmlHolder(mDML);
        
        mOut.ReInit(6, POINTERSIZE_HEX, AlignRight);
        mOut.SetWidths(5, POINTERSIZE_HEX, 11, POINTERSIZE_HEX, 8, POINTERSIZE_HEX);
        mOut.SetColAlignment(1, AlignLeft);
        
        if (mHandleStat.Init(!mPerDomain) == FALSE)
            sos::Throw<sos::Exception>("Error getting per-appdomain handle information");
        
        if (!mStat)
            mOut.WriteRow("Handle", "Type", "Object", "Size", "Data", "Type");
            
        WalkHandles();
        
        for (int i=0; (i < mHandleStat.GetNumDomains()) && !IsInterrupt(); i++)
        {
            GCHandleStatistics *pStats = mHandleStat.GetStatistics(i);

            if (mPerDomain)
            {
                Print( "------------------------------------------------------------------------------\n");           
                Print("GC Handle Statistics for AppDomain ", AppDomainPtr(mHandleStat.GetDomain(i)));
            
                if (i == GCHandleStatsForDomains::SHARED_DOMAIN_INDEX)
                    Print(" (Shared Domain)\n");
                else if (i == GCHandleStatsForDomains::SYSTEM_DOMAIN_INDEX)
                    Print(" (System Domain)\n");
                else
                    Print("\n");
            }

            if (!mStat)
                Print("\n");
            PrintGCStat(&pStats->hs);
            
            // Don't print handle stats if the user has filtered by type.  All handles will be the same
            // type, and the total count will be displayed by PrintGCStat.
            if (mType == (unsigned int)~0)
            {
                Print("\n");
                PrintGCHandleStats(pStats);
            }
        }
    }

private:
    void WalkHandles()
    {
        ToRelease<ISOSHandleEnum> handles;
        if (FAILED(g_sos->GetHandleEnum(&handles)))
        {
            if (IsMiniDumpFile())
                sos::Throw<sos::Exception>("Unable to display GC handles.\nA minidump without full memory may not have this information.");
            else
                sos::Throw<sos::Exception>("Failed to walk the handle table.");
        }
      
        // GCC can't handle stacks which are too large.
#ifndef FEATURE_PAL
        SOSHandleData data[256];
#else
        SOSHandleData data[4];
#endif
        
        unsigned int fetched = 0;
        HRESULT hr = S_OK;
        do
        {
            if (FAILED(hr = handles->Next(_countof(data), data, &fetched)))
            {
                ExtOut("Error %x while walking the handle table.\n", hr);
                break;
            }
            
            WalkHandles(data, fetched);
        } while (_countof(data) == fetched);
    }
    
    void WalkHandles(SOSHandleData data[], unsigned int count)
    {
        for (unsigned int i = 0; i < count; ++i)
        {
            sos::CheckInterrupt();
        
            if (mType != (unsigned int)~0 && mType != data[i].Type)
                continue;
        
            GCHandleStatistics *pStats = mHandleStat.LookupStatistics(data[i].AppDomain);
            TADDR objAddr = 0;
            TADDR mtAddr = 0;
            size_t size = 0;
            const WCHAR *mtName = 0;
            const char *type = 0;
            
            if (FAILED(MOVE(objAddr, data[i].Handle)))
            {
                objAddr = 0;
                mtName = W("<error>");
            }
            else
            {
                sos::Object obj(TO_TADDR(objAddr));
                mtAddr = obj.GetMT();
                if (sos::MethodTable::IsFreeMT(mtAddr))
                {
                    mtName = W("<free>");
                }
                else if (!sos::MethodTable::IsValid(mtAddr))
                {
                    mtName = W("<error>");
                }
                else
                {
                    size = obj.GetSize();
                    if (mType == (unsigned int)~0 || mType == data[i].Type)
                        pStats->hs.Add(obj.GetMT(), (DWORD)size);
                }
            }
        
            switch(data[i].Type)
            {
                case HNDTYPE_PINNED:
                    type = "Pinned";
                    if (pStats) pStats->pinnedHandleCount++;
                    break;
                case HNDTYPE_REFCOUNTED:
                    type = "RefCounted";
                    if (pStats) pStats->refCntHandleCount++;
                    break;    
                case HNDTYPE_STRONG:
                    type = "Strong";
                    if (pStats) pStats->strongHandleCount++;
                    break;
                case HNDTYPE_WEAK_SHORT:
                    type = "WeakShort";
                    if (pStats) pStats->weakShortHandleCount++;
                    break;
                case HNDTYPE_WEAK_LONG:
                    type = "WeakLong";
                    if (pStats) pStats->weakLongHandleCount++;
                    break;
                case HNDTYPE_ASYNCPINNED:
                    type = "AsyncPinned";
                    if (pStats) pStats->asyncPinnedHandleCount++;
                    break;
                case HNDTYPE_VARIABLE:
                    type = "Variable";
                    if (pStats) pStats->variableCount++;
                    break;
                case HNDTYPE_SIZEDREF:
                    type = "SizedRef";
                    if (pStats) pStats->sizedRefCount++;
                    break;
                case HNDTYPE_DEPENDENT:
                    type = "Dependent";
                    if (pStats) pStats->dependentCount++;
                    break;
                case HNDTYPE_WEAK_WINRT:
                    type = "WeakWinRT";
                    if (pStats) pStats->weakWinRTHandleCount++;
                    break;
                default:
                    DebugBreak();
                    type = "Unknown";
                    pStats->unknownHandleCount++;
                    break;
            }
            
            if (type && !mStat)
            {
                sos::MethodTable mt = mtAddr;
                if (mtName == 0)
                    mtName = mt.GetName();
                
                if (data[i].Type == HNDTYPE_REFCOUNTED)
                    mOut.WriteRow(data[i].Handle, type, ObjectPtr(objAddr), Decimal(size), Decimal(data[i].RefCount), mtName);
                else if (data[i].Type == HNDTYPE_DEPENDENT)
                    mOut.WriteRow(data[i].Handle, type, ObjectPtr(objAddr), Decimal(size), ObjectPtr(data[i].Secondary), mtName);
                else if (data[i].Type == HNDTYPE_WEAK_WINRT)
                    mOut.WriteRow(data[i].Handle, type, ObjectPtr(objAddr), Decimal(size), Pointer(data[i].Secondary), mtName);
                else
                    mOut.WriteRow(data[i].Handle, type, ObjectPtr(objAddr), Decimal(size), "", mtName);
            }
        }
    }
    
    inline void PrintHandleRow(const char *text, int count)
    {
        if (count)
            mOut.WriteRow(text, Decimal(count));
    }
    
    void PrintGCHandleStats(GCHandleStatistics *pStats)
    {
        Print("Handles:\n");
        mOut.ReInit(2, 21, AlignLeft, 4);
        
        PrintHandleRow("Strong Handles:", pStats->strongHandleCount);
        PrintHandleRow("Pinned Handles:", pStats->pinnedHandleCount);
        PrintHandleRow("Async Pinned Handles:", pStats->asyncPinnedHandleCount);
        PrintHandleRow("Ref Count Handles:", pStats->refCntHandleCount);
        PrintHandleRow("Weak Long Handles:", pStats->weakLongHandleCount);
        PrintHandleRow("Weak Short Handles:", pStats->weakShortHandleCount);
        PrintHandleRow("Weak WinRT Handles:", pStats->weakWinRTHandleCount);
        PrintHandleRow("Variable Handles:", pStats->variableCount);
        PrintHandleRow("SizedRef Handles:", pStats->sizedRefCount);
        PrintHandleRow("Dependent Handles:", pStats->dependentCount);
        PrintHandleRow("Other Handles:", pStats->unknownHandleCount);
    }
    
private:
    BOOL mPerDomain, mStat, mDML;
    unsigned int mType;
    TableOutput mOut;
    GCHandleStatsForDomains mHandleStat;
};

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function dumps GC Handle statistics        *
*                                                                      *
\**********************************************************************/
DECLARE_API(GCHandles)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    try
    {
        GCHandlesImpl gchandles(args);
        gchandles.Run();
    }
    catch(const sos::Exception &e)
    {
        Print(e.what());
    }

    return Status;
}

BOOL derivedFrom(CLRDATA_ADDRESS mtObj, __in_z LPWSTR baseString)
{
    // We want to follow back until we get the mt for System.Exception
    DacpMethodTableData dmtd;
    CLRDATA_ADDRESS walkMT = mtObj;
    while(walkMT != NULL)
    {
        if (dmtd.Request(g_sos, walkMT) != S_OK)
        {
            break;            
        }
        NameForMT_s (TO_TADDR(walkMT), g_mdName, mdNameLen);                
        if (_wcscmp (baseString, g_mdName) == 0)
        {
            return TRUE;
        }
        walkMT = dmtd.ParentMethodTable;
    }
    return FALSE;
}

// This is an experimental and undocumented SOS API that attempts to step through code
// stopping once jitted code is reached. It currently has some issues - it can take arbitrarily long
// to reach jitted code and canceling it is terrible. At best it doesn't cancel, at worst it
// kills the debugger. IsInterrupt() doesn't work nearly as nicely as one would hope :/
#ifndef FEATURE_PAL
DECLARE_API(TraceToCode)
{
    INIT_API_NOEE();

    static ULONG64 g_clrBaseAddr = 0;


    while(true)
    {
        if (IsInterrupt())
        {
            ExtOut("Interrupted\n");
            return S_FALSE;
        }

        ULONG64 Offset;
        g_ExtRegisters->GetInstructionOffset(&Offset);

        DWORD codeType = 0;
        ULONG64 base = 0;
        CLRDATA_ADDRESS cdaStart = TO_CDADDR(Offset);
        DacpMethodDescData MethodDescData;
        if(g_ExtSymbols->GetModuleByOffset(Offset, 0, NULL, &base) == S_OK)
        {
            if(g_clrBaseAddr == 0)
            {
                g_ExtSymbols->GetModuleByModuleName (MAIN_CLR_MODULE_NAME_A,0,NULL,
                    &g_clrBaseAddr);
            }
            if(g_clrBaseAddr == base)
            {
                ExtOut("Compiled code in CLR\n");
                codeType = 4;
            }
            else
            {
                ExtOut("Compiled code in module @ 0x%I64x\n", base);
                codeType = 8;
            }
        }
        else if (g_sos != NULL || LoadClrDebugDll()==S_OK)
        {
            CLRDATA_ADDRESS addr;
            if(g_sos->GetMethodDescPtrFromIP(cdaStart, &addr) == S_OK)
            {
                WCHAR wszNameBuffer[1024]; // should be large enough

                // get the MethodDesc name
                if ((g_sos->GetMethodDescName(addr, 1024, wszNameBuffer, NULL) == S_OK) &&
                    _wcsncmp(W("DomainBoundILStubClass"), wszNameBuffer, 22)==0)
                {
                    ExtOut("ILStub\n");
                    codeType = 2;
                }
                else
                {
                    ExtOut("Jitted code\n");
                    codeType = 1;
                }
            }
            else
            {
                ExtOut("Not compiled or jitted, assuming stub\n");
                codeType = 16;
            }
        }
        else
        {
            // not compiled but CLR isn't loaded... some other code generator?
            return E_FAIL;
        }

        if(codeType == 1)
        {
            return S_OK;
        }
        else
        {
            Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, "thr; .echo wait" ,0);
            if (FAILED(Status))
            {
                ExtOut("Error tracing instruction\n");
                return Status;
            }
        }
    }

    return Status;

}
#endif // FEATURE_PAL

// This is an experimental and undocumented API that sets a debugger pseudo-register based
// on the type of code at the given IP. It can be used in scripts to keep stepping until certain
// kinds of code have been reached. Presumbably its slower than !TraceToCode but at least it
// cancels much better
#ifndef FEATURE_PAL
DECLARE_API(GetCodeTypeFlags)
{
    INIT_API();   
    

    char buffer[100+mdNameLen];
    size_t ip;
    StringHolder PReg;
    
    CMDValue arg[] = {
        // vptr, type
        {&ip, COSIZE_T},
        {&PReg.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    size_t preg = 1; // by default
    if (nArg == 2)
    {
        preg = GetExpression(PReg.data);
        if (preg > 19)
        {
            ExtOut("Pseudo-register number must be between 0 and 19\n");
            return Status;
        }
    }        

    sprintf_s(buffer,_countof (buffer),
        "r$t%d=0",
        preg);
    Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer ,0);
    if (FAILED(Status))
    {
        ExtOut("Error initialized register $t%d to zero\n", preg);
        return Status;
    }    

    ULONG64 base = 0;
    CLRDATA_ADDRESS cdaStart = TO_CDADDR(ip);
    DWORD codeType = 0;
    CLRDATA_ADDRESS addr;
    if(g_sos->GetMethodDescPtrFromIP(cdaStart, &addr) == S_OK)
    {
        WCHAR wszNameBuffer[1024]; // should be large enough

        // get the MethodDesc name
        if (g_sos->GetMethodDescName(addr, 1024, wszNameBuffer, NULL) == S_OK &&
            _wcsncmp(W("DomainBoundILStubClass"), wszNameBuffer, 22)==0)
        {
            ExtOut("ILStub\n");
            codeType = 2;
        }
        else
        {
            ExtOut("Jitted code");
            codeType = 1;
        }
    }
    else if(g_ExtSymbols->GetModuleByOffset (ip, 0, NULL, &base) == S_OK)
    {
        ULONG64 clrBaseAddr = 0;
        if(SUCCEEDED(g_ExtSymbols->GetModuleByModuleName (MAIN_CLR_MODULE_NAME_A,0,NULL, &clrBaseAddr)) && base==clrBaseAddr)
        {
            ExtOut("Compiled code in CLR");
            codeType = 4;
        }
        else
        {
            ExtOut("Compiled code in module @ 0x%I64x\n", base);
            codeType = 8;
        }
    }
    else
    {
        ExtOut("Not compiled or jitted, assuming stub\n");
        codeType = 16;
    }

    sprintf_s(buffer,_countof (buffer),
        "r$t%d=%x",
        preg, codeType);
    Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);
    if (FAILED(Status))
    {
        ExtOut("Error setting register $t%d\n", preg);
        return Status;
    }  
    return Status;

}
#endif // FEATURE_PAL

DECLARE_API(StopOnException)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    

    char buffer[100+mdNameLen];

    BOOL fDerived = FALSE;
    BOOL fCreate1 = FALSE;    
    BOOL fCreate2 = FALSE;    

    CMDOption option[] = {
        // name, vptr, type, hasValue
        {"-derived", &fDerived, COBOOL, FALSE}, // catch derived exceptions
        {"-create", &fCreate1, COBOOL, FALSE}, // create 1st chance handler
        {"-create2", &fCreate2, COBOOL, FALSE}, // create 2nd chance handler
    };

    StringHolder TypeName,PReg;
    
    CMDValue arg[] = {
        // vptr, type
        {&TypeName.data, COSTRING},
        {&PReg.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (IsDumpFile())
    {
        ExtOut("Live debugging session required\n");
        return Status;
    }
    if (nArg < 1 || nArg > 2)
    {
        ExtOut("usage: StopOnException [-derived] [-create | -create2] <type name>\n");
        ExtOut("                       [<pseudo-register number for result>]\n");            
        ExtOut("ex:    StopOnException -create System.OutOfMemoryException 1\n");
        return Status;
    }

    size_t preg = 1; // by default
    if (nArg == 2)
    {
        preg = GetExpression(PReg.data);
        if (preg > 19)
        {
            ExtOut("Pseudo-register number must be between 0 and 19\n");
            return Status;
        }
    }        

    sprintf_s(buffer,_countof (buffer),
        "r$t%d=0",
        preg);
    Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);
    if (FAILED(Status))
    {
        ExtOut("Error initialized register $t%d to zero\n", preg);
        return Status;
    }    
    
    if (fCreate1 || fCreate2)
    {            
        sprintf_s(buffer,_countof (buffer),
            "sxe %s \"!soe %s %s %d;.if(@$t%d==0) {g} .else {.echo '%s hit'}\" %x",
            fCreate1 ? "-c" : "-c2",
            fDerived ? "-derived" : "",
            TypeName.data,
            preg,
            preg,
            TypeName.data,
            EXCEPTION_COMPLUS
            );
            
        Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);        
        if (FAILED(Status))
        {
            ExtOut("Error setting breakpoint: %s\n", buffer);
            return Status;
        }        

        ExtOut("Breakpoint set\n");
        return Status;
    }    

    // Find the last thrown exception on this thread.
    // Does it match? If so, set the register.
    CLRDATA_ADDRESS threadAddr = GetCurrentManagedThread();
    DacpThreadData Thread;
    
    if ((threadAddr == NULL) || (Thread.Request(g_sos, threadAddr) != S_OK))
    {
        ExtOut("The current thread is unmanaged\n");
        return Status;
    }

    TADDR taLTOH;
    if (!SafeReadMemory(Thread.lastThrownObjectHandle,
                        &taLTOH,
                        sizeof(taLTOH), NULL))
    {
        ExtOut("There is no current managed exception on this thread\n");
        return Status;
    }
    
    if (taLTOH)
    {
        LPWSTR typeNameWide = (LPWSTR)alloca(mdNameLen * sizeof(WCHAR));
        MultiByteToWideChar(CP_ACP,0,TypeName.data,-1,typeNameWide,mdNameLen);
        
        TADDR taMT;
        if (SafeReadMemory(taLTOH, &taMT, sizeof(taMT), NULL))
        {            
            NameForMT_s (taMT, g_mdName, mdNameLen);
            if ((_wcscmp(g_mdName,typeNameWide) == 0) ||
                (fDerived && derivedFrom(taMT, typeNameWide)))
            {
                sprintf_s(buffer,_countof (buffer),
                    "r$t%d=1",
                    preg);
                Status = g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, buffer, 0);
                if (FAILED(Status))
                {
                    ExtOut("Failed to execute the following command: %s\n", buffer);
                }
            }
        }
    }

    return Status;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function finds the size of an object or all roots.           *  
*                                                                      *
\**********************************************************************/
DECLARE_API(ObjSize)
{
#ifndef FEATURE_PAL
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    
    
    BOOL dml = FALSE;
    StringHolder str_Object;    


    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&str_Object.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    TADDR obj = GetExpression(str_Object.data);

    GCRootImpl gcroot;
    if (obj == 0)
    {
        gcroot.ObjSize();
    }
    else
    {
        if(!sos::IsObject(obj))
        {
            ExtOut("%p is not a valid object.\n", SOS_PTR(obj));
            return Status;
        }

        size_t size = gcroot.ObjSize(obj);
        TADDR mt = 0;
        MOVE(mt, obj);
        sos::MethodTable methodTable = mt;
        ExtOut("sizeof(%p) = %d (0x%x) bytes (%S)\n", SOS_PTR(obj), size, size, methodTable.GetName());
    }
    return Status;
#else
    return E_NOTIMPL;
#endif

}

#ifndef FEATURE_PAL
// For FEATURE_PAL, MEMORY_BASIC_INFORMATION64 doesn't exist yet. TODO?
DECLARE_API(GCHandleLeaks)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    ExtOut("-------------------------------------------------------------------------------\n");
    ExtOut("GCHandleLeaks will report any GCHandles that couldn't be found in memory.      \n");
    ExtOut("Strong and Pinned GCHandles are reported at this time. You can safely abort the\n");
    ExtOut("memory scan with Control-C or Control-Break.                                   \n");
    ExtOut("-------------------------------------------------------------------------------\n");
    
    static DWORD_PTR array[2000];
    UINT i;
    BOOL dml = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"/d", &dml, COBOOL, FALSE},
    };

    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL)) 
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    
    UINT iFinal = FindAllPinnedAndStrong(array,sizeof(array)/sizeof(DWORD_PTR));
    ExtOut("Found %d handles:\n",iFinal);
    for (i=1;i<=iFinal;i++)
    {
        ExtOut("%p\t", SOS_PTR(array[i-1]));
        if ((i % 4) == 0)
            ExtOut("\n");
    }

    ExtOut("\nSearching memory\n");
    // Now search memory for this:
    DWORD_PTR buffer[1024];
    ULONG64 memCur = 0x0;
    BOOL bAbort = FALSE;

    //find out memory used by stress log
    StressLogMem stressLog;
    CLRDATA_ADDRESS StressLogAddress = NULL;
    if (LoadClrDebugDll() != S_OK)
    {
        // Try to find stress log symbols
        DWORD_PTR dwAddr = GetValueFromExpression(MAIN_CLR_MODULE_NAME_A "!StressLog::theLog");
        StressLogAddress = dwAddr;        
        g_bDacBroken = TRUE;
    }
    else
    {
        if (g_sos->GetStressLogAddress(&StressLogAddress) != S_OK)
        {
            ExtOut("Unable to find stress log via DAC\n");
        }
        g_bDacBroken = FALSE;
    }

    if (stressLog.Init (StressLogAddress, g_ExtData))
    {
        ExtOut("Reference found in stress log will be ignored\n");
    }
    else
    {
        ExtOut("Failed to read whole or part of stress log, some references may come from stress log\n");
    }
    
    
    while (!bAbort)
    {
        NTSTATUS status;
        MEMORY_BASIC_INFORMATION64 memInfo;

        status = g_ExtData2->QueryVirtual(UL64_TO_CDA(memCur), &memInfo);
                
        if( !NT_SUCCESS(status) ) 
        {            
            break;
        }

        if (memInfo.State == MEM_COMMIT)
        {            
            for (ULONG64 memIter = memCur; memIter < (memCur + memInfo.RegionSize); memIter+=sizeof(buffer))
            {
                if (IsInterrupt())
                {
                    ExtOut("Quitting at %p due to user abort\n", SOS_PTR(memIter));
                    bAbort = TRUE;
                    break;
                }

                if ((memIter % 0x10000000)==0x0)
                {
                    ExtOut("Searching %p...\n", SOS_PTR(memIter));
                }
                
                ULONG size = 0;
                HRESULT ret;
                ret = g_ExtData->ReadVirtual(UL64_TO_CDA(memIter), buffer, sizeof(buffer), &size);
                if (ret == S_OK)
                {
                    for (UINT x=0;x<1024;x++)
                    {            
                        DWORD_PTR value = buffer[x];
                        // We don't care about the low bit. Also, the GCHandle class turns on the
                        // low bit for pinned handles, so without the statement below, we wouldn't
                        // notice pinned handles.
                        value = value & ~1; 
                        for (i=0;i<iFinal;i++)
                        {
                            ULONG64 addrInDebugee = (ULONG64)memIter+(x*sizeof(DWORD_PTR));
                            if ((array[i] & ~1) == value)
                            {
                                if (stressLog.IsInStressLog (addrInDebugee))
                                {
                                    ExtOut("Found %p in stress log at location %p, reference not counted\n", SOS_PTR(value), addrInDebugee);
                                }
                                else
                                {
                                    ExtOut("Found %p at location %p\n", SOS_PTR(value), addrInDebugee);
                                    array[i] |= 0x1;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (size > 0)
                    {
                        ExtOut("only read %x bytes at %p\n", size, SOS_PTR(memIter));
                    }
                }
            }
        }
        
        memCur += memInfo.RegionSize;
    }

    int numNotFound = 0;
    for (i=0;i<iFinal;i++)
    {
        if ((array[i] & 0x1) == 0)
        {
            numNotFound++;
            // ExtOut("WARNING: %p not found\n", SOS_PTR(array[i]));
        }
    }

    if (numNotFound > 0)
    {
        ExtOut("------------------------------------------------------------------------------\n");    
        ExtOut("Some handles were not found. If the number of not-found handles grows over the\n");
        ExtOut("lifetime of your application, you may have a GCHandle leak. This will cause   \n");
        ExtOut("the GC Heap to grow larger as objects are being kept alive, referenced only   \n");
        ExtOut("by the orphaned handle. If the number doesn't grow over time, note that there \n");
        ExtOut("may be some noise in this output, as an unmanaged application may be storing  \n");
        ExtOut("the handle in a non-standard way, perhaps with some bits flipped. The memory  \n");
        ExtOut("scan wouldn't be able to find those.                                          \n");
        ExtOut("------------------------------------------------------------------------------\n");    

        ExtOut("Didn't find %d handles:\n", numNotFound);
        int numPrinted=0;
        for (i=0;i<iFinal;i++)
        {
            if ((array[i] & 0x1) == 0)
            {
                numPrinted++;
                ExtOut("%p\t", SOS_PTR(array[i]));
                if ((numPrinted % 4) == 0)
                    ExtOut("\n");
            }
        }   
        ExtOut("\n");
    }
    else
    {       
        ExtOut("------------------------------------------------------------------------------\n");    
        ExtOut("All handles found");
        if (bAbort)
            ExtOut(" even though you aborted.\n");
        else
            ExtOut(".\n");        
        ExtOut("A leak may still exist because in a general scan of process memory SOS can't  \n");
        ExtOut("differentiate between garbage and valid structures, so you may have false     \n");
        ExtOut("positives. If you still suspect a leak, use this function over time to        \n");
        ExtOut("identify a possible trend.                                                    \n");
        ExtOut("------------------------------------------------------------------------------\n");    
    }
    
    return Status;
}
#endif // FEATURE_PAL

#endif // FEATURE_PAL

class ClrStackImplWithICorDebug
{
private:
    static HRESULT DereferenceAndUnboxValue(ICorDebugValue * pValue, ICorDebugValue** ppOutputValue, BOOL * pIsNull = NULL)
    {
        HRESULT Status = S_OK;
        *ppOutputValue = NULL;
        if(pIsNull != NULL) *pIsNull = FALSE;

        ToRelease<ICorDebugReferenceValue> pReferenceValue;
        Status = pValue->QueryInterface(IID_ICorDebugReferenceValue, (LPVOID*) &pReferenceValue);
        if (SUCCEEDED(Status))
        {
            BOOL isNull = FALSE;
            IfFailRet(pReferenceValue->IsNull(&isNull));
            if(!isNull)
            {
                ToRelease<ICorDebugValue> pDereferencedValue;
                IfFailRet(pReferenceValue->Dereference(&pDereferencedValue));
                return DereferenceAndUnboxValue(pDereferencedValue, ppOutputValue);
            }
            else
            {
                if(pIsNull != NULL) *pIsNull = TRUE;
                *ppOutputValue = pValue;
                (*ppOutputValue)->AddRef();
                return S_OK;
            }
        }

        ToRelease<ICorDebugBoxValue> pBoxedValue;
        Status = pValue->QueryInterface(IID_ICorDebugBoxValue, (LPVOID*) &pBoxedValue);
        if (SUCCEEDED(Status))
        {
            ToRelease<ICorDebugObjectValue> pUnboxedValue;
            IfFailRet(pBoxedValue->GetObject(&pUnboxedValue));
            return DereferenceAndUnboxValue(pUnboxedValue, ppOutputValue);
        }
        *ppOutputValue = pValue;
        (*ppOutputValue)->AddRef();
        return S_OK;
    }

    static BOOL ShouldExpandVariable(__in_z WCHAR* varToExpand, __in_z WCHAR* currentExpansion)
    {
        if(currentExpansion == NULL || varToExpand == NULL) return FALSE;

        size_t varToExpandLen = _wcslen(varToExpand);
        size_t currentExpansionLen = _wcslen(currentExpansion);
        if(currentExpansionLen > varToExpandLen) return FALSE;
        if(currentExpansionLen < varToExpandLen && varToExpand[currentExpansionLen] != L'.') return FALSE;
        if(_wcsncmp(currentExpansion, varToExpand, currentExpansionLen) != 0) return FALSE;

        return TRUE;
    }

    static BOOL IsEnum(ICorDebugValue * pInputValue)
    {
        ToRelease<ICorDebugValue> pValue;
        if(FAILED(DereferenceAndUnboxValue(pInputValue, &pValue, NULL))) return FALSE;

        WCHAR baseTypeName[mdNameLen];
        ToRelease<ICorDebugValue2> pValue2;
        ToRelease<ICorDebugType> pType;
        ToRelease<ICorDebugType> pBaseType;

        if(FAILED(pValue->QueryInterface(IID_ICorDebugValue2, (LPVOID *) &pValue2))) return FALSE;
        if(FAILED(pValue2->GetExactType(&pType))) return FALSE;
        if(FAILED(pType->GetBase(&pBaseType)) || pBaseType == NULL) return FALSE;
        if(FAILED(GetTypeOfValue(pBaseType, baseTypeName, mdNameLen))) return  FALSE;

        return (_wcsncmp(baseTypeName, W("System.Enum"), 11) == 0);
    }

    static HRESULT AddGenericArgs(ICorDebugType * pType, __inout_ecount(typeNameLen) WCHAR* typeName, ULONG typeNameLen)
    {
        bool isFirst = true;
        ToRelease<ICorDebugTypeEnum> pTypeEnum;
        if(SUCCEEDED(pType->EnumerateTypeParameters(&pTypeEnum)))
        {
            ULONG numTypes = 0;
            ToRelease<ICorDebugType> pCurrentTypeParam;
            
            while(SUCCEEDED(pTypeEnum->Next(1, &pCurrentTypeParam, &numTypes)))
            {
                if(numTypes == 0) break;

                if(isFirst)
                {
                    isFirst = false;
                    wcsncat_s(typeName, typeNameLen, W("&lt;"), typeNameLen);
                }
                else wcsncat_s(typeName, typeNameLen, W(","), typeNameLen);

                WCHAR typeParamName[mdNameLen];
                typeParamName[0] = L'\0';
                GetTypeOfValue(pCurrentTypeParam, typeParamName, mdNameLen);
                wcsncat_s(typeName, typeNameLen, typeParamName, typeNameLen);
            }
            if(!isFirst)
                wcsncat_s(typeName, typeNameLen, W("&gt;"), typeNameLen);
        }

        return S_OK;
    }

    static HRESULT GetTypeOfValue(ICorDebugType * pType, __inout_ecount(typeNameLen) WCHAR* typeName, ULONG typeNameLen)
    {
        HRESULT Status = S_OK;

        CorElementType corElemType;
        IfFailRet(pType->GetType(&corElemType));

        switch (corElemType)
        {
        //List of unsupported CorElementTypes:
        //ELEMENT_TYPE_END            = 0x0,
        //ELEMENT_TYPE_VAR            = 0x13,     // a class type variable VAR <U1>
        //ELEMENT_TYPE_GENERICINST    = 0x15,     // GENERICINST <generic type> <argCnt> <arg1> ... <argn>
        //ELEMENT_TYPE_TYPEDBYREF     = 0x16,     // TYPEDREF  (it takes no args) a typed referece to some other type
        //ELEMENT_TYPE_MVAR           = 0x1e,     // a method type variable MVAR <U1>
        //ELEMENT_TYPE_CMOD_REQD      = 0x1F,     // required C modifier : E_T_CMOD_REQD <mdTypeRef/mdTypeDef>
        //ELEMENT_TYPE_CMOD_OPT       = 0x20,     // optional C modifier : E_T_CMOD_OPT <mdTypeRef/mdTypeDef>
        //ELEMENT_TYPE_INTERNAL       = 0x21,     // INTERNAL <typehandle>
        //ELEMENT_TYPE_MAX            = 0x22,     // first invalid element type
        //ELEMENT_TYPE_MODIFIER       = 0x40,
        //ELEMENT_TYPE_SENTINEL       = 0x01 | ELEMENT_TYPE_MODIFIER, // sentinel for varargs
        //ELEMENT_TYPE_PINNED         = 0x05 | ELEMENT_TYPE_MODIFIER,
        //ELEMENT_TYPE_R4_HFA         = 0x06 | ELEMENT_TYPE_MODIFIER, // used only internally for R4 HFA types
        //ELEMENT_TYPE_R8_HFA         = 0x07 | ELEMENT_TYPE_MODIFIER, // used only internally for R8 HFA types
        default:
            swprintf_s(typeName, typeNameLen, W("(Unhandled CorElementType: 0x%x)\0"), corElemType);
            break;

        case ELEMENT_TYPE_VALUETYPE:
        case ELEMENT_TYPE_CLASS:
            {
                //Defaults in case we fail...
                if(corElemType == ELEMENT_TYPE_VALUETYPE) swprintf_s(typeName, typeNameLen, W("struct\0"));
                else swprintf_s(typeName, typeNameLen, W("class\0"));

                mdTypeDef typeDef;
                ToRelease<ICorDebugClass> pClass;
                if(SUCCEEDED(pType->GetClass(&pClass)) && SUCCEEDED(pClass->GetToken(&typeDef)))
                {
                    ToRelease<ICorDebugModule> pModule;
                    IfFailRet(pClass->GetModule(&pModule));

                    ToRelease<IUnknown> pMDUnknown;
                    ToRelease<IMetaDataImport> pMD;
                    IfFailRet(pModule->GetMetaDataInterface(IID_IMetaDataImport, &pMDUnknown));
                    IfFailRet(pMDUnknown->QueryInterface(IID_IMetaDataImport, (LPVOID*) &pMD));

                    if(SUCCEEDED(NameForToken_s(TokenFromRid(typeDef, mdtTypeDef), pMD, g_mdName, mdNameLen, false)))
                        swprintf_s(typeName, typeNameLen, W("%s\0"), g_mdName);
                }
                AddGenericArgs(pType, typeName, typeNameLen);
            }
            break;
        case ELEMENT_TYPE_VOID:
            swprintf_s(typeName, typeNameLen, W("void\0"));
            break;
        case ELEMENT_TYPE_BOOLEAN:
            swprintf_s(typeName, typeNameLen, W("bool\0"));
            break;
        case ELEMENT_TYPE_CHAR:
            swprintf_s(typeName, typeNameLen, W("char\0"));
            break;
        case ELEMENT_TYPE_I1:
            swprintf_s(typeName, typeNameLen, W("signed byte\0"));
            break;
        case ELEMENT_TYPE_U1:
            swprintf_s(typeName, typeNameLen, W("byte\0"));
            break;
        case ELEMENT_TYPE_I2:
            swprintf_s(typeName, typeNameLen, W("short\0"));
            break;
        case ELEMENT_TYPE_U2:
            swprintf_s(typeName, typeNameLen, W("unsigned short\0"));
            break;    
        case ELEMENT_TYPE_I4:
            swprintf_s(typeName, typeNameLen, W("int\0"));
            break;
        case ELEMENT_TYPE_U4:
            swprintf_s(typeName, typeNameLen, W("unsigned int\0"));
            break;
        case ELEMENT_TYPE_I8:
            swprintf_s(typeName, typeNameLen, W("long\0"));
            break;
        case ELEMENT_TYPE_U8:
            swprintf_s(typeName, typeNameLen, W("unsigned long\0"));
            break;
        case ELEMENT_TYPE_R4:
            swprintf_s(typeName, typeNameLen, W("float\0"));
            break;
        case ELEMENT_TYPE_R8:
            swprintf_s(typeName, typeNameLen, W("double\0"));
            break;
        case ELEMENT_TYPE_OBJECT:
            swprintf_s(typeName, typeNameLen, W("object\0"));
            break;
        case ELEMENT_TYPE_STRING:
            swprintf_s(typeName, typeNameLen, W("string\0"));
            break;
        case ELEMENT_TYPE_I:
            swprintf_s(typeName, typeNameLen, W("IntPtr\0"));
            break;
        case ELEMENT_TYPE_U:
            swprintf_s(typeName, typeNameLen, W("UIntPtr\0"));
            break;
        case ELEMENT_TYPE_SZARRAY:
        case ELEMENT_TYPE_ARRAY:
        case ELEMENT_TYPE_BYREF:
        case ELEMENT_TYPE_PTR:
            {
                ToRelease<ICorDebugType> pFirstParameter;
                if(SUCCEEDED(pType->GetFirstTypeParameter(&pFirstParameter)))
                    GetTypeOfValue(pFirstParameter, typeName, typeNameLen);
                else
                    swprintf_s(typeName, typeNameLen, W("<unknown>\0"));

                switch(corElemType)
                {
                case ELEMENT_TYPE_SZARRAY: 
                    wcsncat_s(typeName, typeNameLen, W("[]\0"), typeNameLen);
                    return S_OK;
                case ELEMENT_TYPE_ARRAY:
                    {
                        ULONG32 rank = 0;
                        pType->GetRank(&rank);
                        wcsncat_s(typeName, typeNameLen, W("["), typeNameLen);
                        for(ULONG32 i = 0; i < rank - 1; i++)
                        {
                            // 
                            wcsncat_s(typeName, typeNameLen, W(","), typeNameLen);
                        }
                        wcsncat_s(typeName, typeNameLen, W("]\0"), typeNameLen);
                    }
                    return S_OK;
                case ELEMENT_TYPE_BYREF:   
                    wcsncat_s(typeName, typeNameLen, W("&\0"), typeNameLen);
                    return S_OK;
                case ELEMENT_TYPE_PTR:     
                    wcsncat_s(typeName, typeNameLen, W("*\0"), typeNameLen);
                    return S_OK;
                default:
                    // note we can never reach here as this is a nested switch
                    // and corElemType can only be one of the values above
                    break;
                }
            }
            break;
        case ELEMENT_TYPE_FNPTR:
            swprintf_s(typeName, typeNameLen, W("*(...)\0"));
            break;
        case ELEMENT_TYPE_TYPEDBYREF:
            swprintf_s(typeName, typeNameLen, W("typedbyref\0"));
            break;
        }
        return S_OK;
    }

    static HRESULT GetTypeOfValue(ICorDebugValue * pValue, __inout_ecount(typeNameLen) WCHAR* typeName, ULONG typeNameLen)
    {
        HRESULT Status = S_OK;

        CorElementType corElemType;
        IfFailRet(pValue->GetType(&corElemType));

        ToRelease<ICorDebugType> pType;
        ToRelease<ICorDebugValue2> pValue2;
        if(SUCCEEDED(pValue->QueryInterface(IID_ICorDebugValue2, (void**) &pValue2)) && SUCCEEDED(pValue2->GetExactType(&pType)))
            return GetTypeOfValue(pType, typeName, typeNameLen);
        else
            swprintf_s(typeName, typeNameLen, W("<unknown>\0"));

        return S_OK;
    }

    static HRESULT PrintEnumValue(ICorDebugValue* pInputValue, BYTE* enumValue)
    {
        HRESULT Status = S_OK;

        ToRelease<ICorDebugValue> pValue;
        IfFailRet(DereferenceAndUnboxValue(pInputValue, &pValue, NULL));

        mdTypeDef currentTypeDef;
        ToRelease<ICorDebugClass> pClass;
        ToRelease<ICorDebugValue2> pValue2;
        ToRelease<ICorDebugType> pType;
        ToRelease<ICorDebugModule> pModule;
        IfFailRet(pValue->QueryInterface(IID_ICorDebugValue2, (LPVOID *) &pValue2));
        IfFailRet(pValue2->GetExactType(&pType));
        IfFailRet(pType->GetClass(&pClass));
        IfFailRet(pClass->GetModule(&pModule));
        IfFailRet(pClass->GetToken(&currentTypeDef));

        ToRelease<IUnknown> pMDUnknown;
        ToRelease<IMetaDataImport> pMD;
        IfFailRet(pModule->GetMetaDataInterface(IID_IMetaDataImport, &pMDUnknown));
        IfFailRet(pMDUnknown->QueryInterface(IID_IMetaDataImport, (LPVOID*) &pMD));


        //First, we need to figure out the underlying enum type so that we can correctly type cast the raw values of each enum constant
        //We get that from the non-static field of the enum variable (I think the field is called __value or something similar)
        ULONG numFields = 0;
        HCORENUM fEnum = NULL;
        mdFieldDef fieldDef;
        CorElementType enumUnderlyingType = ELEMENT_TYPE_END;
        while(SUCCEEDED(pMD->EnumFields(&fEnum, currentTypeDef, &fieldDef, 1, &numFields)) && numFields != 0)
        {
            DWORD             fieldAttr = 0;
            PCCOR_SIGNATURE   pSignatureBlob = NULL;
            ULONG             sigBlobLength = 0;
            if(SUCCEEDED(pMD->GetFieldProps(fieldDef, NULL, NULL, 0, NULL, &fieldAttr, &pSignatureBlob, &sigBlobLength, NULL, NULL, NULL)))
            {
                if((fieldAttr & fdStatic) == 0)
                {
                    CorSigUncompressCallingConv(pSignatureBlob);
                    enumUnderlyingType = CorSigUncompressElementType(pSignatureBlob);
                    break;
                }
            }
        }
        pMD->CloseEnum(fEnum);


        //Now that we know the underlying enum type, let's decode the enum variable into OR-ed, human readable enum contants
        fEnum = NULL;
        bool isFirst = true;
        ULONG64 remainingValue = *((ULONG64*)enumValue);
        while(SUCCEEDED(pMD->EnumFields(&fEnum, currentTypeDef, &fieldDef, 1, &numFields)) && numFields != 0)
        {
            ULONG             nameLen = 0;
            DWORD             fieldAttr = 0;
            WCHAR             mdName[mdNameLen];
            WCHAR             typeName[mdNameLen];
            UVCP_CONSTANT     pRawValue = NULL;
            ULONG             rawValueLength = 0;
            if(SUCCEEDED(pMD->GetFieldProps(fieldDef, NULL, mdName, mdNameLen, &nameLen, &fieldAttr, NULL, NULL, NULL, &pRawValue, &rawValueLength)))
            {
                DWORD enumValueRequiredAttributes = fdPublic | fdStatic | fdLiteral | fdHasDefault;
                if((fieldAttr & enumValueRequiredAttributes) != enumValueRequiredAttributes)
                    continue;

                ULONG64 currentConstValue = 0;
                switch (enumUnderlyingType)
                {
                    case ELEMENT_TYPE_CHAR:
                    case ELEMENT_TYPE_I1:
                        currentConstValue = (ULONG64)(*((CHAR*)pRawValue));
                        break;
                    case ELEMENT_TYPE_U1:
                        currentConstValue = (ULONG64)(*((BYTE*)pRawValue));
                        break;
                    case ELEMENT_TYPE_I2:
                        currentConstValue = (ULONG64)(*((SHORT*)pRawValue));
                        break;
                    case ELEMENT_TYPE_U2:
                        currentConstValue = (ULONG64)(*((USHORT*)pRawValue));
                        break;
                    case ELEMENT_TYPE_I4:
                        currentConstValue = (ULONG64)(*((INT32*)pRawValue));
                        break;
                    case ELEMENT_TYPE_U4:
                        currentConstValue = (ULONG64)(*((UINT32*)pRawValue));
                        break;
                    case ELEMENT_TYPE_I8:
                        currentConstValue = (ULONG64)(*((LONG*)pRawValue));
                        break;
                    case ELEMENT_TYPE_U8:
                        currentConstValue = (ULONG64)(*((ULONG*)pRawValue));
                        break;
                    case ELEMENT_TYPE_I:
                        currentConstValue = (ULONG64)(*((int*)pRawValue));
                        break;
                    case ELEMENT_TYPE_U:
                    case ELEMENT_TYPE_R4:
                    case ELEMENT_TYPE_R8:
                    // Technically U and the floating-point ones are options in the CLI, but not in the CLS or C#, so these are NYI
                    default:
                        currentConstValue = 0;
                }

                if((currentConstValue == remainingValue) || ((currentConstValue != 0) && ((currentConstValue & remainingValue) == currentConstValue)))
                {
                    remainingValue &= ~currentConstValue;
                    if(isFirst)
                    {
                        ExtOut(" = %S", mdName);
                        isFirst = false;
                    }
                    else ExtOut(" | %S", mdName);
                }
            }
        }
        pMD->CloseEnum(fEnum);

        return S_OK;
    }

    static HRESULT PrintStringValue(ICorDebugValue * pValue)
    {
        HRESULT Status;

        ToRelease<ICorDebugStringValue> pStringValue;
        IfFailRet(pValue->QueryInterface(IID_ICorDebugStringValue, (LPVOID*) &pStringValue));

        ULONG32 cchValue;
        IfFailRet(pStringValue->GetLength(&cchValue));
        cchValue++;         // Allocate one more for null terminator

        CQuickString quickString;
        quickString.Alloc(cchValue);

        ULONG32 cchValueReturned;
        IfFailRet(pStringValue->GetString(
            cchValue,
            &cchValueReturned,
            quickString.String()));

        ExtOut(" = \"%S\"\n", quickString.String());
        
        return S_OK;
    }

    static HRESULT PrintSzArrayValue(ICorDebugValue * pValue, ICorDebugILFrame * pILFrame, IMetaDataImport * pMD, int indent, __in_z WCHAR* varToExpand, __inout_ecount(currentExpansionSize) WCHAR* currentExpansion, DWORD currentExpansionSize, int currentFrame)
    {
        HRESULT Status = S_OK;

        ToRelease<ICorDebugArrayValue> pArrayValue;
        IfFailRet(pValue->QueryInterface(IID_ICorDebugArrayValue, (LPVOID*) &pArrayValue));

        ULONG32 nRank;
        IfFailRet(pArrayValue->GetRank(&nRank));
        if (nRank != 1)
        {
            return E_UNEXPECTED;
        }

        ULONG32 cElements;
        IfFailRet(pArrayValue->GetCount(&cElements));

        if (cElements == 0) ExtOut("   (empty)\n");
        else if (cElements == 1) ExtOut("   (1 element)\n");
        else ExtOut("   (%d elements)\n", cElements);

        if(!ShouldExpandVariable(varToExpand, currentExpansion)) return S_OK;
        size_t currentExpansionLen = _wcslen(currentExpansion);

        for (ULONG32 i=0; i < cElements; i++)
        {
            for(int j = 0; j <= indent; j++) ExtOut("    ");
            currentExpansion[currentExpansionLen] = L'\0';
            swprintf_s(currentExpansion, mdNameLen, W("%s.[%d]\0"), currentExpansion, i);

            bool printed = false;
            CorElementType corElemType;
            ToRelease<ICorDebugType> pFirstParameter;
            ToRelease<ICorDebugValue2> pValue2;
            ToRelease<ICorDebugType> pType;
            if(SUCCEEDED(pArrayValue->QueryInterface(IID_ICorDebugValue2, (LPVOID *) &pValue2)) && SUCCEEDED(pValue2->GetExactType(&pType)))
            {
                if(SUCCEEDED(pType->GetFirstTypeParameter(&pFirstParameter)) && SUCCEEDED(pFirstParameter->GetType(&corElemType)))
                {
                    switch(corElemType)
                    {
                    //If the array element is something that we can expand with !clrstack, show information about the type of this element
                    case ELEMENT_TYPE_VALUETYPE:
                    case ELEMENT_TYPE_CLASS:
                    case ELEMENT_TYPE_SZARRAY:
                        {
                            WCHAR typeOfElement[mdNameLen];
                            GetTypeOfValue(pFirstParameter, typeOfElement, mdNameLen);
                            DMLOut(" |- %s = %S", DMLManagedVar(currentExpansion, currentFrame, i), typeOfElement);
                            printed = true;
                        }
                        break;
                    default:
                        break;
                    }
                }
            }
            if(!printed) DMLOut(" |- %s", DMLManagedVar(currentExpansion, currentFrame, i));

            ToRelease<ICorDebugValue> pElementValue;
            IfFailRet(pArrayValue->GetElementAtPosition(i, &pElementValue));
            IfFailRet(PrintValue(pElementValue, pILFrame, pMD, indent + 1, varToExpand, currentExpansion, currentExpansionSize, currentFrame));
        }

        return S_OK;
    }

    static HRESULT PrintValue(ICorDebugValue * pInputValue, ICorDebugILFrame * pILFrame, IMetaDataImport * pMD, int indent, __in_z WCHAR* varToExpand, __inout_ecount(currentExpansionSize) WCHAR* currentExpansion, DWORD currentExpansionSize, int currentFrame)
    {
        HRESULT Status = S_OK;

        BOOL isNull = TRUE;
        ToRelease<ICorDebugValue> pValue;
        IfFailRet(DereferenceAndUnboxValue(pInputValue, &pValue, &isNull));

        if(isNull)
        {
            ExtOut(" = null\n");
            return S_OK;
        }

        ULONG32 cbSize;
        IfFailRet(pValue->GetSize(&cbSize));
        ArrayHolder<BYTE> rgbValue = new NOTHROW BYTE[cbSize];
        if (rgbValue == NULL)
        {
            ReportOOM();
            return E_OUTOFMEMORY;
        }

        memset(rgbValue.GetPtr(), 0, cbSize * sizeof(BYTE));

        CorElementType corElemType;
        IfFailRet(pValue->GetType(&corElemType));
        if (corElemType == ELEMENT_TYPE_STRING)
        {
            return PrintStringValue(pValue);
        }

        if (corElemType == ELEMENT_TYPE_SZARRAY)
        {
            return PrintSzArrayValue(pValue, pILFrame, pMD, indent, varToExpand, currentExpansion, currentExpansionSize, currentFrame);
        }

        ToRelease<ICorDebugGenericValue> pGenericValue;
        IfFailRet(pValue->QueryInterface(IID_ICorDebugGenericValue, (LPVOID*) &pGenericValue));
        IfFailRet(pGenericValue->GetValue((LPVOID) &(rgbValue[0])));

        if(IsEnum(pValue))
        {
            Status = PrintEnumValue(pValue, rgbValue);
            ExtOut("\n");
            return Status;
        }

        switch (corElemType)
        {
        default:
            ExtOut("  (Unhandled CorElementType: 0x%x)\n", corElemType);
            break;

        case ELEMENT_TYPE_PTR:
            ExtOut("  = <pointer>\n");
            break;

        case ELEMENT_TYPE_FNPTR:
            {
                CORDB_ADDRESS addr = 0;
                ToRelease<ICorDebugReferenceValue> pReferenceValue = NULL;
                if(SUCCEEDED(pValue->QueryInterface(IID_ICorDebugReferenceValue, (LPVOID*) &pReferenceValue)))
                    pReferenceValue->GetValue(&addr);
                ExtOut("  = <function pointer 0x%x>\n", addr);
            }
            break;

        case ELEMENT_TYPE_VALUETYPE:
        case ELEMENT_TYPE_CLASS:
            CORDB_ADDRESS addr;
            if(SUCCEEDED(pValue->GetAddress(&addr)))
            {
                ExtOut(" @ 0x%I64x\n", addr);
            }
            else
            {
                ExtOut("\n");
            }
            ProcessFields(pValue, NULL, pILFrame, indent + 1, varToExpand, currentExpansion, currentExpansionSize, currentFrame);
            break;

        case ELEMENT_TYPE_BOOLEAN:
            ExtOut("  = %s\n", rgbValue[0] == 0 ? "false" : "true");
            break;

        case ELEMENT_TYPE_CHAR:
            ExtOut("  = '%C'\n", *(WCHAR *) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_I1:
            ExtOut("  = %d\n", *(char*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_U1:
            ExtOut("  = %d\n", *(unsigned char*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_I2:
            ExtOut("  = %hd\n", *(short*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_U2:
            ExtOut("  = %hu\n", *(unsigned short*) &(rgbValue[0]));
            break;
        
        case ELEMENT_TYPE_I:
            ExtOut("  = %d\n", *(int*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_U:
            ExtOut("  = %u\n", *(unsigned int*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_I4:
            ExtOut("  = %d\n", *(int*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_U4:
            ExtOut("  = %u\n", *(unsigned int*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_I8:
            ExtOut("  = %I64d\n", *(__int64*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_U8:
            ExtOut("  = %I64u\n", *(unsigned __int64*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_R4:
            ExtOut("  = %f\n", (double) *(float*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_R8:
            ExtOut("  = %f\n", *(double*) &(rgbValue[0]));
            break;

        case ELEMENT_TYPE_OBJECT:
            ExtOut("  = object\n");
            break;

            // TODO: The following corElementTypes are not yet implemented here.  Array
            // might be interesting to add, though the others may be of rather limited use:
            // ELEMENT_TYPE_ARRAY          = 0x14,     // MDARRAY <type> <rank> <bcount> <bound1> ... <lbcount> <lb1> ...
            // 
            // ELEMENT_TYPE_GENERICINST    = 0x15,     // GENERICINST <generic type> <argCnt> <arg1> ... <argn>
        }

        return S_OK;
    }

    static HRESULT PrintParameters(BOOL bParams, BOOL bLocals, IMetaDataImport * pMD, mdTypeDef typeDef, mdMethodDef methodDef, ICorDebugILFrame * pILFrame, ICorDebugModule * pModule, __in_z WCHAR* varToExpand, int currentFrame)
    {
        HRESULT Status = S_OK;

        ULONG cParams = 0;
        ToRelease<ICorDebugValueEnum> pParamEnum;
        IfFailRet(pILFrame->EnumerateArguments(&pParamEnum));
        IfFailRet(pParamEnum->GetCount(&cParams));
        if (cParams > 0 && bParams)
        {
            DWORD methAttr = 0;
            IfFailRet(pMD->GetMethodProps(methodDef, NULL, NULL, 0, NULL, &methAttr, NULL, NULL, NULL, NULL));

            ExtOut("\nPARAMETERS:\n");
            for (ULONG i=0; i < cParams; i++)
            {
                ULONG paramNameLen = 0;
                mdParamDef paramDef;
                WCHAR paramName[mdNameLen] = W("\0");

                if(i == 0 && (methAttr & mdStatic) == 0)
                    swprintf_s(paramName, mdNameLen, W("this\0"));
                else 
                {
                    int idx = ((methAttr & mdStatic) == 0)? i : (i + 1);
                    if(SUCCEEDED(pMD->GetParamForMethodIndex(methodDef, idx, &paramDef)))
                        pMD->GetParamProps(paramDef, NULL, NULL, paramName, mdNameLen, &paramNameLen, NULL, NULL, NULL, NULL);
                }
                if(_wcslen(paramName) == 0)
                    swprintf_s(paramName, mdNameLen, W("param_%d\0"), i);

                ToRelease<ICorDebugValue> pValue;
                ULONG cArgsFetched;
                Status = pParamEnum->Next(1, &pValue, &cArgsFetched);

                if (FAILED(Status))
                {
                    ExtOut("  + (Error 0x%x retrieving parameter '%S')\n", Status, paramName);
                    continue;
                }

                if (Status == S_FALSE)
                {
                    break;
                }

                WCHAR typeName[mdNameLen] = W("\0");
                GetTypeOfValue(pValue, typeName, mdNameLen);
                DMLOut("  + %S %s", typeName, DMLManagedVar(paramName, currentFrame, paramName));

                ToRelease<ICorDebugReferenceValue> pRefValue;
                if(SUCCEEDED(pValue->QueryInterface(IID_ICorDebugReferenceValue, (void**)&pRefValue)) && pRefValue != NULL)
                {
                    BOOL bIsNull = TRUE;
                    pRefValue->IsNull(&bIsNull);
                    if(bIsNull)
                    {
                        ExtOut(" = null\n");
                        continue;
                    }
                }

                WCHAR currentExpansion[mdNameLen];
                swprintf_s(currentExpansion, mdNameLen, W("%s\0"), paramName);
                if((Status=PrintValue(pValue, pILFrame, pMD, 0, varToExpand, currentExpansion, mdNameLen, currentFrame)) != S_OK)
                    ExtOut("  + (Error 0x%x printing parameter %d)\n", Status, i);
            }
        }
        else if (cParams == 0 && bParams)
            ExtOut("\nPARAMETERS: (none)\n");

        ULONG cLocals = 0;
        ToRelease<ICorDebugValueEnum> pLocalsEnum;
        IfFailRet(pILFrame->EnumerateLocalVariables(&pLocalsEnum));
        IfFailRet(pLocalsEnum->GetCount(&cLocals));
        if (cLocals > 0 && bLocals)
        {
            bool symbolsAvailable = false;
            SymbolReader symReader;
            if(SUCCEEDED(symReader.LoadSymbols(pMD, pModule)))
                symbolsAvailable = true;
            ExtOut("\nLOCALS:\n");
            for (ULONG i=0; i < cLocals; i++)
            {
                ULONG paramNameLen = 0;
                WCHAR paramName[mdNameLen] = W("\0");

                ToRelease<ICorDebugValue> pValue;
                if(symbolsAvailable)
                {
                    Status = symReader.GetNamedLocalVariable(pILFrame, i, paramName, mdNameLen, &pValue);
                }
                else
                {
                    ULONG cArgsFetched;
                    Status = pLocalsEnum->Next(1, &pValue, &cArgsFetched);
                }
                if(_wcslen(paramName) == 0)
                    swprintf_s(paramName, mdNameLen, W("local_%d\0"), i);

                if (FAILED(Status))
                {
                    ExtOut("  + (Error 0x%x retrieving local variable '%S')\n", Status, paramName);
                    continue;
                }

                if (Status == S_FALSE)
                {
                    break;
                }

                WCHAR typeName[mdNameLen] = W("\0");
                GetTypeOfValue(pValue, typeName, mdNameLen);
                DMLOut("  + %S %s", typeName, DMLManagedVar(paramName, currentFrame, paramName));

                ToRelease<ICorDebugReferenceValue> pRefValue = NULL;
                if(SUCCEEDED(pValue->QueryInterface(IID_ICorDebugReferenceValue, (void**)&pRefValue)) && pRefValue != NULL)
                {
                    BOOL bIsNull = TRUE;
                    pRefValue->IsNull(&bIsNull);
                    if(bIsNull)
                    {
                        ExtOut(" = null\n");
                        continue;
                    }
                }

                WCHAR currentExpansion[mdNameLen];
                swprintf_s(currentExpansion, mdNameLen, W("%s\0"), paramName);
                if((Status=PrintValue(pValue, pILFrame, pMD, 0, varToExpand, currentExpansion, mdNameLen, currentFrame)) != S_OK)
                    ExtOut("  + (Error 0x%x printing local variable %d)\n", Status, i);
            }
        }
        else if (cLocals == 0 && bLocals)
            ExtOut("\nLOCALS: (none)\n");

        if(bParams || bLocals)
            ExtOut("\n");

        return S_OK;
    }

    static HRESULT ProcessFields(ICorDebugValue* pInputValue, ICorDebugType* pTypeCast, ICorDebugILFrame * pILFrame, int indent, __in_z WCHAR* varToExpand, __inout_ecount(currentExpansionSize) WCHAR* currentExpansion, DWORD currentExpansionSize, int currentFrame)
    {
        if(!ShouldExpandVariable(varToExpand, currentExpansion)) return S_OK;
        size_t currentExpansionLen = _wcslen(currentExpansion);

        HRESULT Status = S_OK;

        BOOL isNull = FALSE;
        ToRelease<ICorDebugValue> pValue;
        IfFailRet(DereferenceAndUnboxValue(pInputValue, &pValue, &isNull));

        if(isNull) return S_OK;

        mdTypeDef currentTypeDef;
        ToRelease<ICorDebugClass> pClass;
        ToRelease<ICorDebugValue2> pValue2;
        ToRelease<ICorDebugType> pType;
        ToRelease<ICorDebugModule> pModule;
        IfFailRet(pValue->QueryInterface(IID_ICorDebugValue2, (LPVOID *) &pValue2));
        if(pTypeCast == NULL)
            IfFailRet(pValue2->GetExactType(&pType));
        else
        {
            pType = pTypeCast;
            pType->AddRef();
        }
        IfFailRet(pType->GetClass(&pClass));
        IfFailRet(pClass->GetModule(&pModule));
        IfFailRet(pClass->GetToken(&currentTypeDef));

        ToRelease<IUnknown> pMDUnknown;
        ToRelease<IMetaDataImport> pMD;
        IfFailRet(pModule->GetMetaDataInterface(IID_IMetaDataImport, &pMDUnknown));
        IfFailRet(pMDUnknown->QueryInterface(IID_IMetaDataImport, (LPVOID*) &pMD));

        WCHAR baseTypeName[mdNameLen] = W("\0");
        ToRelease<ICorDebugType> pBaseType;
        if(SUCCEEDED(pType->GetBase(&pBaseType)) && pBaseType != NULL && SUCCEEDED(GetTypeOfValue(pBaseType, baseTypeName, mdNameLen)))
        {
            if(_wcsncmp(baseTypeName, W("System.Enum"), 11) == 0)
                return S_OK;
            else if(_wcsncmp(baseTypeName, W("System.Object"), 13) != 0 && _wcsncmp(baseTypeName, W("System.ValueType"), 16) != 0)
            {
                currentExpansion[currentExpansionLen] = W('\0');
                wcscat_s(currentExpansion, currentExpansionSize, W(".\0"));
                wcscat_s(currentExpansion, currentExpansionSize, W("[basetype]"));
                for(int i = 0; i < indent; i++) ExtOut("    ");
                DMLOut(" |- %S %s\n", baseTypeName, DMLManagedVar(currentExpansion, currentFrame, W("[basetype]")));

                if(ShouldExpandVariable(varToExpand, currentExpansion))
                    ProcessFields(pInputValue, pBaseType, pILFrame, indent + 1, varToExpand, currentExpansion, currentExpansionSize, currentFrame);
            }
        }


        ULONG numFields = 0;
        HCORENUM fEnum = NULL;
        mdFieldDef fieldDef;
        while(SUCCEEDED(pMD->EnumFields(&fEnum, currentTypeDef, &fieldDef, 1, &numFields)) && numFields != 0)
        {
            ULONG             nameLen = 0;
            DWORD             fieldAttr = 0;
            WCHAR             mdName[mdNameLen];
            WCHAR             typeName[mdNameLen];
            if(SUCCEEDED(pMD->GetFieldProps(fieldDef, NULL, mdName, mdNameLen, &nameLen, &fieldAttr, NULL, NULL, NULL, NULL, NULL)))
            {
                currentExpansion[currentExpansionLen] = W('\0');
                wcscat_s(currentExpansion, currentExpansionSize, W(".\0"));
                wcscat_s(currentExpansion, currentExpansionSize, mdName);

                ToRelease<ICorDebugValue> pFieldVal;
                if(fieldAttr & fdLiteral)
                {
                    //TODO: Is it worth it??
                    //ExtOut(" |- const %S", mdName);
                }
                else
                {
                    for(int i = 0; i < indent; i++) ExtOut("    ");

                    if (fieldAttr & fdStatic)
                        pType->GetStaticFieldValue(fieldDef, pILFrame, &pFieldVal);
                    else
                    {
                        ToRelease<ICorDebugObjectValue> pObjValue;
                        if (SUCCEEDED(pValue->QueryInterface(IID_ICorDebugObjectValue, (LPVOID*) &pObjValue)))
                            pObjValue->GetFieldValue(pClass, fieldDef, &pFieldVal);
                    }

                    if(pFieldVal != NULL)
                    {
                        typeName[0] = L'\0';
                        GetTypeOfValue(pFieldVal, typeName, mdNameLen);
                        DMLOut(" |- %S %s", typeName, DMLManagedVar(currentExpansion, currentFrame, mdName));
                        PrintValue(pFieldVal, pILFrame, pMD, indent, varToExpand, currentExpansion, currentExpansionSize, currentFrame);
                    }
                    else if(!(fieldAttr & fdLiteral)) 
                        ExtOut(" |- < unknown type > %S\n", mdName);
                }
            }
        }
        pMD->CloseEnum(fEnum);
        return S_OK;
    }

public:

    // This is the main worker function used if !clrstack is called with "-i" to indicate
    // that the public ICorDebug* should be used instead of the private DAC interface. NOTE:
    // Currently only bParams is supported. NOTE: This is a work in progress and the
    // following would be good to do:
    //     * More thorough testing with interesting stacks, especially with transitions into
    //         and out of managed code.
    //     * Consider interleaving this code back into the main body of !clrstack if it turns
    //         out that there's a lot of duplication of code between these two functions.
    //         (Still unclear how things will look once locals is implemented.)
    static HRESULT ClrStackFromPublicInterface(BOOL bParams, BOOL bLocals, BOOL bSuppressLines, __in_z WCHAR* varToExpand = NULL, int onlyShowFrame = -1)
    {
        HRESULT Status;

        IfFailRet(InitCorDebugInterface());

        ExtOut("\n\n\nDumping managed stack and managed variables using ICorDebug.\n");
        ExtOut("=============================================================================\n");

        ToRelease<ICorDebugThread> pThread;
        ToRelease<ICorDebugThread3> pThread3;
        ToRelease<ICorDebugStackWalk> pStackWalk;
        ULONG ulThreadID = 0;
        g_ExtSystem->GetCurrentThreadSystemId(&ulThreadID);

        IfFailRet(g_pCorDebugProcess->GetThread(ulThreadID, &pThread));
        IfFailRet(pThread->QueryInterface(IID_ICorDebugThread3, (LPVOID *) &pThread3));
        IfFailRet(pThread3->CreateStackWalk(&pStackWalk));

        InternalFrameManager internalFrameManager;
        IfFailRet(internalFrameManager.Init(pThread3));
        
    #if defined(_AMD64_)
        ExtOut("%-16s %-16s %s\n", "Child SP", "IP", "Call Site");
    #elif defined(_X86_)
        ExtOut("%-8s %-8s %s\n", "Child SP", "IP", "Call Site");
    #endif

        int currentFrame = -1;

        for (Status = S_OK; ; Status = pStackWalk->Next())
        {
            currentFrame++;

            if (Status == CORDBG_S_AT_END_OF_STACK)
            {
                ExtOut("Stack walk complete.\n");
                break;
            }
            IfFailRet(Status);

            if (IsInterrupt())
            {
                ExtOut("<interrupted>\n");
                break;
            }
            
            CROSS_PLATFORM_CONTEXT context;
            ULONG32 cbContextActual;
            if ((Status=pStackWalk->GetContext(
                DT_CONTEXT_FULL, 
                sizeof(context),
                &cbContextActual,
                (BYTE *)&context))!=S_OK)
            {
                ExtOut("GetFrameContext failed: %lx\n",Status);
                break;
            }

            // First find the info for the Frame object, if the current frame has an associated clr!Frame.
            CLRDATA_ADDRESS sp = GetSP(context);
            CLRDATA_ADDRESS ip = GetIP(context);

            ToRelease<ICorDebugFrame> pFrame;
            IfFailRet(pStackWalk->GetFrame(&pFrame));
            if (Status == S_FALSE)
            {
                DMLOut("%p %s [NativeStackFrame]\n", SOS_PTR(sp), DMLIP(ip));
                continue;
            }

            // TODO: What about internal frames preceding the above native stack frame? 
            // Should I just exclude the above native stack frame from the output?
            // TODO: Compare caller frame (instead of current frame) against internal frame,
            // to deal with issues of current frame's current SP being closer to leaf than
            // EE Frames it pushes.  By "caller" I mean not just managed caller, but the
            // very next non-internal frame dbi would return (native or managed). OR...
            // perhaps I should use GetStackRange() instead, to see if the internal frame
            // appears leafier than the base-part of the range of the currently iterated
            // stack frame?  I think I like that better.
            _ASSERTE(pFrame != NULL);
            IfFailRet(internalFrameManager.PrintPrecedingInternalFrames(pFrame));

            // Print the stack and instruction pointers.
            DMLOut("%p %s ", SOS_PTR(sp), DMLIP(ip));

            ToRelease<ICorDebugRuntimeUnwindableFrame> pRuntimeUnwindableFrame;
            Status = pFrame->QueryInterface(IID_ICorDebugRuntimeUnwindableFrame, (LPVOID *) &pRuntimeUnwindableFrame);
            if (SUCCEEDED(Status))
            {
                ExtOut("[RuntimeUnwindableFrame]\n");
                continue;
            }

            // Print the method/Frame info

            // TODO: IS THE FOLLOWING NECESSARY, OR AM I GUARANTEED THAT ALL INTERNAL FRAMES
            // CAN BE FOUND VIA GetActiveInternalFrames?
            ToRelease<ICorDebugInternalFrame> pInternalFrame;
            Status = pFrame->QueryInterface(IID_ICorDebugInternalFrame, (LPVOID *) &pInternalFrame);
            if (SUCCEEDED(Status))
            {
                // This is a clr!Frame.
                LPCWSTR pwszFrameName = W("TODO: Implement GetFrameName");
                ExtOut("[%S: p] ", pwszFrameName);
            }

            // Print the frame's associated function info, if it has any.
            ToRelease<ICorDebugILFrame> pILFrame;
            HRESULT hrILFrame = pFrame->QueryInterface(IID_ICorDebugILFrame, (LPVOID*) &pILFrame);

            if (SUCCEEDED(hrILFrame))
            {
                ToRelease<ICorDebugFunction> pFunction;
                Status = pFrame->GetFunction(&pFunction);
                if (FAILED(Status))
                {
                    // We're on a JITted frame, but there's no Function for it.  So it must
                    // be... 
                    ExtOut("[IL Stub or LCG]\n");
                    continue;
                }

                ToRelease<ICorDebugClass> pClass;
                ToRelease<ICorDebugModule> pModule;
                mdMethodDef methodDef;
                IfFailRet(pFunction->GetClass(&pClass));
                IfFailRet(pFunction->GetModule(&pModule));
                IfFailRet(pFunction->GetToken(&methodDef));

                WCHAR wszModuleName[100];
                ULONG32 cchModuleNameActual;
                IfFailRet(pModule->GetName(_countof(wszModuleName), &cchModuleNameActual, wszModuleName));

                ToRelease<IUnknown> pMDUnknown;
                ToRelease<IMetaDataImport> pMD;
                ToRelease<IMDInternalImport> pMDInternal;
                IfFailRet(pModule->GetMetaDataInterface(IID_IMetaDataImport, &pMDUnknown));
                IfFailRet(pMDUnknown->QueryInterface(IID_IMetaDataImport, (LPVOID*) &pMD));
                IfFailRet(GetMDInternalFromImport(pMD, &pMDInternal));

                mdTypeDef typeDef;
                IfFailRet(pClass->GetToken(&typeDef));

                // Note that we don't need to pretty print the class, as class name is
                // already printed from GetMethodName below

                CQuickBytes functionName;
                // TODO: WARNING: GetMethodName() appears to include lots of unexercised
                // code, as evidenced by some fundamental bugs I found.  It should either be
                // thoroughly reviewed, or some other more exercised code path to grab the
                // name should be used.
                // TODO: If we do stay with GetMethodName, it should be updated to print
                // generics properly.  Today, it does not show generic type parameters, and
                // if any arguments have a generic type, those arguments are just shown as
                // "__Canon", even when they're value types.
                GetMethodName(methodDef, pMD, &functionName);

                DMLOut(DMLManagedVar(W("-a"), currentFrame, (LPWSTR)functionName.Ptr()));
                ExtOut(" (%S)\n", wszModuleName);

                if (SUCCEEDED(hrILFrame) && (bParams || bLocals))
                {
                    if(onlyShowFrame == -1 || (onlyShowFrame >= 0 && currentFrame == onlyShowFrame))
                        IfFailRet(PrintParameters(bParams, bLocals, pMD, typeDef, methodDef, pILFrame, pModule, varToExpand, currentFrame));
                }
            }
        }
        ExtOut("=============================================================================\n");

#ifdef FEATURE_PAL
        // Temporary until we get a process exit notification plumbed from lldb
        UninitCorDebugInterface();
#endif
        return S_OK;
    }
};

WString BuildRegisterOutput(const SOSStackRefData &ref, bool printObj)
{
    WString res;
    
    if (ref.HasRegisterInformation)
    {
        WCHAR reg[32];
        HRESULT hr = g_sos->GetRegisterName(ref.Register, _countof(reg), reg, NULL);
        if (SUCCEEDED(hr))
            res = reg;
        else
            res = W("<unknown register>");
            
        if (ref.Offset)
        {
            int offset = ref.Offset;
            if (offset > 0)
            {
                res += W("+");
            }
            else
            {
                res += W("-");
                offset = -offset;
            }
            
            res += Hex(offset);
        }
        
        res += W(": ");
    }
    
    if (ref.Address)
        res += WString(Pointer(ref.Address));
        
    if (printObj)
    {
        if (ref.Address)
            res += W(" -> ");

        res += WString(ObjectPtr(ref.Object));
    }

    if (ref.Flags & SOSRefPinned)
    {
        res += W(" (pinned)");
    }
    
    if (ref.Flags & SOSRefInterior)
    {
        res += W(" (interior)");
    }
    
    return res;
}

void PrintRef(const SOSStackRefData &ref, TableOutput &out)
{
    WString res = BuildRegisterOutput(ref);
    
    if (ref.Object && (ref.Flags & SOSRefInterior) == 0)
    {
        WCHAR type[128];
        sos::BuildTypeWithExtraInfo(TO_TADDR(ref.Object), _countof(type), type);
        
        res += WString(W(" - ")) + type;
    }
    
    out.WriteColumn(2, res);
}


class ClrStackImpl
{
public:
    static void PrintThread(ULONG osID, BOOL bParams, BOOL bLocals, BOOL bSuppressLines, BOOL bGC, BOOL bFull, BOOL bDisplayRegVals)
    {
        // Symbols variables
        ULONG symlines = 0; // symlines will be non-zero only if SYMOPT_LOAD_LINES was set in the symbol options
        if (!bSuppressLines && SUCCEEDED(g_ExtSymbols->GetSymbolOptions(&symlines)))
        {
            symlines &= SYMOPT_LOAD_LINES;
        }
        
        if (symlines == 0)
            bSuppressLines = TRUE;
        
        ToRelease<IXCLRDataStackWalk> pStackWalk;
        
        HRESULT hr = CreateStackWalk(osID, &pStackWalk);
        if (FAILED(hr) || pStackWalk == NULL)
        {
            ExtOut("Failed to start stack walk: %lx\n", hr);
            return;
        }

#ifdef _TARGET_WIN64_
        PDEBUG_STACK_FRAME currentNativeFrame = NULL;
        ULONG numNativeFrames = 0;
        if (bFull)
        {
            hr = GetContextStackTrace(&numNativeFrames);
            if (FAILED(hr))
            {
                ExtOut("Failed to get native stack frames: %lx\n", hr);
                return;
            }
            currentNativeFrame = &g_Frames[0];
        }
#endif // _TARGET_WIN64_
        
        unsigned int refCount = 0, errCount = 0;
        ArrayHolder<SOSStackRefData> pRefs = NULL;
        ArrayHolder<SOSStackRefError> pErrs = NULL;
        if (bGC && FAILED(GetGCRefs(osID, &pRefs, &refCount, &pErrs, &errCount)))
            refCount = 0;
            
        TableOutput out(3, POINTERSIZE_HEX, AlignRight);
        out.WriteRow("Child SP", "IP", "Call Site");
                
        do
        {
            if (IsInterrupt())
            {
                ExtOut("<interrupted>\n");
                break;
            }
            CLRDATA_ADDRESS ip = 0, sp = 0;
            hr = GetFrameLocation(pStackWalk, &ip, &sp);

            DacpFrameData FrameData;
            HRESULT frameDataResult = FrameData.Request(pStackWalk);
            if (SUCCEEDED(frameDataResult) && FrameData.frameAddr)
                sp = FrameData.frameAddr;

#ifdef _TARGET_WIN64_
            while ((numNativeFrames > 0) && (currentNativeFrame->StackOffset <= sp))
            {
                if (currentNativeFrame->StackOffset != sp)
                {
                    PrintNativeStackFrame(out, currentNativeFrame, bSuppressLines);
                }
                currentNativeFrame++;
                numNativeFrames--;
            }
#endif // _TARGET_WIN64_

            // Print the stack pointer.
            out.WriteColumn(0, sp);

            // Print the method/Frame info
            if (SUCCEEDED(frameDataResult) && FrameData.frameAddr)
            {
                // Skip the instruction pointer because it doesn't really mean anything for method frames
                out.WriteColumn(1, bFull ? String("") : NativePtr(ip));
                
                // This is a clr!Frame.
                out.WriteColumn(2, GetFrameFromAddress(TO_TADDR(FrameData.frameAddr), pStackWalk, bFull));
            
                // Print out gc references for the Frame.  
                for (unsigned int i = 0; i < refCount; ++i)
                    if (pRefs[i].Source == sp)
                        PrintRef(pRefs[i], out);
                        
                // Print out an error message if we got one.
                for (unsigned int i = 0; i < errCount; ++i)
                    if (pErrs[i].Source == sp)
                        out.WriteColumn(2, "Failed to enumerate GC references.");
            }
            else
            {
                out.WriteColumn(1, InstructionPtr(ip));
                out.WriteColumn(2, MethodNameFromIP(ip, bSuppressLines, bFull, bFull));
                    
                // Print out gc references.  refCount will be zero if bGC is false (or if we
                // failed to fetch gc reference information).
                for (unsigned int i = 0; i < refCount; ++i)
                    if (pRefs[i].Source == ip && pRefs[i].StackPointer == sp)
                        PrintRef(pRefs[i], out);

                // Print out an error message if we got one.
                for (unsigned int i = 0; i < errCount; ++i)
                    if (pErrs[i].Source == sp)
                        out.WriteColumn(2, "Failed to enumerate GC references.");

                if (bParams || bLocals)
                    PrintArgsAndLocals(pStackWalk, bParams, bLocals);
            }

            if (bDisplayRegVals)
                PrintManagedFrameContext(pStackWalk);

        } while (pStackWalk->Next() == S_OK);

#ifdef _TARGET_WIN64_
        while (numNativeFrames > 0)
        {
            PrintNativeStackFrame(out, currentNativeFrame, bSuppressLines);
            currentNativeFrame++;
            numNativeFrames--;
        }
#endif // _TARGET_WIN64_
    }
    
    static HRESULT PrintManagedFrameContext(IXCLRDataStackWalk *pStackWalk)
    {
        CROSS_PLATFORM_CONTEXT context;
        HRESULT hr = pStackWalk->GetContext(DT_CONTEXT_FULL, g_targetMachine->GetContextSize(), NULL, (BYTE *)&context);
        if (FAILED(hr) || hr == S_FALSE)
        {
            // GetFrameContext returns S_FALSE if the frame iterator is invalid.  That's basically an error for us.
            ExtOut("GetFrameContext failed: %lx\n", hr);
            return E_FAIL;
        }
                     
#if defined(SOS_TARGET_AMD64)
        String outputFormat3 = "    %3s=%016x %3s=%016x %3s=%016x\n";
        String outputFormat2 = "    %3s=%016x %3s=%016x\n";
        ExtOut(outputFormat3, "rsp", context.Amd64Context.Rsp, "rbp", context.Amd64Context.Rbp, "rip", context.Amd64Context.Rip);
        ExtOut(outputFormat3, "rax", context.Amd64Context.Rax, "rbx", context.Amd64Context.Rbx, "rcx", context.Amd64Context.Rcx);
        ExtOut(outputFormat3, "rdx", context.Amd64Context.Rdx, "rsi", context.Amd64Context.Rsi, "rdi", context.Amd64Context.Rdi);
        ExtOut(outputFormat3, "r8", context.Amd64Context.R8, "r9", context.Amd64Context.R9, "r10", context.Amd64Context.R10);
        ExtOut(outputFormat3, "r11", context.Amd64Context.R11, "r12", context.Amd64Context.R12, "r13", context.Amd64Context.R13);
        ExtOut(outputFormat2, "r14", context.Amd64Context.R14, "r15", context.Amd64Context.R15);
#elif defined(SOS_TARGET_X86)
        String outputFormat3 = "    %3s=%08x %3s=%08x %3s=%08x\n";
        String outputFormat2 = "    %3s=%08x %3s=%08x\n";
        ExtOut(outputFormat3, "esp", context.X86Context.Esp, "ebp", context.X86Context.Ebp, "eip", context.X86Context.Eip);
        ExtOut(outputFormat3, "eax", context.X86Context.Eax, "ebx", context.X86Context.Ebx, "ecx", context.X86Context.Ecx);      
        ExtOut(outputFormat3, "edx", context.X86Context.Edx, "esi", context.X86Context.Esi, "edi", context.X86Context.Edi);
#elif defined(SOS_TARGET_ARM)
        String outputFormat3 = "    %3s=%08x %3s=%08x %3s=%08x\n";
        String outputFormat2 = "    %s=%08x %s=%08x\n";
        String outputFormat1 = "    %s=%08x\n";
        ExtOut(outputFormat3, "r0", context.ArmContext.R0, "r1", context.ArmContext.R1, "r2", context.ArmContext.R2);
        ExtOut(outputFormat3, "r3", context.ArmContext.R3, "r4", context.ArmContext.R4, "r5", context.ArmContext.R5);
        ExtOut(outputFormat3, "r6", context.ArmContext.R6, "r7", context.ArmContext.R7, "r8", context.ArmContext.R8);
        ExtOut(outputFormat3, "r9", context.ArmContext.R9, "r10", context.ArmContext.R10, "r11", context.ArmContext.R11);
        ExtOut(outputFormat1, "r12", context.ArmContext.R12);
        ExtOut(outputFormat3, "sp", context.ArmContext.Sp, "lr", context.ArmContext.Lr, "pc", context.ArmContext.Pc);
        ExtOut(outputFormat2, "cpsr", context.ArmContext.Cpsr, "fpsr", context.ArmContext.Fpscr);
#elif defined(SOS_TARGET_ARM64)
        String outputXRegFormat3 = "    x%d=%016x x%d=%016x x%d=%016x\n";
        String outputXRegFormat1 = "    x%d=%016x\n";
        String outputFormat3     = "    %s=%016x %s=%016x %s=%016x\n";
        String outputFormat2     = "    %s=%08x %s=%08x\n";
        DWORD64 *X = context.Arm64Context.X;
        for (int i = 0; i < 9; i++)
        {
            ExtOut(outputXRegFormat3, i + 0, X[i + 0], i + 1, X[i + 1], i + 2, X[i + 2]);
        }
        ExtOut(outputXRegFormat1, 28, X[28]);
        ExtOut(outputFormat3, "sp", context.ArmContext.Sp, "lr", context.ArmContext.Lr, "pc", context.ArmContext.Pc);
        ExtOut(outputFormat2, "cpsr", context.ArmContext.Cpsr, "fpsr", context.ArmContext.Fpscr);
#else
        ExtOut("Can't display register values for this platform\n");
#endif
        return S_OK;

    }

    static HRESULT GetFrameLocation(IXCLRDataStackWalk *pStackWalk, CLRDATA_ADDRESS *ip, CLRDATA_ADDRESS *sp)
    {
        CROSS_PLATFORM_CONTEXT context;
        HRESULT hr = pStackWalk->GetContext(DT_CONTEXT_FULL, g_targetMachine->GetContextSize(), NULL, (BYTE *)&context);
        if (FAILED(hr) || hr == S_FALSE)
        {
            // GetFrameContext returns S_FALSE if the frame iterator is invalid.  That's basically an error for us.
            ExtOut("GetFrameContext failed: %lx\n", hr);
            return E_FAIL;
        }

        // First find the info for the Frame object, if the current frame has an associated clr!Frame.
        *ip = GetIP(context);
        *sp = GetSP(context);
        
        if (IsDbgTargetArm())
            *ip = *ip & ~THUMB_CODE;
        
        return S_OK;
    }
    
    static void PrintNativeStackFrame(TableOutput out, PDEBUG_STACK_FRAME frame, BOOL bSuppressLines)
    {
        char filename[MAX_LONGPATH + 1];
        char symbol[1024];
        ULONG64 displacement;

        ULONG64 ip = frame->InstructionOffset;

        out.WriteColumn(0, frame->StackOffset);
        out.WriteColumn(1, NativePtr(ip));

        HRESULT hr = g_ExtSymbols->GetNameByOffset(TO_CDADDR(ip), symbol, _countof(symbol), NULL, &displacement);
        if (SUCCEEDED(hr) && symbol[0] != '\0')
        {
            String frameOutput;
            frameOutput += symbol;

            if (displacement)
            {
                frameOutput += " + ";
                frameOutput += Decimal(displacement);
            }

            if (!bSuppressLines)
            {
                ULONG line;
                hr = g_ExtSymbols->GetLineByOffset(TO_CDADDR(ip), &line, filename, _countof(filename), NULL, NULL);
                if (SUCCEEDED(hr))
                {
                    frameOutput += " at ";
                    frameOutput += filename;
                    frameOutput += ":";
                    frameOutput += Decimal(line);
                }
            }

            out.WriteColumn(2, frameOutput);
        }
        else
        {
            out.WriteColumn(2, "");
        }
    }

    static void PrintCurrentThread(BOOL bParams, BOOL bLocals, BOOL bSuppressLines, BOOL bGC, BOOL bNative, BOOL bDisplayRegVals)
    {
        ULONG id = 0;
        ULONG osid = 0;
        
        g_ExtSystem->GetCurrentThreadSystemId(&osid);
        ExtOut("OS Thread Id: 0x%x ", osid);
        g_ExtSystem->GetCurrentThreadId(&id);
        ExtOut("(%d)\n", id);
        
        PrintThread(osid, bParams, bLocals, bSuppressLines, bGC, bNative, bDisplayRegVals);
    }
private: 

    static HRESULT CreateStackWalk(ULONG osID, IXCLRDataStackWalk **ppStackwalk)
    {
        HRESULT hr = S_OK;
        ToRelease<IXCLRDataTask> pTask;

        if ((hr = g_ExtSystem->GetCurrentThreadSystemId(&osID)) != S_OK ||
            (hr = g_clrData->GetTaskByOSThreadID(osID, &pTask)) != S_OK)
        {
            ExtOut("Unable to walk the managed stack. The current thread is likely not a \n");
            ExtOut("managed thread. You can run !threads to get a list of managed threads in\n");
            ExtOut("the process\n");
            return hr;
        }

        return pTask->CreateStackWalk(CLRDATA_SIMPFRAME_UNRECOGNIZED |
                                      CLRDATA_SIMPFRAME_MANAGED_METHOD |
                                      CLRDATA_SIMPFRAME_RUNTIME_MANAGED_CODE |
                                      CLRDATA_SIMPFRAME_RUNTIME_UNMANAGED_CODE,
                                      ppStackwalk);
    }

    /* Prints the args and locals of for a thread's stack.
     * Params:
     *      pStackWalk - the stack we are printing
     *      bArgs - whether to print args
     *      bLocals - whether to print locals
     */
    static void PrintArgsAndLocals(IXCLRDataStackWalk *pStackWalk, BOOL bArgs, BOOL bLocals)
    {
        ToRelease<IXCLRDataFrame> pFrame;
        ToRelease<IXCLRDataValue> pVal;
        ULONG32 argCount = 0;
        ULONG32 localCount = 0;
        HRESULT hr = S_OK;
        
        hr = pStackWalk->GetFrame(&pFrame);
        
        // Print arguments
        if (SUCCEEDED(hr) && bArgs)
            hr = pFrame->GetNumArguments(&argCount);
                
        if (SUCCEEDED(hr) && bArgs)
            hr = ShowArgs(argCount, pFrame, pVal);
        
        // Print locals
        if (SUCCEEDED(hr) && bLocals)
            hr = pFrame->GetNumLocalVariables(&localCount);
        
        if (SUCCEEDED(hr) && bLocals)
            ShowLocals(localCount, pFrame, pVal);
            
        ExtOut("\n");
    }
    
    

    /* Displays the arguments to a function
     * Params:
     *      argy - the number of arguments the function has
     *      pFramey - the frame we are inspecting
     *      pVal - a pointer to the CLRDataValue we use to query for info about the args
     */
    static HRESULT ShowArgs(ULONG32 argy, IXCLRDataFrame *pFramey, IXCLRDataValue *pVal)
    {
        CLRDATA_ADDRESS addr = 0;
        BOOL fPrintedLocation = FALSE;
        ULONG64 outVar = 0;
        ULONG32 tmp;
        HRESULT hr = S_OK;
        
        ArrayHolder<WCHAR> argName = new NOTHROW WCHAR[mdNameLen];
        if (!argName)
        {
            ReportOOM();
            return E_FAIL;
        }
        
        for (ULONG32 i=0; i < argy; i++)
        {   
            if (i == 0)
            {      
                ExtOut("    PARAMETERS:\n");
            }
            
            hr = pFramey->GetArgumentByIndex(i,
                                   &pVal,
                                   mdNameLen,
                                   &tmp,
                                   argName);
            
            if (FAILED(hr))
                return hr;

            ExtOut("        ");
            
            if (argName[0] != L'\0')
            {
                ExtOut("%S ", argName.GetPtr());
            }
            
            // At times we cannot print the value of a parameter (most
            // common case being a non-primitive value type).  In these 
            // cases we need to print the location of the parameter, 
            // so that we can later examine it (e.g. using !dumpvc)
            {
                bool result = SUCCEEDED(pVal->GetNumLocations(&tmp)) && tmp == 1;
                if (result)
                    result = SUCCEEDED(pVal->GetLocationByIndex(0, &tmp, &addr));
                
                if (result)
                {
                    if (tmp == CLRDATA_VLOC_REGISTER)
                    {
                        ExtOut("(<CLR reg>) ");
                    }
                    else
                    {
                        ExtOut("(0x%p) ", SOS_PTR(CDA_TO_UL64(addr)));
                    }
                    fPrintedLocation = TRUE;
                }
            }

            if (argName[0] != L'\0' || fPrintedLocation)
            {
                ExtOut("= ");                
            }
            
            if (HRESULT_CODE(pVal->GetBytes(0,&tmp,NULL)) == ERROR_BUFFER_OVERFLOW)
            {
                ArrayHolder<BYTE> pByte = new NOTHROW BYTE[tmp + 1];
                if (pByte == NULL)
                {
                    ReportOOM();
                    return E_FAIL;
                }
                
                hr = pVal->GetBytes(tmp, &tmp, pByte);
                
                if (FAILED(hr))
                {
                    ExtOut("<unable to retrieve data>\n");
                }
                else
                {
                    switch(tmp)
                    {
                        case 1: outVar = *((BYTE *)pByte.GetPtr()); break;
                        case 2: outVar = *((short *)pByte.GetPtr()); break;
                        case 4: outVar = *((DWORD *)pByte.GetPtr()); break;
                        case 8: outVar = *((ULONG64 *)pByte.GetPtr()); break;
                        default: outVar = 0;
                    }

                    if (outVar)
                        DMLOut("0x%s\n", DMLObject(outVar));
                    else
                        ExtOut("0x%p\n", SOS_PTR(outVar));
                }
                
            }
            else
            {
                ExtOut("<no data>\n");
            }
            
            pVal->Release();
        }
        
        return S_OK;
    }


    /* Prints the locals of a frame.
     * Params:
     *      localy - the number of locals in the frame
     *      pFramey - the frame we are inspecting
     *      pVal - a pointer to the CLRDataValue we use to query for info about the args
     */
    static HRESULT ShowLocals(ULONG32 localy, IXCLRDataFrame *pFramey, IXCLRDataValue *pVal)
    {
        for (ULONG32 i=0; i < localy; i++)
        {   
            if (i == 0)
                ExtOut("    LOCALS:\n");
            
            HRESULT hr;
            ExtOut("        ");
            
            // local names don't work in Whidbey.
            hr = pFramey->GetLocalVariableByIndex(i, &pVal, mdNameLen, NULL, g_mdName);
            if (FAILED(hr))
            {
                return hr;
            }

            ULONG32 numLocations;
            if (SUCCEEDED(pVal->GetNumLocations(&numLocations)) &&
                numLocations == 1)
            {
                ULONG32 flags;
                CLRDATA_ADDRESS addr;
                if (SUCCEEDED(pVal->GetLocationByIndex(0, &flags, &addr)))
                {
                    if (flags == CLRDATA_VLOC_REGISTER)
                    {
                        ExtOut("<CLR reg> ");
                    }
                    else
                    {
                        ExtOut("0x%p ", SOS_PTR(CDA_TO_UL64(addr)));
                    }
                }

                // Can I get a name for the item?

                ExtOut("= ");                
            }
            ULONG32 dwSize = 0;
            hr = pVal->GetBytes(0, &dwSize, NULL);
            
            if (HRESULT_CODE(hr) == ERROR_BUFFER_OVERFLOW)
            {
                ArrayHolder<BYTE> pByte = new NOTHROW BYTE[dwSize + 1];
                if (pByte == NULL)
                {
                    ReportOOM();
                    return E_FAIL;
                }

                hr = pVal->GetBytes(dwSize,&dwSize,pByte);

                if (FAILED(hr))
                {
                    ExtOut("<unable to retrieve data>\n");
                }
                else
                {
                    ULONG64 outVar = 0;
                    switch(dwSize)
                    {
                        case 1: outVar = *((BYTE *) pByte.GetPtr()); break;
                        case 2: outVar = *((short *) pByte.GetPtr()); break;
                        case 4: outVar = *((DWORD *) pByte.GetPtr()); break;
                        case 8: outVar = *((ULONG64 *) pByte.GetPtr()); break;
                        default: outVar = 0;
                    }

                    if (outVar)
                        DMLOut("0x%s\n", DMLObject(outVar));
                    else
                        ExtOut("0x%p\n", SOS_PTR(outVar));
                }
            }
            else
            {
                ExtOut("<no data>\n");
            }
            
            pVal->Release();
        }
        
        return S_OK;
    }

};

#ifndef FEATURE_PAL

WatchCmd g_watchCmd;

// The grand new !Watch command, private to Apollo for now
DECLARE_API(Watch)
{
    INIT_API_NOEE();
    BOOL bExpression = FALSE;
    StringHolder addExpression;
    StringHolder aExpression;
    StringHolder saveName;
    StringHolder sName;
    StringHolder expression;
    StringHolder filterName;
    StringHolder renameOldName;
    size_t expandIndex = -1;
    size_t removeIndex = -1;
    BOOL clear = FALSE;

    size_t nArg = 0;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-add", &addExpression.data, COSTRING, TRUE},
        {"-a", &aExpression.data, COSTRING, TRUE},
        {"-save", &saveName.data, COSTRING, TRUE},
        {"-s", &sName.data, COSTRING, TRUE},
        {"-clear", &clear, COBOOL, FALSE},
        {"-c", &clear, COBOOL, FALSE},
        {"-expand", &expandIndex, COSIZE_T, TRUE},
        {"-filter", &filterName.data, COSTRING, TRUE},
        {"-r", &removeIndex, COSIZE_T, TRUE},
        {"-remove", &removeIndex, COSIZE_T, TRUE},
        {"-rename", &renameOldName.data, COSTRING, TRUE},
    };

    CMDValue arg[] = 
    {   // vptr, type
        {&expression.data, COSTRING}
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }

    if(addExpression.data != NULL || aExpression.data != NULL)
    {
        WCHAR pAddExpression[MAX_EXPRESSION];
        swprintf_s(pAddExpression, MAX_EXPRESSION, W("%S"), addExpression.data != NULL ? addExpression.data : aExpression.data);
        Status = g_watchCmd.Add(pAddExpression);
    }
    else if(removeIndex != -1)
    {
        if(removeIndex <= 0)
        {
            ExtOut("Index must be a postive decimal number\n");
        }
        else
        {
            Status = g_watchCmd.Remove((int)removeIndex);
            if(Status == S_OK)
                ExtOut("Watch expression #%d has been removed\n", removeIndex);
            else if(Status == S_FALSE)
                ExtOut("There is no watch expression with index %d\n", removeIndex);
            else
                ExtOut("Unknown failure 0x%x removing watch expression\n", Status);
        }
    }
    else if(saveName.data != NULL || sName.data != NULL)
    {
        WCHAR pSaveName[MAX_EXPRESSION];
        swprintf_s(pSaveName, MAX_EXPRESSION, W("%S"), saveName.data != NULL ? saveName.data : sName.data);
        Status = g_watchCmd.SaveList(pSaveName);
    }
    else if(clear)
    {
        g_watchCmd.Clear();
    }
    else if(renameOldName.data != NULL)
    {
        if(nArg != 1)
        {
             ExtOut("Must provide an old and new name. Usage: !watch -rename <old_name> <new_name>.\n");
             return S_FALSE;
        }
        WCHAR pOldName[MAX_EXPRESSION];
        swprintf_s(pOldName, MAX_EXPRESSION, W("%S"), renameOldName.data);
        WCHAR pNewName[MAX_EXPRESSION];
        swprintf_s(pNewName, MAX_EXPRESSION, W("%S"), expression.data);
        g_watchCmd.RenameList(pOldName, pNewName);
    }
    // print the tree, possibly with filtering and/or expansion
    else if(expandIndex != -1 || expression.data == NULL)
    {
        WCHAR pExpression[MAX_EXPRESSION];
        pExpression[0] = '\0';

        if(expandIndex != -1)
        {
            if(expression.data != NULL)
            {
                swprintf_s(pExpression, MAX_EXPRESSION, W("%S"), expression.data);
            }
            else
            {
                ExtOut("No expression was provided. Usage !watch -expand <index> <expression>\n");
                return S_FALSE;
            }
        }
        WCHAR pFilterName[MAX_EXPRESSION];
        pFilterName[0] = '\0';

        if(filterName.data != NULL)
        {
            swprintf_s(pFilterName, MAX_EXPRESSION, W("%S"), filterName.data);
        }

        g_watchCmd.Print((int)expandIndex, pExpression, pFilterName);
    }
    else
    {
        ExtOut("Unrecognized argument: %s\n", expression.data);
    }

    return Status;
}

#endif // FEATURE_PAL

DECLARE_API(ClrStack)
{
    INIT_API();

    BOOL bAll = FALSE;    
    BOOL bParams = FALSE;
    BOOL bLocals = FALSE;
    BOOL bSuppressLines = FALSE;
    BOOL bICorDebug = FALSE;
    BOOL bGC = FALSE;
    BOOL dml = FALSE;
    BOOL bFull = FALSE;
    BOOL bDisplayRegVals = FALSE;
    DWORD frameToDumpVariablesFor = -1;
    StringHolder cvariableName;
    ArrayHolder<WCHAR> wvariableName = new NOTHROW WCHAR[mdNameLen];
    if (wvariableName == NULL)
    {
        ReportOOM();
        return E_OUTOFMEMORY;
    }

    memset(wvariableName, 0, sizeof(wvariableName));

    size_t nArg = 0;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-a", &bAll, COBOOL, FALSE},
        {"-p", &bParams, COBOOL, FALSE},
        {"-l", &bLocals, COBOOL, FALSE},
        {"-n", &bSuppressLines, COBOOL, FALSE},
        {"-i", &bICorDebug, COBOOL, FALSE},
        {"-gc", &bGC, COBOOL, FALSE},
        {"-f", &bFull, COBOOL, FALSE},
        {"-r", &bDisplayRegVals, COBOOL, FALSE },
#ifndef FEATURE_PAL
        {"/d", &dml, COBOOL, FALSE},
#endif
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&cvariableName.data, COSTRING},
        {&frameToDumpVariablesFor, COSIZE_T},
    };
    if (!GetCMDOption(args, option, _countof(option), arg, _countof(arg), &nArg))
    {
        return Status;
    }

    EnableDMLHolder dmlHolder(dml);
    if (bAll || bParams || bLocals)
    {
        // No parameter or local supports for minidump case!
        MINIDUMP_NOT_SUPPORTED();        
    }

    if (bAll)
    {
        bParams = bLocals = TRUE;
    }

    if (bICorDebug)
    {
        if(nArg > 0)
        {
            bool firstParamIsNumber = true;
            for(DWORD i = 0; i < strlen(cvariableName.data); i++)
                firstParamIsNumber = firstParamIsNumber && isdigit(cvariableName.data[i]);

            if(firstParamIsNumber && nArg == 1)
            {
                frameToDumpVariablesFor = (DWORD)GetExpression(cvariableName.data);
                cvariableName.data[0] = '\0';
            }
        }
        if(cvariableName.data != NULL && strlen(cvariableName.data) > 0)
            swprintf_s(wvariableName, mdNameLen, W("%S\0"), cvariableName.data);
        
        if(_wcslen(wvariableName) > 0)
            bParams = bLocals = TRUE;

        EnableDMLHolder dmlHolder(TRUE);
        return ClrStackImplWithICorDebug::ClrStackFromPublicInterface(bParams, bLocals, FALSE, wvariableName, frameToDumpVariablesFor);
    }
    
    ClrStackImpl::PrintCurrentThread(bParams, bLocals, bSuppressLines, bGC, bFull, bDisplayRegVals);
    
    return S_OK;
}

#ifndef FEATURE_PAL

BOOL IsMemoryInfoAvailable()
{
    ULONG Class;
    ULONG Qualifier;
    g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
    if (Qualifier == DEBUG_DUMP_SMALL) 
    {
        g_ExtControl->GetDumpFormatFlags(&Qualifier);
        if ((Qualifier & DEBUG_FORMAT_USER_SMALL_FULL_MEMORY) == 0)            
        {
            if ((Qualifier & DEBUG_FORMAT_USER_SMALL_FULL_MEMORY_INFO) == 0)
            {
                return FALSE;
            }            
        }
    }        
    return TRUE;
}

DECLARE_API( VMMap )
{
    INIT_API();

    if (IsMiniDumpFile() || !IsMemoryInfoAvailable())
    {
        ExtOut("!VMMap requires a full memory dump (.dump /ma) or a live process.\n");
    }
    else
    {
        vmmap();
    }

    return Status;
}   // DECLARE_API( vmmap )

DECLARE_API( SOSFlush )
{
    INIT_API();

    g_clrData->Flush();
    
    return Status;
}   // DECLARE_API( SOSFlush )

DECLARE_API( VMStat )
{
    INIT_API();

    if (IsMiniDumpFile() || !IsMemoryInfoAvailable())
    {
        ExtOut("!VMStat requires a full memory dump (.dump /ma) or a live process.\n");
    }
    else
    {
        vmstat();
    }

    return Status;
}   // DECLARE_API( vmmap )

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function saves a dll to a file.                              *  
*                                                                      *
\**********************************************************************/
DECLARE_API(SaveModule)
{
    INIT_API();
    MINIDUMP_NOT_SUPPORTED();    

    StringHolder Location;
    DWORD_PTR moduleAddr = NULL;
    BOOL bIsImage;

    CMDValue arg[] = 
    {   // vptr, type
        {&moduleAddr, COHEX},
        {&Location.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg)) 
    {
        return Status;
    }
    if (nArg != 2)
    {
        ExtOut("Usage: SaveModule <address> <file to save>\n");
        return Status;
    }
    if (moduleAddr == 0) {
        ExtOut ("Invalid arg\n");
        return Status;
    }

    char* ptr = Location.data;
    
    DWORD_PTR dllBase = 0;
    ULONG64 base;
    if (g_ExtSymbols->GetModuleByOffset(TO_CDADDR(moduleAddr),0,NULL,&base) == S_OK)
    {
        dllBase = TO_TADDR(base);
    }
    else if (IsModule(moduleAddr))
    {        
        DacpModuleData module;
        module.Request(g_sos, TO_CDADDR(moduleAddr));
        dllBase = TO_TADDR(module.ilBase);
        if (dllBase == 0)
        {
            ExtOut ("Module does not have base address\n");
            return Status;
        }
    }
    else
    {
        ExtOut ("%p is not a Module or base address\n", SOS_PTR(moduleAddr));
        return Status;
    }

    MEMORY_BASIC_INFORMATION64 mbi;
    if (FAILED(g_ExtData2->QueryVirtual(TO_CDADDR(dllBase), &mbi)))
    {
        ExtOut("Failed to retrieve information about segment %p", SOS_PTR(dllBase));
        return Status;
    }

    // module loaded as an image or mapped as a flat file?
    bIsImage = (mbi.Type == MEM_IMAGE);

    IMAGE_DOS_HEADER DosHeader;
    if (g_ExtData->ReadVirtual(TO_CDADDR(dllBase), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
        return S_FALSE;

    IMAGE_NT_HEADERS Header;
    if (g_ExtData->ReadVirtual(TO_CDADDR(dllBase + DosHeader.e_lfanew), &Header, sizeof(Header), NULL) != S_OK)
        return S_FALSE;

    DWORD_PTR sectionAddr = dllBase + DosHeader.e_lfanew + offsetof(IMAGE_NT_HEADERS,OptionalHeader)
            + Header.FileHeader.SizeOfOptionalHeader;    

    IMAGE_SECTION_HEADER section;
    struct MemLocation
    {
        DWORD_PTR VAAddr;
        DWORD_PTR VASize;
        DWORD_PTR FileAddr;
        DWORD_PTR FileSize;
    };

    int nSection = Header.FileHeader.NumberOfSections;
    ExtOut("%u sections in file\n",nSection);
    MemLocation *memLoc = (MemLocation*)_alloca(nSection*sizeof(MemLocation));
    int indxSec = -1;
    int slot;
    for (int n = 0; n < nSection; n++)
    {
        if (g_ExtData->ReadVirtual(TO_CDADDR(sectionAddr), &section, sizeof(section), NULL) == S_OK)
        {
            for (slot = 0; slot <= indxSec; slot ++)
                if (section.PointerToRawData < memLoc[slot].FileAddr)
                    break;

            for (int k = indxSec; k >= slot; k --)
                memcpy(&memLoc[k+1], &memLoc[k], sizeof(MemLocation));

            memLoc[slot].VAAddr = section.VirtualAddress;
            memLoc[slot].VASize = section.Misc.VirtualSize;
            memLoc[slot].FileAddr = section.PointerToRawData;
            memLoc[slot].FileSize = section.SizeOfRawData;
            ExtOut("section %d - VA=%x, VASize=%x, FileAddr=%x, FileSize=%x\n",
                n, memLoc[slot].VAAddr,memLoc[slot]. VASize,memLoc[slot].FileAddr,
                memLoc[slot].FileSize);
            indxSec ++;
        }
        else
        {
            ExtOut("Fail to read PE section info\n");
            return Status;
        }
        sectionAddr += sizeof(section);
    }

    if (ptr[0] == '\0')
    {
        ExtOut ("File not specified\n");
        return Status;
    }

    PCSTR file = ptr;
    ptr += strlen(ptr)-1;
    while (isspace(*ptr))
    {
        *ptr = '\0';
        ptr --;
    }

    HANDLE hFile = CreateFileA(file,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,0,NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        ExtOut ("Fail to create file %s\n", file);
        return Status;
    }

    ULONG pageSize = OSPageSize();
    char *buffer = (char *)_alloca(pageSize);
    DWORD nRead;
    DWORD nWrite;
    
    // NT PE Headers
    TADDR dwAddr = dllBase;
    TADDR dwEnd = dllBase + Header.OptionalHeader.SizeOfHeaders;
    while (dwAddr < dwEnd)
    {
        nRead = pageSize;
        if (dwEnd - dwAddr < nRead)
            nRead = (ULONG)(dwEnd - dwAddr);

        if (g_ExtData->ReadVirtual(TO_CDADDR(dwAddr), buffer, nRead, &nRead) == S_OK)
        {
            WriteFile(hFile,buffer,nRead,&nWrite,NULL);
        }
        else
        {
            ExtOut ("Fail to read memory\n");
            goto end;
        }
        dwAddr += nRead;
    }

    for (slot = 0; slot <= indxSec; slot ++)
    {
        dwAddr = dllBase + (bIsImage ? memLoc[slot].VAAddr : memLoc[slot].FileAddr);
        dwEnd = memLoc[slot].FileSize + dwAddr - 1;

        while (dwAddr <= dwEnd)
        {
            nRead = pageSize;
            if (dwEnd - dwAddr + 1 < pageSize)
                nRead = (ULONG)(dwEnd - dwAddr + 1);
            
            if (g_ExtData->ReadVirtual(TO_CDADDR(dwAddr), buffer, nRead, &nRead) == S_OK)
            {
                WriteFile(hFile,buffer,nRead,&nWrite,NULL);
            }
            else
            {
                ExtOut ("Fail to read memory\n");
                goto end;
            }
            dwAddr += pageSize;
        }
    }
end:
    CloseHandle (hFile);
    return Status;
}

#ifdef _DEBUG
DECLARE_API(dbgout)
{
    INIT_API();

    BOOL bOff = FALSE;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-off", &bOff, COBOOL, FALSE},
    };

    if (!GetCMDOption(args, option, _countof(option), NULL, 0, NULL))
    {
        return Status;
    }    

    Output::SetDebugOutputEnabled(!bOff);
    return Status;
}
DECLARE_API(filthint)
{
    INIT_API();

    BOOL bOff = FALSE;
    DWORD_PTR filter = 0;

    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-off", &bOff, COBOOL, FALSE},
    };
    CMDValue arg[] = 
    {   // vptr, type
        {&filter, COHEX}
    };
    size_t nArg;
    if (!GetCMDOption(args, option, _countof(option),
                      arg, _countof(arg), &nArg)) 
    {
        return Status;
    }    
    if (bOff)
    {
        g_filterHint = 0;
        return Status;
    }

    g_filterHint = filter;
    return Status;
}
#endif // _DEBUG

#endif // FEATURE_PAL

static HRESULT DumpMDInfoBuffer(DWORD_PTR dwStartAddr, DWORD Flags, ULONG64 Esp, 
        ULONG64 IPAddr, StringOutput& so)
{
#define DOAPPEND(str)         \
    do { \
    if (!so.Append((str))) {  \
    return E_OUTOFMEMORY; \
    }} while (0)

    // Should we skip explicit frames?  They are characterized by Esp = 0, && Eip = 0 or 1.
    // See comment in FormatGeneratedException() for explanation why on non_IA64 Eip is 1, and not 0
    if (!(Flags & SOS_STACKTRACE_SHOWEXPLICITFRAMES) && (Esp == 0) && (IPAddr == 1))
    {
        return S_FALSE;
    }

    DacpMethodDescData MethodDescData;
    if (MethodDescData.Request(g_sos, TO_CDADDR(dwStartAddr)) != S_OK)
    {
        return E_FAIL;
    }

    ArrayHolder<WCHAR> wszNameBuffer = new WCHAR[MAX_LONGPATH+1];

    if (Flags & SOS_STACKTRACE_SHOWADDRESSES)
    {
        _snwprintf_s(wszNameBuffer, MAX_LONGPATH, MAX_LONGPATH, W("%p %p "), (void*)(size_t) Esp, (void*)(size_t) IPAddr); // _TRUNCATE
        DOAPPEND(wszNameBuffer);
    }

    DacpModuleData dmd;
    BOOL bModuleNameWorked = FALSE;
    ULONG64 addrInModule = IPAddr;
    if (dmd.Request(g_sos, MethodDescData.ModulePtr) == S_OK)
    {
        CLRDATA_ADDRESS base = 0;
        if (g_sos->GetPEFileBase(dmd.File, &base) == S_OK)
        {
            if (base)
            {
                addrInModule = base;
            }
        }
    }
    ULONG Index;
    ULONG64 base;
    if (g_ExtSymbols->GetModuleByOffset(UL64_TO_CDA(addrInModule), 0, &Index, &base) == S_OK)
    {                                    
        ArrayHolder<char> szModuleName = new char[MAX_LONGPATH+1];
        if (g_ExtSymbols->GetModuleNames(Index, base, NULL, 0, NULL, szModuleName, MAX_LONGPATH, NULL, NULL, 0, NULL) == S_OK)
        {
            MultiByteToWideChar (CP_ACP, 0, szModuleName, MAX_LONGPATH, wszNameBuffer, MAX_LONGPATH);
            DOAPPEND (wszNameBuffer);
            bModuleNameWorked = TRUE;
        }
    }
#ifdef FEATURE_PAL
    else
    {
        if (g_sos->GetPEFileName(dmd.File, MAX_LONGPATH, wszNameBuffer, NULL) == S_OK)
        {
            if (wszNameBuffer[0] != W('\0'))
            {
                WCHAR *pJustName = _wcsrchr(wszNameBuffer, DIRECTORY_SEPARATOR_CHAR_W);
                if (pJustName == NULL)
                    pJustName = wszNameBuffer - 1;

                DOAPPEND(pJustName + 1);
                bModuleNameWorked = TRUE;
            }
        }
    }
#endif // FEATURE_PAL

    // Under certain circumstances DacpMethodDescData::GetMethodDescName() 
    //   returns a module qualified method name
    HRESULT hr = g_sos->GetMethodDescName(dwStartAddr, MAX_LONGPATH, wszNameBuffer, NULL);

    WCHAR* pwszMethNameBegin = (hr != S_OK ? NULL : _wcschr(wszNameBuffer, L'!'));
    if (!bModuleNameWorked && hr == S_OK && pwszMethNameBegin != NULL)
    {
        // if we weren't able to get the module name, but GetMethodDescName returned
        // the module as part of the returned method name, use this data
        DOAPPEND(wszNameBuffer);
    }
    else
    {
        if (!bModuleNameWorked)
        {
            DOAPPEND (W("UNKNOWN"));
        }
        DOAPPEND(W("!"));
        if (hr == S_OK)
        {
            // the module name we retrieved above from debugger will take 
            // precedence over the name possibly returned by GetMethodDescName()
            DOAPPEND(pwszMethNameBegin != NULL ? (pwszMethNameBegin+1) : (WCHAR *)wszNameBuffer);
        }
        else
        {
            DOAPPEND(W("UNKNOWN"));
        }
    }

    ULONG64 Displacement = (IPAddr - MethodDescData.NativeCodeAddr);
    if (Displacement)
    {
        _snwprintf_s(wszNameBuffer, MAX_LONGPATH, MAX_LONGPATH, W("+%#x"), Displacement); // _TRUNCATE
        DOAPPEND (wszNameBuffer);
    }

    return S_OK;
#undef DOAPPEND
}

BOOL AppendContext(LPVOID pTransitionContexts, size_t maxCount, size_t *pcurCount, size_t uiSizeOfContext,
    CROSS_PLATFORM_CONTEXT *context)
{
    if (pTransitionContexts == NULL || *pcurCount >= maxCount)
    {
        ++(*pcurCount);
        return FALSE;
    }
    if (uiSizeOfContext == sizeof(StackTrace_SimpleContext))
    {
        StackTrace_SimpleContext *pSimple = (StackTrace_SimpleContext *) pTransitionContexts;
        g_targetMachine->FillSimpleContext(&pSimple[*pcurCount], context);
    }
    else if (uiSizeOfContext == g_targetMachine->GetContextSize())
    {
        // FillTargetContext ensures we only write uiSizeOfContext bytes in pTransitionContexts
        // and not sizeof(CROSS_PLATFORM_CONTEXT) bytes (which would overrun).
        g_targetMachine->FillTargetContext(pTransitionContexts, context, (int)(*pcurCount));
    }
    else
    {
        return FALSE;
    }
    ++(*pcurCount);
    return TRUE;
}

HRESULT CALLBACK ImplementEFNStackTrace(
    PDEBUG_CLIENT client,
    __out_ecount_opt(*puiTextLength) WCHAR wszTextOut[],
    size_t *puiTextLength,
    LPVOID pTransitionContexts,
    size_t *puiTransitionContextCount,
    size_t uiSizeOfContext,
    DWORD Flags) 
{

#define DOAPPEND(str) if (!so.Append((str))) { \
    Status = E_OUTOFMEMORY;                    \
    goto Exit;                                 \
}

    HRESULT Status = E_FAIL;    
    StringOutput so;
    size_t transitionContextCount = 0;

    if (puiTextLength == NULL)
    {
        return E_INVALIDARG;
    }

    if (pTransitionContexts)
    {
        if (puiTransitionContextCount == NULL)
        {
            return E_INVALIDARG;
        }

        // Do error checking on context size
        if ((uiSizeOfContext != g_targetMachine->GetContextSize()) &&
            (uiSizeOfContext != sizeof(StackTrace_SimpleContext)))
        {
            return E_INVALIDARG;
        }
    }

    IXCLRDataStackWalk *pStackWalk = NULL;
    IXCLRDataTask* Task;
    ULONG ThreadId;

    if ((Status = g_ExtSystem->GetCurrentThreadSystemId(&ThreadId)) != S_OK ||
        (Status = g_clrData->GetTaskByOSThreadID(ThreadId, &Task)) != S_OK)
    {
        // Not a managed thread.
        return SOS_E_NOMANAGEDCODE;
    }

    Status = Task->CreateStackWalk(CLRDATA_SIMPFRAME_UNRECOGNIZED |
                                   CLRDATA_SIMPFRAME_MANAGED_METHOD |
                                   CLRDATA_SIMPFRAME_RUNTIME_MANAGED_CODE |
                                   CLRDATA_SIMPFRAME_RUNTIME_UNMANAGED_CODE,
                                   &pStackWalk);

    Task->Release();

    if (Status != S_OK)
    {
        if (Status == E_FAIL)
        {
            return SOS_E_NOMANAGEDCODE;
        }
        return Status;
    }

#ifdef _TARGET_WIN64_
    ULONG numFrames = 0;
    BOOL bInNative = TRUE;

    Status = GetContextStackTrace(&numFrames);
    if (FAILED(Status))
    {
        goto Exit;
    }

    for (ULONG i = 0; i < numFrames; i++)
    {
        PDEBUG_STACK_FRAME pCur = g_Frames + i;                

        CLRDATA_ADDRESS pMD;
        if (g_sos->GetMethodDescPtrFromIP(pCur->InstructionOffset, &pMD) == S_OK)
        {
            if (bInNative || transitionContextCount==0)
            {
                // We only want to list one transition frame if there are multiple frames.
                bInNative = FALSE;

                DOAPPEND (W("(TransitionMU)\n"));
                // For each transition, we need to store the context information
                if (puiTransitionContextCount)
                {
                    // below we cast the i-th AMD64_CONTEXT to CROSS_PLATFORM_CONTEXT
                    AppendContext (pTransitionContexts, *puiTransitionContextCount, 
                        &transitionContextCount, uiSizeOfContext, (CROSS_PLATFORM_CONTEXT*)(&(g_X64FrameContexts[i])));
                }
                else
                {
                    transitionContextCount++;
                }
            }

            Status = DumpMDInfoBuffer((DWORD_PTR) pMD, Flags,
                    pCur->StackOffset, pCur->InstructionOffset, so);
            if (FAILED(Status))
            {
                goto Exit;
            }
            else if (Status == S_OK)
            {
                DOAPPEND (W("\n"));
            }
            // for S_FALSE do not append anything

        }        
        else
        {
            if (!bInNative)
            {
                // We only want to list one transition frame if there are multiple frames.
                bInNative = TRUE;

                DOAPPEND (W("(TransitionUM)\n"));
                // For each transition, we need to store the context information
                if (puiTransitionContextCount)
                {
                    AppendContext (pTransitionContexts, *puiTransitionContextCount, 
                        &transitionContextCount, uiSizeOfContext, (CROSS_PLATFORM_CONTEXT*)(&(g_X64FrameContexts[i])));
                }
                else
                {
                    transitionContextCount++;
                }
            }
        }
    }

Exit:
#else // _TARGET_WIN64_

#ifdef _DEBUG
    size_t prevLength = 0;
    static WCHAR wszNameBuffer[1024]; // should be large enough
    wcscpy_s(wszNameBuffer, 1024, W("Frame")); // default value
#endif

    BOOL bInNative = TRUE;

    UINT frameCount = 0;
    do
    {
        DacpFrameData FrameData;
        if ((Status = FrameData.Request(pStackWalk)) != S_OK)
        {
            goto Exit;
        }

        CROSS_PLATFORM_CONTEXT context;
        if ((Status=pStackWalk->GetContext(DT_CONTEXT_FULL, g_targetMachine->GetContextSize(),
                                           NULL, (BYTE *)&context))!=S_OK)
        {
            goto Exit;
        }

        ExtDbgOut ( " * Ctx[BSI]:  %08x  %08x  %08x    ", GetBP(context), GetSP(context), GetIP(context) );

        CLRDATA_ADDRESS pMD;
        if (!FrameData.frameAddr)
        {
            if (bInNative || transitionContextCount==0)
            {
                // We only want to list one transition frame if there are multiple frames.
                bInNative = FALSE;

                DOAPPEND (W("(TransitionMU)\n"));
                // For each transition, we need to store the context information
                if (puiTransitionContextCount)
                {
                    AppendContext (pTransitionContexts, *puiTransitionContextCount, 
                            &transitionContextCount, uiSizeOfContext, &context);
                }
                else
                {
                    transitionContextCount++;
                }                    
            }

            // we may have a method, try to get the methoddesc
            if (g_sos->GetMethodDescPtrFromIP(GetIP(context), &pMD)==S_OK)
            {
                Status = DumpMDInfoBuffer((DWORD_PTR) pMD, Flags, 
                                          GetSP(context), GetIP(context), so);
                if (FAILED(Status))
                {
                    goto Exit;
                }
                else if (Status == S_OK)
                {
                    DOAPPEND (W("\n"));
                }
                // for S_FALSE do not append anything
            }
        }
        else
        {
#ifdef _DEBUG
            if (Output::IsDebugOutputEnabled())
            {
                DWORD_PTR vtAddr;
                MOVE(vtAddr, TO_TADDR(FrameData.frameAddr));
                if (g_sos->GetFrameName(TO_CDADDR(vtAddr), 1024, wszNameBuffer, NULL) == S_OK)
                    ExtDbgOut("[%ls: %08x] ", wszNameBuffer, FrameData.frameAddr);  
                else
                    ExtDbgOut("[Frame: %08x] ", FrameData.frameAddr);
            }
#endif
            if (!bInNative)
            {
                // We only want to list one transition frame if there are multiple frames.
                bInNative = TRUE;

                DOAPPEND (W("(TransitionUM)\n"));
                // For each transition, we need to store the context information
                if (puiTransitionContextCount)
                {
                    AppendContext (pTransitionContexts, *puiTransitionContextCount, 
                            &transitionContextCount, uiSizeOfContext, &context);
                }
                else
                {
                    transitionContextCount++;
                }                    
            }
        }

#ifdef _DEBUG
        if (so.Length() > prevLength)
        {
            ExtDbgOut ( "%ls", so.String()+prevLength );
            prevLength = so.Length();
        }
        else
            ExtDbgOut ( "\n" );
#endif

    } 
    while ((frameCount++) < MAX_STACK_FRAMES && pStackWalk->Next()==S_OK);
    
    Status = S_OK;

Exit:
#endif // _TARGET_WIN64_

    if (pStackWalk)
    {
        pStackWalk->Release();
        pStackWalk = NULL;
    }

    // We have finished. Does the user want to copy this data to a buffer?
    if (Status == S_OK)
    {
        if(wszTextOut)
        {
            // They want at least partial output
            wcsncpy_s (wszTextOut, *puiTextLength, so.String(),  *puiTextLength-1); // _TRUNCATE
        }
        else
        {
            *puiTextLength = _wcslen (so.String()) + 1;
        }

        if (puiTransitionContextCount)
        {
            *puiTransitionContextCount = transitionContextCount;
        }
    }

    return Status;
}

#ifdef FEATURE_PAL
#define PAL_TRY_NAKED PAL_CPP_TRY
#define PAL_EXCEPT_NAKED(disp) PAL_CPP_CATCH_ALL
#define PAL_ENDTRY_NAKED PAL_CPP_ENDTRY
#endif

// TODO: Convert PAL_TRY_NAKED to something that works on the Mac.
HRESULT CALLBACK ImplementEFNStackTraceTry(
    PDEBUG_CLIENT client,
    __out_ecount_opt(*puiTextLength) WCHAR wszTextOut[],
    size_t *puiTextLength,
    LPVOID pTransitionContexts,
    size_t *puiTransitionContextCount,
    size_t uiSizeOfContext,
    DWORD Flags) 
{
    HRESULT Status = E_FAIL;

    PAL_TRY_NAKED
    {
        Status = ImplementEFNStackTrace(client, wszTextOut, puiTextLength, 
            pTransitionContexts, puiTransitionContextCount,
            uiSizeOfContext, Flags);
    }
    PAL_EXCEPT_NAKED (EXCEPTION_EXECUTE_HANDLER)
    {
    }        
    PAL_ENDTRY_NAKED

    return Status;
}

// See sos_stacktrace.h for the contract with the callers regarding the LPVOID arguments.
HRESULT CALLBACK _EFN_StackTrace(
    PDEBUG_CLIENT client,
    __out_ecount_opt(*puiTextLength) WCHAR wszTextOut[],
    size_t *puiTextLength,
    __out_bcount_opt(uiSizeOfContext*(*puiTransitionContextCount)) LPVOID pTransitionContexts,
    size_t *puiTransitionContextCount,
    size_t uiSizeOfContext,
    DWORD Flags) 
{
    INIT_API();    

    Status = ImplementEFNStackTraceTry(client, wszTextOut, puiTextLength, 
        pTransitionContexts, puiTransitionContextCount,
        uiSizeOfContext, Flags);

    return Status;
}


BOOL FormatFromRemoteString(DWORD_PTR strObjPointer, __out_ecount(cchString) PWSTR wszBuffer, ULONG cchString)
{
    BOOL bRet = FALSE;

    wszBuffer[0] = L'\0';
    
    DacpObjectData objData;
    if (objData.Request(g_sos, TO_CDADDR(strObjPointer))!=S_OK)
    {
        return bRet;
    }

    strobjInfo stInfo;

    if (MOVE(stInfo, strObjPointer) != S_OK)
    {
        return bRet;
    }
    
    DWORD dwBufLength = 0;
    if (!ClrSafeInt<DWORD>::addition(stInfo.m_StringLength, 1, dwBufLength))
    {
        ExtOut("<integer overflow>\n");
        return bRet;
    }

    LPWSTR pwszBuf = new NOTHROW WCHAR[dwBufLength];
    if (pwszBuf == NULL)
    {
        return bRet;
    }
    
    if (g_sos->GetObjectStringData(TO_CDADDR(strObjPointer), stInfo.m_StringLength+1, pwszBuf, NULL)!=S_OK)
    {
        delete [] pwszBuf;
        return bRet;
    }

    // String is in format
    // <SP><SP><SP>at <function name>(args,...)\n
    // ...
    // Parse and copy just <function name>(args,...)

    LPWSTR pwszPointer = pwszBuf;

    WCHAR PSZSEP[] = W("   at ");

    UINT Length = 0;
    while(1)
    {
        if (_wcsncmp(pwszPointer, PSZSEP, _countof(PSZSEP)-1) != 0)
        {
            delete [] pwszBuf;
            return bRet;
        }

        pwszPointer += _wcslen(PSZSEP);
        LPWSTR nextPos = _wcsstr(pwszPointer, PSZSEP);
        if (nextPos == NULL)
        {
            // Done! Note that we are leaving the function before we add the last
            // line of stack trace to the output string. This is on purpose because
            // this string needs to be merged with a real trace, and the last line
            // of the trace will be common to the real trace.
            break;
        }
        WCHAR c = *nextPos;
        *nextPos = L'\0';

        // Buffer is calculated for sprintf below ("   %p %p %S\n");
        WCHAR wszLineBuffer[mdNameLen + 8 + sizeof(size_t)*2];

        // Note that we don't add a newline because we have this embedded in wszLineBuffer
        swprintf_s(wszLineBuffer, _countof(wszLineBuffer), W("    %p %p %s"), (void*)(size_t)-1, (void*)(size_t)-1, pwszPointer);
        Length += (UINT)_wcslen(wszLineBuffer);
        
        if (wszBuffer)
        {            
            wcsncat_s(wszBuffer, cchString, wszLineBuffer, _TRUNCATE);
        }

        *nextPos = c;
        // Move to the next line.
        pwszPointer = nextPos;
    }
    
    delete [] pwszBuf; 

    // Return TRUE only if the stack string had any information that was successfully parsed.
    // (Length > 0) is a good indicator of that.
    bRet = (Length > 0);
    return bRet;
}

HRESULT AppendExceptionInfo(CLRDATA_ADDRESS cdaObj, 
    __out_ecount(cchString) PWSTR wszStackString,
    ULONG cchString,
    BOOL bNestedCase) // If bNestedCase is TRUE, the last frame of the computed stack is left off
{    
    DacpObjectData objData;
    if (objData.Request(g_sos, cdaObj) != S_OK)
    {        
        return E_FAIL;
    }

    // Make sure it is an exception object, and get the MT of Exception
    CLRDATA_ADDRESS exceptionMT = isExceptionObj(objData.MethodTable);
    if (exceptionMT == NULL)
    {
        return E_INVALIDARG;
    }

    // First try to get exception object data using ISOSDacInterface2
    DacpExceptionObjectData excData;
    BOOL bGotExcData = SUCCEEDED(excData.Request(g_sos, cdaObj));

    int iOffset;    
    // Is there a _remoteStackTraceString? We'll want to prepend that data.
    // We only have string data, so IP/SP info has to be set to -1.
    DWORD_PTR strPointer;
    if (bGotExcData)
    {
        strPointer = TO_TADDR(excData.RemoteStackTraceString);
    }
    else
    {
        iOffset = GetObjFieldOffset (cdaObj, objData.MethodTable, W("_remoteStackTraceString"));
        MOVE (strPointer, TO_TADDR(cdaObj) + iOffset);        
    }
    if (strPointer)
    {
        WCHAR *pwszBuffer = new NOTHROW WCHAR[cchString];
        if (pwszBuffer == NULL)
        {
            return E_OUTOFMEMORY;
        }
        
        if (FormatFromRemoteString(strPointer, pwszBuffer, cchString))
        {
            // Prepend this stuff to the string for the user
            wcsncat_s(wszStackString, cchString, pwszBuffer, _TRUNCATE);
        }
        delete[] pwszBuffer;
    }
    
    BOOL bAsync = bGotExcData ? IsAsyncException(excData)
                              : IsAsyncException(TO_TADDR(cdaObj), TO_TADDR(objData.MethodTable));

    DWORD_PTR arrayPtr;
    if (bGotExcData)
    {
        arrayPtr = TO_TADDR(excData.StackTrace);
    }
    else
    {
        iOffset = GetObjFieldOffset (cdaObj, objData.MethodTable, W("_stackTrace"));
        MOVE (arrayPtr, TO_TADDR(cdaObj) + iOffset);
    }

    if (arrayPtr)
    {
        DWORD arrayLen;
        MOVE (arrayLen, arrayPtr + sizeof(DWORD_PTR));

        if (arrayLen)
        {
#ifdef _TARGET_WIN64_
            DWORD_PTR dataPtr = arrayPtr + sizeof(DWORD_PTR) + sizeof(DWORD) + sizeof(DWORD);
#else
            DWORD_PTR dataPtr = arrayPtr + sizeof(DWORD_PTR) + sizeof(DWORD);
#endif // _TARGET_WIN64_
            size_t stackTraceSize = 0;
            MOVE (stackTraceSize, dataPtr); // data length is stored at the beginning of the array in this case

            DWORD cbStackSize = static_cast<DWORD>(stackTraceSize * sizeof(StackTraceElement));
            dataPtr += sizeof(size_t) + sizeof(size_t); // skip the array header, then goes the data
            
            if (stackTraceSize != 0)
            {                
                size_t iLength = FormatGeneratedException (dataPtr, cbStackSize, NULL, 0, bAsync, bNestedCase);
                WCHAR *pwszBuffer = new NOTHROW WCHAR[iLength + 1];
                if (pwszBuffer)
                {
                    FormatGeneratedException(dataPtr, cbStackSize, pwszBuffer, iLength + 1, bAsync, bNestedCase);
                    wcsncat_s(wszStackString, cchString, pwszBuffer, _TRUNCATE);
                    delete[] pwszBuffer;
                }
                else
                {
                    return E_OUTOFMEMORY;
                }
            }
        }
    }                   
    return S_OK;
}

HRESULT ImplementEFNGetManagedExcepStack(
    CLRDATA_ADDRESS cdaStackObj, 
    __out_ecount(cchString) PWSTR wszStackString,
    ULONG cchString)
{
    HRESULT Status = E_FAIL;

    if (wszStackString == NULL || cchString == 0)
    {
        return E_INVALIDARG;
    }

    CLRDATA_ADDRESS threadAddr = GetCurrentManagedThread();
    DacpThreadData Thread;
    BOOL bCanUseThreadContext = TRUE;

    ZeroMemory(&Thread, sizeof(DacpThreadData));
    
    if ((threadAddr == NULL) || (Thread.Request(g_sos, threadAddr) != S_OK))
    {
        // The current thread is unmanaged
        bCanUseThreadContext = FALSE;
    }

    if (cdaStackObj == NULL)    
    {
        if (!bCanUseThreadContext)
        {
            return E_INVALIDARG;
        }
        
        TADDR taLTOH = NULL;
        if ((!SafeReadMemory(TO_TADDR(Thread.lastThrownObjectHandle),
                            &taLTOH,
                            sizeof(taLTOH), NULL)) || (taLTOH==NULL))
        {
            return Status;
        }    
        else
        {        
            cdaStackObj = TO_CDADDR(taLTOH);
        }
    }

    // Put the stack trace header on
    AddExceptionHeader(wszStackString, cchString);
    
    // First is there a nested exception?
    if (bCanUseThreadContext && Thread.firstNestedException)    
    {
        CLRDATA_ADDRESS obj = 0, next = 0;
        CLRDATA_ADDRESS currentNested = Thread.firstNestedException;
        do
        {
            Status = g_sos->GetNestedExceptionData(currentNested, &obj, &next);

            // deal with the inability to read a nested exception gracefully
            if (Status != S_OK)
            {
                break;
            }
                        
            Status = AppendExceptionInfo(obj, wszStackString, cchString, TRUE);
            currentNested = next;
        }
        while(currentNested != NULL);                        
    }
    
    Status = AppendExceptionInfo(cdaStackObj, wszStackString, cchString, FALSE);

    return Status;
}

// TODO: Enable this when ImplementEFNStackTraceTry is fixed.
// This function, like VerifyDAC, exists for the purpose of testing
// hard-to-get-to SOS APIs.
DECLARE_API(VerifyStackTrace)
{
    INIT_API();

    BOOL bVerifyManagedExcepStack = FALSE;
    CMDOption option[] = 
    {   // name, vptr, type, hasValue
        {"-ManagedExcepStack", &bVerifyManagedExcepStack, COBOOL, FALSE},
    };
    
    if (!GetCMDOption(args, option, _countof(option), NULL,0,NULL)) 
    {
        return Status;
    }

    if (bVerifyManagedExcepStack)
    {
        CLRDATA_ADDRESS threadAddr = GetCurrentManagedThread();
        DacpThreadData Thread;

        TADDR taExc = NULL;
        if ((threadAddr == NULL) || (Thread.Request(g_sos, threadAddr) != S_OK))
        {
            ExtOut("The current thread is unmanaged\n");
            return Status;
        }

        TADDR taLTOH = NULL;
        if ((!SafeReadMemory(TO_TADDR(Thread.lastThrownObjectHandle),
                            &taLTOH,
                            sizeof(taLTOH), NULL)) || (taLTOH == NULL))
        {
            ExtOut("There is no current managed exception on this thread\n");            
            return Status;
        }    
        else
        {        
            taExc = taLTOH;
        }

        const SIZE_T cchStr = 4096;
        WCHAR *wszStr = (WCHAR *)alloca(cchStr * sizeof(WCHAR));
        if (ImplementEFNGetManagedExcepStack(TO_CDADDR(taExc), wszStr, cchStr) != S_OK)
        {
            ExtOut("Error!\n");
            return Status;
        }

        ExtOut("_EFN_GetManagedExcepStack(%P, wszStr, sizeof(wszStr)) returned:\n", SOS_PTR(taExc));
        ExtOut("%S\n", wszStr);

        if (ImplementEFNGetManagedExcepStack((ULONG64)NULL, wszStr, cchStr) != S_OK)
        {
            ExtOut("Error!\n");
            return Status;
        }

        ExtOut("_EFN_GetManagedExcepStack(NULL, wszStr, sizeof(wszStr)) returned:\n");
        ExtOut("%S\n", wszStr);
    }
    else
    {
        size_t textLength = 0;
        size_t contextLength = 0;
        Status = ImplementEFNStackTraceTry(client,
                                 NULL,
                                 &textLength,
                                 NULL,
                                 &contextLength,
                                 0,
                                 0);

        if (Status != S_OK)
        {
            ExtOut("Error: %lx\n", Status);
            return Status;
        }

        ExtOut("Number of characters requested: %d\n", textLength);
        WCHAR *wszBuffer = new NOTHROW WCHAR[textLength + 1];
        if (wszBuffer == NULL)
        {
            ReportOOM();
            return Status;
        }

        // For the transition contexts buffer the callers are expected to allocate 
        // contextLength * sizeof(TARGET_CONTEXT), and not
        // contextLength * sizeof(CROSS_PLATFORM_CONTEXT). See sos_stacktrace.h for
        // details.
        LPBYTE pContexts = new NOTHROW BYTE[contextLength * g_targetMachine->GetContextSize()];

        if (pContexts == NULL)
        {
            ReportOOM();
            delete[] wszBuffer;
            return Status;
        }

        Status = ImplementEFNStackTrace(client,
                                 wszBuffer,
                                 &textLength,
                                 pContexts,
                                 &contextLength,
                                 g_targetMachine->GetContextSize(),
                                 0);

        if (Status != S_OK)
        {
            ExtOut("Error: %lx\n", Status);
            delete[] wszBuffer;
            delete [] pContexts;
            return Status;
        }

        ExtOut("%S\n", wszBuffer);

        ExtOut("Context information:\n");
        if (IsDbgTargetX86())
        {
            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                   "Ebp", "Esp", "Eip"); 
        }
        else if (IsDbgTargetAmd64())
        {
            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                   "Rbp", "Rsp", "Rip"); 
        }
        else if (IsDbgTargetArm())
        {
            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                   "FP", "SP", "PC"); 
        }
        else
        {
            ExtOut("Unsupported platform");
            delete [] pContexts;
            delete[] wszBuffer;
            return S_FALSE;
        }

        for (size_t j=0; j < contextLength; j++)
        {
            CROSS_PLATFORM_CONTEXT *pCtx = (CROSS_PLATFORM_CONTEXT*)(pContexts + j*g_targetMachine->GetContextSize());
            ExtOut("%p %p %p\n", GetBP(*pCtx), GetSP(*pCtx), GetIP(*pCtx));
        }

        delete [] pContexts;

        StackTrace_SimpleContext *pSimple = new NOTHROW StackTrace_SimpleContext[contextLength];
        if (pSimple == NULL)
        {
            ReportOOM();
            delete[] wszBuffer;
            return Status;
        }

        Status = ImplementEFNStackTrace(client,
                                 wszBuffer,
                                 &textLength,
                                 pSimple,
                                 &contextLength,
                                 sizeof(StackTrace_SimpleContext),
                                 0);

        if (Status != S_OK)
        {
            ExtOut("Error: %lx\n", Status);
            delete[] wszBuffer;
            delete [] pSimple;
            return Status;
        }

        ExtOut("Simple Context information:\n");
        if (IsDbgTargetX86())
            ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                       "Ebp", "Esp", "Eip"); 
        else if (IsDbgTargetAmd64())
                ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                       "Rbp", "Rsp", "Rip"); 
        else if (IsDbgTargetArm())
                ExtOut("%" POINTERSIZE "s %" POINTERSIZE "s %" POINTERSIZE "s\n",
                       "FP", "SP", "PC"); 
        else 
        {
            ExtOut("Unsupported platform");
            delete[] wszBuffer;
            delete [] pSimple;
            return S_FALSE;
        }
        for (size_t j=0; j < contextLength; j++)
        {
            ExtOut("%p %p %p\n", SOS_PTR(pSimple[j].FrameOffset),
                    SOS_PTR(pSimple[j].StackOffset),
                    SOS_PTR(pSimple[j].InstructionOffset));
        }
        delete [] pSimple;
        delete[] wszBuffer;
    }

    return Status;
}

#ifndef FEATURE_PAL

// This is an internal-only Apollo extension to de-optimize the code
DECLARE_API(SuppressJitOptimization)
{
    INIT_API_NOEE();    
    MINIDUMP_NOT_SUPPORTED();    

    StringHolder onOff;
    CMDValue arg[] = 
    {   // vptr, type
        {&onOff.data, COSTRING},
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg)) 
    {
        return E_FAIL;
    }

    if(nArg == 1 && (_stricmp(onOff.data, "On") == 0))
    {
        // if CLR is already loaded, try to change the flags now
        if(CheckEEDll() == S_OK)
        {
            SetNGENCompilerFlags(CORDEBUG_JIT_DISABLE_OPTIMIZATION);
        }

        if(!g_fAllowJitOptimization)
            ExtOut("JIT optimization is already suppressed\n");
        else
        {
            g_fAllowJitOptimization = FALSE;
            g_ExtControl->Execute(DEBUG_EXECUTE_NOT_LOGGED, "sxe -c \"!HandleCLRN\" clrn", 0);
            ExtOut("JIT optimization will be suppressed\n");
        }


    }
    else if(nArg == 1 && (_stricmp(onOff.data, "Off") == 0))
    {
        // if CLR is already loaded, try to change the flags now
        if(CheckEEDll() == S_OK)
        {
            SetNGENCompilerFlags(CORDEBUG_JIT_DEFAULT);
        }

        if(g_fAllowJitOptimization)
            ExtOut("JIT optimization is already permitted\n");
        else
        {
            g_fAllowJitOptimization = TRUE;
            ExtOut("JIT optimization will be permitted\n");
        }
    }
    else
    {
        ExtOut("Usage: !SuppressJitOptimization <on|off>\n");
    }

    return S_OK;
}

// Uses ICorDebug to set the state of desired NGEN compiler flags. This can suppress pre-jitted optimized
// code
HRESULT SetNGENCompilerFlags(DWORD flags)
{
    HRESULT hr;

    ToRelease<ICorDebugProcess2> proc2;
    if(FAILED(hr = InitCorDebugInterface()))
    {
        ExtOut("SOS: warning, prejitted code optimizations could not be changed. Failed to load ICorDebug HR = 0x%x\n", hr);
    }
    else if(FAILED(g_pCorDebugProcess->QueryInterface(__uuidof(ICorDebugProcess2), (void**) &proc2)))
    {
        if(flags != CORDEBUG_JIT_DEFAULT)
        {
            ExtOut("SOS: warning, prejitted code optimizations could not be changed. This CLR version doesn't support the functionality\n");
        }
        else
        {
            hr = S_OK;
        }
    }
    else if(FAILED(hr = proc2->SetDesiredNGENCompilerFlags(flags)))
    {
        // Versions of CLR that don't have SetDesiredNGENCompilerFlags DAC-ized will return E_FAIL.
        // This was first supported in the clr_triton branch around 4/1/12, Apollo release
        // It will likely be supported in desktop CLR during Dev12
        if(hr == E_FAIL)
        {
            if(flags != CORDEBUG_JIT_DEFAULT)
            {
                ExtOut("SOS: warning, prejitted code optimizations could not be changed. This CLR version doesn't support the functionality\n");
            }
            else
            {
                hr = S_OK;
            }
        }
        else if(hr == CORDBG_E_NGEN_NOT_SUPPORTED)
        {
            if(flags != CORDEBUG_JIT_DEFAULT)
            {
                ExtOut("SOS: warning, prejitted code optimizations could not be changed. This CLR version doesn't support NGEN\n");
            }
            else
            {
                hr = S_OK;
            }
        }
        else if(hr == CORDBG_E_MUST_BE_IN_CREATE_PROCESS)
        {
            DWORD currentFlags = 0;
            if(FAILED(hr = proc2->GetDesiredNGENCompilerFlags(&currentFlags)))
            {
                ExtOut("SOS: warning, prejitted code optimizations could not be changed. GetDesiredNGENCompilerFlags failed hr=0x%x\n", hr);
            }
            else if(currentFlags != flags)
            {
                ExtOut("SOS: warning, prejitted code optimizations could not be changed at this time. This setting is fixed once CLR starts\n");
            }
            else
            {
                hr = S_OK;
            }
        }
        else
        {
            ExtOut("SOS: warning, prejitted code optimizations could not be changed at this time. SetDesiredNGENCompilerFlags hr = 0x%x\n", hr);
        }
    }

    return hr;
}


// This is an internal-only Apollo extension to save breakpoint/watch state
DECLARE_API(SaveState)
{
    INIT_API_NOEE();    
    MINIDUMP_NOT_SUPPORTED();    

    StringHolder filePath;
    CMDValue arg[] = 
    {   // vptr, type
        {&filePath.data, COSTRING},
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg)) 
    {
        return E_FAIL;
    }

    if(nArg == 0)
    {
        ExtOut("Usage: !SaveState <file_path>\n");
    }

    FILE* pFile;
    errno_t error = fopen_s(&pFile, filePath.data, "w");
    if(error != 0)
    {
        ExtOut("Failed to open file %s, error=0x%x\n", filePath.data, error);
        return E_FAIL;
    }

    g_bpoints.SaveBreakpoints(pFile);
    g_watchCmd.SaveListToFile(pFile);

    fclose(pFile);
    ExtOut("Session breakpoints and watch expressions saved to %s\n", filePath.data);
    return S_OK;
}

#endif // FEATURE_PAL

DECLARE_API(StopOnCatch)
{
    INIT_API();    
    MINIDUMP_NOT_SUPPORTED();    

    g_stopOnNextCatch = TRUE;
    ULONG32 flags = 0;
    g_clrData->GetOtherNotificationFlags(&flags);
    flags |= CLRDATA_NOTIFY_ON_EXCEPTION_CATCH_ENTER;
    g_clrData->SetOtherNotificationFlags(flags);
    ExtOut("Debuggee will break the next time a managed exception is caught during execution\n");
    return S_OK;
}

// This is an undocumented SOS extension command intended to help test SOS
// It causes the Dml output to be printed to the console uninterpretted so
// that a test script can read the commands which are hidden in the markup
DECLARE_API(ExposeDML)
{
    Output::SetDMLExposed(true);
    return S_OK;
}

// According to kksharma the Windows debuggers always sign-extend
// arguments when calling externally, therefore StackObjAddr 
// conforms to CLRDATA_ADDRESS contract.
HRESULT CALLBACK 
_EFN_GetManagedExcepStack(
    PDEBUG_CLIENT client,
    ULONG64 StackObjAddr,
   __out_ecount (cbString) PSTR szStackString,
    ULONG cbString
    )
{
    INIT_API();

    ArrayHolder<WCHAR> tmpStr = new NOTHROW WCHAR[cbString];
    if (tmpStr == NULL)
    {
        ReportOOM();
        return E_OUTOFMEMORY;
    }

    if (FAILED(Status = ImplementEFNGetManagedExcepStack(StackObjAddr, tmpStr, cbString)))
    {
        return Status;
    }

    if (WideCharToMultiByte(CP_ACP, WC_NO_BEST_FIT_CHARS, tmpStr, -1, szStackString, cbString, NULL, NULL) == 0)
    {
        return E_FAIL;
    }

    return S_OK;
}

// same as _EFN_GetManagedExcepStack, but returns the stack as a wide string.
HRESULT CALLBACK
_EFN_GetManagedExcepStackW(
    PDEBUG_CLIENT client,
    ULONG64 StackObjAddr,
    __out_ecount(cchString) PWSTR wszStackString,
    ULONG cchString
    )
{
    INIT_API();

    return ImplementEFNGetManagedExcepStack(StackObjAddr, wszStackString, cchString);
}
    
// According to kksharma the Windows debuggers always sign-extend
// arguments when calling externally, therefore objAddr 
// conforms to CLRDATA_ADDRESS contract.
HRESULT CALLBACK 
_EFN_GetManagedObjectName(
    PDEBUG_CLIENT client,
    ULONG64 objAddr,
    __out_ecount (cbName) PSTR szName,
    ULONG cbName
    )
{
    INIT_API ();

    if (!sos::IsObject(objAddr, false))
    {
        return E_INVALIDARG;
    }

    sos::Object obj = TO_TADDR(objAddr);

    if (WideCharToMultiByte(CP_ACP, 0, obj.GetTypeName(), (int) (_wcslen(obj.GetTypeName()) + 1),
                            szName, cbName, NULL, NULL) == 0)
    {
        return E_FAIL;
    }
    return S_OK;
}

// According to kksharma the Windows debuggers always sign-extend
// arguments when calling externally, therefore objAddr 
// conforms to CLRDATA_ADDRESS contract.
HRESULT CALLBACK 
_EFN_GetManagedObjectFieldInfo(
    PDEBUG_CLIENT client,
    ULONG64 objAddr,
    __out_ecount (mdNameLen) PSTR szFieldName,
    PULONG64 pValue,
    PULONG pOffset
    )
{
    INIT_API();
    DacpObjectData objData;
    LPWSTR fieldName = (LPWSTR)alloca(mdNameLen * sizeof(WCHAR));
    
    if (szFieldName == NULL || *szFieldName == '\0' ||
        objAddr == NULL)
    {
        return E_FAIL;
    }

    if (pOffset == NULL && pValue == NULL)
    {
        // One of these needs to be valid
        return E_FAIL;
    }
        
    if (FAILED(objData.Request(g_sos, objAddr)))
    {        
        return E_FAIL;
    }
    
    MultiByteToWideChar(CP_ACP,0,szFieldName,-1,fieldName,mdNameLen);

    int iOffset = GetObjFieldOffset (objAddr, objData.MethodTable, fieldName);
    if (iOffset <= 0)
    {
        return E_FAIL;
    }

    if (pOffset)
    {
        *pOffset = (ULONG) iOffset;
    }

    if (pValue)
    {
        if (FAILED(g_ExtData->ReadVirtual(UL64_TO_CDA(objAddr + iOffset), pValue, sizeof(ULONG64), NULL)))
        {
            return E_FAIL;
        }
    }

    return S_OK;
}

void PrintHelp (__in_z LPCSTR pszCmdName)
{
    static LPSTR pText = NULL;

    if (pText == NULL) {
#ifndef FEATURE_PAL
        HGLOBAL hResource = NULL;
        HRSRC hResInfo = FindResource (g_hInstance, TEXT ("DOCUMENTATION"), TEXT ("TEXT"));
        if (hResInfo) hResource = LoadResource (g_hInstance, hResInfo);
        if (hResource) pText = (LPSTR) LockResource (hResource); 
        if (pText == NULL)
        {
            ExtOut("Error loading documentation resource\n");
            return;
        }
#else
        int err = PAL_InitializeDLL();
        if(err != 0)
        {
            ExtOut("Error initializing PAL\n");
            return;
        }
        char lpFilename[MAX_LONGPATH + 12]; // + 12 to make enough room for strcat function.
        strcpy_s(lpFilename, _countof(lpFilename), g_ExtServices->GetCoreClrDirectory());
        strcat_s(lpFilename, _countof(lpFilename), "sosdocsunix.txt");
        
        HANDLE hSosDocFile = CreateFileA(lpFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
        if (hSosDocFile == INVALID_HANDLE_VALUE) {
            ExtOut("Error finding documentation file\n");
            return;
        }

        HANDLE hMappedSosDocFile = CreateFileMappingA(hSosDocFile, NULL, PAGE_READONLY, 0, 0, NULL);
        CloseHandle(hSosDocFile);
        if (hMappedSosDocFile == NULL) { 
            ExtOut("Error mapping documentation file\n");
            return;
        }

        pText = (LPSTR)MapViewOfFile(hMappedSosDocFile, FILE_MAP_READ, 0, 0, 0);
        CloseHandle(hMappedSosDocFile);
        if (pText == NULL)
        {
            ExtOut("Error loading documentation file\n");
            return;
        }
#endif
    }

    // Find our line in the text file
    char searchString[MAX_LONGPATH];
    sprintf_s(searchString, _countof(searchString), "COMMAND: %s.", pszCmdName);
    
    LPSTR pStart = strstr(pText, searchString);
    LPSTR pEnd = NULL;
    if (!pStart)
    {
        ExtOut("Documentation for %s not found.\n", pszCmdName);
        return;
    }

    // Go to the end of this line:
    pStart = strchr(pStart, '\n');
    if (!pStart)
    {
        ExtOut("Expected newline in documentation resource.\n");
        return;
    }

    // Bypass the newline that pStart points to and setup pEnd for the loop below. We set
    // pEnd to be the old pStart since we add one to it when we call strstr.
    pEnd = pStart++;

    // Find the first occurrence of \\ followed by an \r or an \n on a line by itself.
    do
    {
        pEnd = strstr(pEnd+1, "\\\\");
    } while (pEnd && ((pEnd[-1] != '\r' && pEnd[-1] != '\n') || (pEnd[3] != '\r' && pEnd[3] != '\n')));

    if (pEnd)
    {
        // We have found a \\ followed by a \r or \n.  Do not print out the character pEnd points
        // to, as this will be the first \ (this is why we don't add one to the second parameter).
        ExtOut("%.*s", pEnd - pStart, pStart);
    }
    else
    {
        // If pEnd is false then we have run to the end of the document.  However, we did find
        // the command to print, so we should simply print to the end of the file.  We'll add
        // an extra newline here in case the file does not contain one.
        ExtOut("%s\n", pStart);
    }
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function displays the commands available in strike and the   *  
*    arguments passed into each.
*                                                                      *
\**********************************************************************/
DECLARE_API(Help)
{
    // Call extension initialization functions directly, because we don't need the DAC dll to be initialized to get help.
    HRESULT Status;
    __ExtensionCleanUp __extensionCleanUp;
    if ((Status = ExtQuery(client)) != S_OK) return Status;
    ControlC = FALSE;

    StringHolder commandName;
    CMDValue arg[] = 
    {
        {&commandName.data, COSTRING}
    };
    size_t nArg;
    if (!GetCMDOption(args, NULL, 0, arg, _countof(arg), &nArg))
    {
        return Status;
    }

    ExtOut("-------------------------------------------------------------------------------\n");

    if (nArg == 1)
    {        
        // Convert commandName to lower-case
        LPSTR curChar = commandName.data;
        while (*curChar != '\0')
        {
            if ( ((unsigned) *curChar <= 0x7F) && isupper(*curChar))
            {
                *curChar = (CHAR) tolower(*curChar);
            }
            curChar++;
        }

        // Strip off leading "!" if the user put that.
        curChar = commandName.data;
        if (*curChar == '!')
            curChar++;
        
        PrintHelp (curChar);
    }
    else
    {
        PrintHelp ("contents");
    }
    
    return S_OK;
}