summaryrefslogtreecommitdiff
path: root/src/ToolBox/SOS/Strike/util.cpp
blob: 9eec76e42c9e41014bab3b93e45a13c173da745d (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
// 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.

// ==++==
// 

// 
// ==--==
#include "sos.h"
#include "disasm.h"
#include <dbghelp.h>

#include "corhdr.h"
#include "cor.h"
#include "dacprivate.h"
#include "sospriv.h"
#include "corerror.h"
#include "safemath.h"

#include <psapi.h>
#include <cordebug.h>
#include <xcordebug.h>
#include <metahost.h>
#include <mscoree.h>
#include <tchar.h>
#include "debugshim.h"

#ifdef FEATURE_PAL
#include "datatarget.h"
#endif // FEATURE_PAL
#include "gcinfo.h"

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

#ifndef FEATURE_PAL
#define MAX_SYMBOL_LEN 4096
#define SYM_BUFFER_SIZE (sizeof(IMAGEHLP_SYMBOL) + MAX_SYMBOL_LEN)
char symBuffer[SYM_BUFFER_SIZE];
PIMAGEHLP_SYMBOL sym = (PIMAGEHLP_SYMBOL) symBuffer;
#else
#include <sys/stat.h>
#include <coreruncommon.h>
#include <dlfcn.h>
#endif // !FEATURE_PAL

#include <coreclrhost.h>
#include <set>

LoadSymbolsForModuleDelegate SymbolReader::loadSymbolsForModuleDelegate;
DisposeDelegate SymbolReader::disposeDelegate;
ResolveSequencePointDelegate SymbolReader::resolveSequencePointDelegate;
GetLocalVariableName SymbolReader::getLocalVariableNameDelegate;
GetLineByILOffsetDelegate SymbolReader::getLineByILOffsetDelegate;

const char * const CorElementTypeName[ELEMENT_TYPE_MAX]=
{
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv)    c,
#include "cortypeinfo.h"
#undef TYPEINFO
};

const char * const CorElementTypeNamespace[ELEMENT_TYPE_MAX]=
{
#define TYPEINFO(e,ns,c,s,g,ia,ip,if,im,gv)    ns,
#include "cortypeinfo.h"
#undef TYPEINFO
};

IXCLRDataProcess *g_clrData = NULL;
ISOSDacInterface *g_sos = NULL;
ICorDebugProcess *g_pCorDebugProcess = NULL;

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

#ifndef IfFailGoto
#define IfFailGoto(EXPR, label) do { Status = (EXPR); if(FAILED(Status)) { goto label; } } while (0)
#endif // IfFailGoto

#ifndef IfFailGo
#define IfFailGo(EXPR) IfFailGoto(EXPR, Error)
#endif // IfFailGo

// Max number of reverted rejit versions that !dumpmd and !ip2md will print
const UINT kcMaxRevertedRejitData = 10;

#ifndef FEATURE_PAL

// ensure we always allocate on the process heap
void* __cdecl operator new(size_t size) throw()
{ return HeapAlloc(GetProcessHeap(), 0, size); }
void __cdecl operator delete(void* pObj) throw()
{ HeapFree(GetProcessHeap(), 0, pObj); }

void* __cdecl operator new[](size_t size) throw()
{ return HeapAlloc(GetProcessHeap(), 0, size); }
void __cdecl operator delete[](void* pObj) throw()
{ HeapFree(GetProcessHeap(), 0, pObj); }

/**********************************************************************\
* Here we define types and functions that support custom COM           *
* activation rules, as defined by the CIOptions enum.                  *
*                                                                      *
\**********************************************************************/

typedef unsigned __int64 QWORD;

namespace com_activation
{
    //
    // Forward declarations for the implementation methods
    //

    HRESULT CreateInstanceCustomImpl(
                            REFCLSID clsid,
                            REFIID   iid,
                            LPCWSTR  dllName,
                            CIOptions cciOptions,
                            void** ppItf);
    HRESULT ClrCreateInstance(
                            REFCLSID clsid, 
                            REFIID iid, 
                            LPCWSTR dllName,
                            CIOptions cciOptions, 
                            void** ppItf);
    HRESULT CreateInstanceFromPath(
                            REFCLSID clsid, 
                            REFIID iid, 
                            LPCWSTR path, 
                            void** ppItf);
    BOOL GetPathFromModule(
                            HMODULE hModule, 
                            __in_ecount(cFqPath) LPWSTR fqPath,
                            DWORD  cFqPath);
    HRESULT PickClrRuntimeInfo(
                            ICLRMetaHost *pMetaHost,
                            CIOptions cciOptions,
                            ICLRRuntimeInfo** ppClr);
    QWORD VerString2Qword(LPCWSTR vStr);
    void CleanupClsidHmodMap();

    // Helper structures for defining the CLSID -> HMODULE hash table we
    // use for caching already activated objects
    class hash_compareGUID
    {
    public:
        static const size_t bucket_size = 4;
        static const size_t min_buckets = 8;
        hash_compareGUID()
        { }

        size_t operator( )(const GUID& _Key) const
        {
            DWORD *pdw = (DWORD*)&_Key;
            return (size_t)(pdw[0] ^ pdw[1] ^ pdw[2] ^ pdw[3]);
        }

        bool operator( )(const GUID& _Key1, const GUID& _Key2) const
        { return memcmp(&_Key1, &_Key2, sizeof(GUID)) == -1; }
    };

    static std::unordered_map<GUID, HMODULE, hash_compareGUID> *g_pClsidHmodMap = NULL;



/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* CreateInstanceCustomImpl() provides a way to activate a COM object   *
* w/o triggering the FeatureOnDemand dialog. In order to do this we    *
* must avoid using  the CoCreateInstance() API, which, on a machine    *
* with v4+ installed and w/o v2, would trigger this.                   *
* CreateInstanceCustom() activates the requested COM object according  *
* to the specified passed in CIOptions, in the following order         *
* (skipping the steps not enabled in the CIOptions flags passed in):   *
*    1. Attempt to activate the COM object using a framework install:  *
*       a. If the debugger machine has a V4+ shell shim use the shim   *
*          to activate the object                                      *
*       b. Otherwise simply call CoCreateInstance                      *
*    2. If unsuccessful attempt to activate looking for the dllName in *
*       the same folder as the DAC was loaded from                     *
*    3. If unsuccessful attempt to activate the COM object looking in  *
*       every path specified in the debugger's .exepath and .sympath   *
\**********************************************************************/
HRESULT CreateInstanceCustomImpl(
                        REFCLSID clsid,
                        REFIID   iid,
                        LPCWSTR  dllName,
                        CIOptions cciOptions,
                        void** ppItf)
{
    _ASSERTE(ppItf != NULL);

    if (ppItf == NULL)
        return E_POINTER;

    WCHAR wszClsid[64] = W("<CLSID>");

    // Step 1: Attempt activation using an installed runtime
    if ((cciOptions & cciFxMask) != 0)
    {
        CIOptions opt = cciOptions & cciFxMask;
        if (SUCCEEDED(ClrCreateInstance(clsid, iid, dllName, opt, ppItf)))
            return S_OK;

        ExtDbgOut("Failed to instantiate {%ls} from installed .NET framework locations.\n", wszClsid);
    }

    if ((cciOptions & cciDbiColocated) != 0)
    {
        // if we institute a way to retrieve the module for the current DBI we
        // can perform the same steps as for the DAC.
    }

    // Step 2: attempt activation using the folder the DAC was loaded from
    if ((cciOptions & cciDacColocated) != 0)
    {
        _ASSERTE(dllName != NULL);
        HMODULE hDac = NULL;
        WCHAR path[MAX_LONGPATH];

        if (SUCCEEDED(g_sos->GetDacModuleHandle(&hDac))
            && GetPathFromModule(hDac, path, _countof(path)))
        {
            // build the fully qualified file name and attempt instantiation
            if (wcscat_s(path, dllName) == 0
                && SUCCEEDED(CreateInstanceFromPath(clsid, iid, path, ppItf)))
            {
                return S_OK;
            }
        }

        ExtDbgOut("Failed to instantiate {%ls} from DAC location.\n", wszClsid);
    }

    // Step 3: attempt activation using the debugger's .exepath and .sympath
    if ((cciOptions & cciDbgPath) != 0)
    {
        _ASSERTE(dllName != NULL);

        ToRelease<IDebugSymbols3> spSym3(NULL);
        HRESULT hr = g_ExtSymbols->QueryInterface(__uuidof(IDebugSymbols3), (void**)&spSym3);
        if (FAILED(hr))
        {
            ExtDbgOut("Unable to query IDebugSymbol3 HRESULT=0x%x.\n", hr);
            goto ErrDbgPath;
        }

        typedef HRESULT (__stdcall IDebugSymbols3::*GetPathFunc)(LPWSTR , ULONG, ULONG*);

        // Handle both the image path and the symbol path
        GetPathFunc rgGetPathFuncs[] = 
            { &IDebugSymbols3::GetImagePathWide, &IDebugSymbols3::GetSymbolPathWide };

        for (int i = 0; i < _countof(rgGetPathFuncs); ++i)
        {
            ULONG pathSize = 0;

            // get the path buffer size
            if ((spSym3.GetPtr()->*rgGetPathFuncs[i])(NULL, 0, &pathSize) != S_OK)
            {
                continue;
            }

            ArrayHolder<WCHAR> imgPath = new WCHAR[pathSize+MAX_LONGPATH+1];
            if (imgPath == NULL)
            {
                continue;
            }

            // actually get the path
            if ((spSym3.GetPtr()->*rgGetPathFuncs[i])(imgPath, pathSize, NULL) != S_OK)
            {
                continue;
            }

            LPWSTR ctx;
            LPCWSTR pathElem = wcstok_s(imgPath, W(";"), &ctx);
            while (pathElem != NULL)
            {
                WCHAR fullName[MAX_LONGPATH];
                wcscpy_s(fullName, _countof(fullName), pathElem);
                if (wcscat_s(fullName, W("\\")) == 0 && wcscat_s(fullName, dllName) == 0)
                {
                    if (SUCCEEDED(CreateInstanceFromPath(clsid, iid, fullName, ppItf)))
                    {
                        return S_OK;
                    }
                }

                pathElem = wcstok_s(NULL, W(";"), &ctx);
            }
        }

    ErrDbgPath:
        ExtDbgOut("Failed to instantiate {%ls} from debugger's image path.\n", wszClsid);
    }

    return REGDB_E_CLASSNOTREG;
}


#ifdef _MSC_VER
// SOS is essentially single-threaded. ignore "construction of local static object is not thread-safe"
#pragma warning(push)
#pragma warning(disable:4640)
#endif // _MSC_VER


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* ClrCreateInstance() attempts to activate a COM object using an       *
* installed framework:                                                 *
*    a. If the debugger machine has a V4+ shell shim use the shim to   *
*        activate the object                                           *
*    b. Otherwise simply call CoCreateInstance                         *
\**********************************************************************/
HRESULT ClrCreateInstance(
                        REFCLSID clsid, 
                        REFIID iid,
                        LPCWSTR dllName,
                        CIOptions cciOptions, 
                        void** ppItf)
{
    _ASSERTE((cciOptions & ~cciFxMask) == 0 && (cciOptions & cciFxMask) != 0);
    HRESULT Status = S_OK;

    static CIOptions prevOpt = 0;
    static HRESULT   prevHr = S_OK;

    // if we already tried to use NetFx install and failed don't try it again
    if (prevOpt == cciOptions && FAILED(prevHr))
    {
        return prevHr;
    }

    prevOpt = cciOptions;

    // first try usig the metahost API:
    HRESULT (__stdcall *pfnCLRCreateInstance)(REFCLSID  clsid, REFIID riid, LPVOID * ppInterface) = NULL;
    HMODULE hMscoree = NULL;

    // if there's a v4+ shim on the debugger machine
    if (GetProcAddressT("CLRCreateInstance", W("mscoree.dll"), &pfnCLRCreateInstance, &hMscoree))
    {
        // attempt to create an ICLRMetaHost instance
        ToRelease<ICLRMetaHost> spMH;
        Status = pfnCLRCreateInstance(CLSID_CLRMetaHost, IID_ICLRMetaHost, (void**)&spMH);
        if (Status == E_NOTIMPL)
        {
            // E_NOTIMPL means we have a v4 aware mscoree but no v4+ framework
            IfFailGo( CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, iid, ppItf) );
        }
        else
        {
            IfFailGo( Status );

            // pick a runtime according to cciOptions
            ToRelease<ICLRRuntimeInfo> spClr;
            IfFailGo( PickClrRuntimeInfo(spMH, cciOptions, &spClr) );

            // activate the COM object
            Status = spClr->GetInterface(clsid, iid, ppItf);

            if (FAILED(Status) && dllName)
            {
                // if we have a v4+ runtime that does not have the fix to activate the requested CLSID
                // try activating with the path
                WCHAR clrDir[MAX_LONGPATH]; 
                DWORD cchClrDir = _countof(clrDir);
                IfFailGo( spClr->GetRuntimeDirectory(clrDir, &cchClrDir) );
                IfFailGo( wcscat_s(clrDir, dllName) == 0 ? S_OK : E_FAIL  );
                IfFailGo( CreateInstanceFromPath(clsid, iid, clrDir, ppItf) );
            }
        }
    }
    else
    {
        // otherwise fallback to regular COM activation
        IfFailGo( CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, iid, ppItf) );
    }

Error:
    if (hMscoree != NULL)
    {
        FreeLibrary(hMscoree);
    }

    // remember if we succeeded or failed
    prevHr = Status;

    return Status;
}

#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* CreateInstanceFromPath() instantiates a COM object using a passed in *
* fully-qualified path and a CLSID.                                    *
*                                                                      *
* Note:                                                                *
*                                                                      *
* It uses a unordered_map to cache the mapping between a CLSID and the      *
* HMODULE that is successfully used to activate the CLSID from. When   *
* SOS is unloaded (in DebugExtensionUninitialize()) we call            *
* FreeLibrary() for all cached HMODULEs.                               *
\**********************************************************************/
HRESULT CreateInstanceFromPath(
                        REFCLSID clsid, 
                        REFIID iid, 
                        LPCWSTR path, 
                        void** ppItf)
{
    HRESULT Status = S_OK;
    HRESULT (__stdcall *pfnDllGetClassObject)(REFCLSID rclsid, REFIID riid, LPVOID *ppv) = NULL;

    HMODULE hmod = NULL;

    if (g_pClsidHmodMap == NULL)
    {
        g_pClsidHmodMap = new std::unordered_map<GUID, HMODULE, hash_compareGUID>();
        OnUnloadTask::Register(CleanupClsidHmodMap);
    }

    auto it = g_pClsidHmodMap->find(clsid);
    if (it != g_pClsidHmodMap->end())
        hmod = it->second;

    if (!GetProcAddressT("DllGetClassObject", path, &pfnDllGetClassObject, &hmod))
        return REGDB_E_CLASSNOTREG;

    ToRelease<IClassFactory> pFactory;
    IfFailGo(pfnDllGetClassObject(clsid, IID_IClassFactory, (void**)&pFactory));

    IfFailGo(pFactory->CreateInstance(NULL, iid, ppItf));

    // only cache the HMODULE if we successfully created the COM object
    (*g_pClsidHmodMap)[clsid] = hmod;

    return S_OK;

Error:
    if (hmod != NULL)
        FreeLibrary(hmod);

    return Status;
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* CleanupClsidHmodMap() cleans up the CLSID -> HMODULE map used to     *
* cache successful activations from specific paths. This is registered *
* as an OnUnloadTask in CreateInstanceFromPath(), and executes when    *
* SOS is unloaded, in DebugExtensionUninitialize().                    *
\**********************************************************************/
void CleanupClsidHmodMap()
{
    if (g_pClsidHmodMap != NULL)
    {
        for (auto it = g_pClsidHmodMap->begin(); it != g_pClsidHmodMap->end(); ++it)
        {
            _ASSERTE(it->second != NULL);
            FreeLibrary(it->second);
        }

        delete g_pClsidHmodMap;
        g_pClsidHmodMap = NULL;
    }
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* PickClrRuntimeInfo() selects on CLR runtime from the ones installed  *
* on the debugger machine. If cciFxAny is specified in cciOptions it   *
* simply returns the first runtime enumerated by the metahost          *
* interface. If cciLatestFx is specified we pick the runtime with the  *
* highest version (parsing the string returned from                    *
* ICLRRuntimeInfo::GetVersionString().                                 *
\**********************************************************************/
HRESULT PickClrRuntimeInfo(
                        ICLRMetaHost *pMetaHost,
                        CIOptions cciOptions,
                        ICLRRuntimeInfo** ppClr)
{
    if (ppClr == NULL)
        return E_POINTER;

    // only support "Any framework" and "latest framework"
    if (cciOptions != cciAnyFx && cciOptions != cciLatestFx)
        return E_INVALIDARG;

    HRESULT Status = S_OK;
    *ppClr = NULL;

    // get the CLRRuntime enumerator
    ToRelease<IEnumUnknown> spClrsEnum;
    IfFailRet(pMetaHost->EnumerateInstalledRuntimes(&spClrsEnum));

    ToRelease<ICLRRuntimeInfo> spChosenClr;
    QWORD verMax = 0;

    int cntClr = 0;
    while (1)
    {
        // retrieve the next ICLRRuntimeInfo
        ULONG cnt;
        ToRelease<IUnknown> spClrUnk;
        if (spClrsEnum->Next(1, &spClrUnk, &cnt) != S_OK || cnt != 1)
            break;

        ToRelease<ICLRRuntimeInfo> spClr;
        BOOL bLoadable = FALSE;
        // ignore un-loadable runtimes
        if (FAILED(spClrUnk->QueryInterface(IID_ICLRRuntimeInfo, (void**)&spClr))
            || FAILED(spClr->IsLoadable(&bLoadable))
            || !bLoadable)
        {
            continue;
        }

        WCHAR vStr[128];
        DWORD cStr = _countof(vStr);
        if (FAILED(spClr->GetVersionString(vStr, &cStr)))
            continue;

        ++cntClr;

        if ((cciOptions & cciAnyFx) != 0)
        {
            spChosenClr = spClr.Detach();
            break;
        }

        QWORD ver = VerString2Qword(vStr);
        if ((cciOptions & cciLatestFx) != 0)
        {
            if (ver > verMax)
            {
                verMax = ver;
                spChosenClr = spClr.Detach();
            }
        }
    }

    if (cntClr == 0 || spChosenClr == NULL)
    {
        *ppClr = NULL;
        return E_NOINTERFACE;
    }
    else
    {
        *ppClr = spChosenClr.Detach();
        return S_OK;
    }
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* VerString2Qword() parses a string as returned from                   *
* ICLRRuntimeInfo::GetVersionString() into a QWORD, assuming every     *
* numeric element is a WORD portion in the QWORD.                      *
\**********************************************************************/
QWORD VerString2Qword(LPCWSTR vStr)
{
    _ASSERTE(vStr[0] == L'v' || vStr[0] == L'V');
    QWORD result = 0;

    DWORD v1, v2, v3;
    if (swscanf_s(vStr+1, W("%d.%d.%d"), &v1, &v2, &v3) == 3)
    {
        result = ((QWORD)v1 << 48) | ((QWORD)v2 << 32) | ((QWORD)v3 << 16);
    }
    else if (swscanf_s(vStr+1, W("%d.%d"), &v1, &v2) == 2)
    {
        result = ((QWORD)v1 << 48) | ((QWORD)v2 << 32);
    }
    else if (swscanf_s(vStr+1, W("%d"), &v1) == 1)
    {
        result = ((QWORD)v1 << 48);
    }

    return result;
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* GetPathFromModule() returns the name of the folder containing the    *
* file associated with hModule.                                        *
 \**********************************************************************/
BOOL GetPathFromModule(
                        HMODULE hModule, 
                        __in_ecount(cFqPath) LPWSTR fqPath, 
                        DWORD  cFqPath)
{
    int len = GetModuleFileNameW(hModule, fqPath, cFqPath);
    if (len == 0 || len == cFqPath)
        return FALSE;

    WCHAR *pLastSep = _wcsrchr(fqPath, DIRECTORY_SEPARATOR_CHAR_W);
    if (pLastSep == NULL || pLastSep+1 >= fqPath+cFqPath)
        return FALSE;

    *(pLastSep+1) = L'\0';

    return TRUE;
}

}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
* CreateInstanceCustom() provides a way to activate a COM object w/o   *
* triggering the FeatureOnDemand dialog. In order to do this we        *
* must avoid using  the CoCreateInstance() API, which, on a machine    *
* with v4+ installed and w/o v2, would trigger this.                   *
* CreateInstanceCustom() activates the requested COM object according  *
* to the specified passed in CIOptions, in the following order         *
* (skipping the steps not enabled in the CIOptions flags passed in):   *
*    1. Attempt to activate the COM object using a framework install:  *
*       a. If the debugger machine has a V4+ shell shim use the shim   *
*          to activate the object                                      *
*       b. Otherwise simply call CoCreateInstance                      *
*    2. If unsuccessful attempt to activate looking for the dllName in *
*       the same folder as the DAC was loaded from                     *
*    3. If unsuccessful attempt to activate the COM object looking in  *
*       every path specified in the debugger's .exepath and .sympath   *
\**********************************************************************/
HRESULT CreateInstanceCustom(
                        REFCLSID clsid,
                        REFIID   iid,
                        LPCWSTR  dllName,
                        CIOptions cciOptions,
                        void** ppItf)
{
    return com_activation::CreateInstanceCustomImpl(clsid, iid, dllName, cciOptions, ppItf);
}




/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to get the memory address given a symbol  *  
*    name.  It handles difference in symbol name between ntsd and      *
*    windbg.                                                           *
*                                                                      *
\**********************************************************************/
DWORD_PTR GetValueFromExpression (___in __in_z const char *const instr)
{
    ULONG64 dwAddr;
    const char *str = instr;
    char name[256];

    dwAddr = 0;
    HRESULT hr = g_ExtSymbols->GetOffsetByName (str, &dwAddr);
    if (SUCCEEDED(hr))
        return (DWORD_PTR)dwAddr;
    else if (hr == S_FALSE && dwAddr)
        return (DWORD_PTR)dwAddr;

    strcpy_s (name, _countof(name), str);
    char *ptr;
    if ((ptr = strstr (name, "__")) != NULL)
    {
        ptr[0] = ':';
        ptr[1] = ':';
        ptr += 2;
        while ((ptr = strstr(ptr, "__")) != NULL)
        {
            ptr[0] = ':';
            ptr[1] = ':';
            ptr += 2;
        }
        dwAddr = 0;
        hr = g_ExtSymbols->GetOffsetByName (name, &dwAddr);
        if (SUCCEEDED(hr))
            return (DWORD_PTR)dwAddr;
        else if (hr == S_FALSE && dwAddr)
            return (DWORD_PTR)dwAddr;
    }
    else if ((ptr = strstr (name, "::")) != NULL)
    {
        ptr[0] = '_';
        ptr[1] = '_';
        ptr += 2;
        while ((ptr = strstr(ptr, "::")) != NULL)
        {
            ptr[0] = '_';
            ptr[1] = '_';
            ptr += 2;
        }
        dwAddr = 0;
        hr = g_ExtSymbols->GetOffsetByName (name, &dwAddr);
        if (SUCCEEDED(hr))
            return (DWORD_PTR)dwAddr;
        else if (hr == S_FALSE && dwAddr)
            return (DWORD_PTR)dwAddr;
    }
    return 0;
}

#endif // FEATURE_PAL

ModuleInfo moduleInfo[MSCOREND] = {{0,FALSE,0},{0,FALSE,0},{0,FALSE,0}};

void ReportOOM()
{
    ExtOut("SOS Error: Out of memory\n");
}

HRESULT CheckEEDll()
{
#ifndef FEATURE_PAL
    VS_FIXEDFILEINFO ee = {};

    static VS_FIXEDFILEINFO sos = {};
    static BOOL sosDataInit = FALSE;
    
    BOOL result = GetEEVersion(&ee);
    if (result && !sosDataInit)
    {
        result = GetSOSVersion(&sos);
        
        if (result)
            sosDataInit = TRUE;
    }

    // We will ignore errors because it's possible sos is being loaded before CLR.
    if (result)
    {
        if ((ee.dwFileVersionMS != sos.dwFileVersionMS) || (ee.dwFileVersionLS != sos.dwFileVersionLS))
        {
            ExtOut("The version of SOS does not match the version of CLR you are debugging.  Please\n");
            ExtOut("load the matching version of SOS for the version of CLR you are debugging.\n");
            ExtOut("CLR Version: %u.%u.%u.%u\n",
                   HIWORD(ee.dwFileVersionMS),
                   LOWORD(ee.dwFileVersionMS),
                   HIWORD(ee.dwFileVersionLS),
                   LOWORD(ee.dwFileVersionLS));

            ExtOut("SOS Version: %u.%u.%u.%u\n",
                   HIWORD(sos.dwFileVersionMS),
                   LOWORD(sos.dwFileVersionMS),
                   HIWORD(sos.dwFileVersionLS),
                   LOWORD(sos.dwFileVersionLS));
        }
    }

    DEBUG_MODULE_PARAMETERS Params;
            
    // Do we have clr.dll
    if (moduleInfo[MSCORWKS].baseAddr == 0)
    {
        g_ExtSymbols->GetModuleByModuleName (MAIN_CLR_MODULE_NAME_A,0,NULL,
                                             &moduleInfo[MSCORWKS].baseAddr);
        if (moduleInfo[MSCORWKS].baseAddr != 0 && moduleInfo[MSCORWKS].hasPdb == FALSE)
        {
            g_ExtSymbols->GetModuleParameters (1, &moduleInfo[MSCORWKS].baseAddr, 0, &Params);
            if (Params.SymbolType == SymDeferred)
            {
                g_ExtSymbols->Reload("/f " MAIN_CLR_DLL_NAME_A);
                g_ExtSymbols->GetModuleParameters (1, &moduleInfo[MSCORWKS].baseAddr, 0, &Params);
            }

            if (Params.SymbolType == SymPdb || Params.SymbolType == SymDia)
            {
                moduleInfo[MSCORWKS].hasPdb = TRUE;
            }

            moduleInfo[MSCORWKS].size = Params.Size;
        }
        if (moduleInfo[MSCORWKS].baseAddr != 0 && moduleInfo[MSCORWKS].hasPdb == FALSE)
            ExtOut("PDB symbol for clr.dll not loaded\n");
    }
    
    return (moduleInfo[MSCORWKS].baseAddr != 0) ? S_OK : E_FAIL;
#else
    return S_OK;
#endif // FEATURE_PAL
}

EEFLAVOR GetEEFlavor ()
{
#ifdef FEATURE_PAL
    return MSCORWKS;
#else // FEATUER_PAL
    EEFLAVOR flavor = UNKNOWNEE;    
    
    if (SUCCEEDED(g_ExtSymbols->GetModuleByModuleName(MAIN_CLR_MODULE_NAME_A,0,NULL,NULL))) {
        flavor = MSCORWKS;
    }
    return flavor;
#endif // FEATURE_PAL else
}

BOOL IsDumpFile ()
{
    static int g_fDumpFile = -1;
    if (g_fDumpFile == -1) {
        ULONG Class;
        ULONG Qualifier;
        g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
        if (Qualifier >= DEBUG_DUMP_SMALL)
            g_fDumpFile = 1;
        else
            g_fDumpFile = 0;
    }
    return g_fDumpFile != 0;
}

BOOL g_InMinidumpSafeMode = FALSE;

BOOL IsMiniDumpFileNODAC ()
{
#ifndef FEATURE_PAL
    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)
        {
            return TRUE;
        }
    }
    
#endif // FEATURE_PAL    
    return FALSE;
}


// We use this predicate to mean the smallest, most restrictive kind of
// minidump file. There is no heap dump, only that set of information
// gathered to make !clrstack, !threads, !help, !eeversion and !pe work.
BOOL IsMiniDumpFile ()
{
#ifndef FEATURE_PAL
    // It is okay for this to be static, because although the debugger may debug multiple
    // managed processes at once, I don't believe multiple dumpfiles of different
    // types is a scenario to worry about.
    if (IsMiniDumpFileNODAC())
    {
        // Beyond recognizing the dump type above, all we can rely on for this
        // is a flag set by the user indicating they want a safe mode minidump
        // experience. This is primarily for testing.
        return g_InMinidumpSafeMode;
    }
    
#endif // FEATURE_PAL
    return FALSE;
}

ULONG DebuggeeType()
{
    static ULONG Class = DEBUG_CLASS_UNINITIALIZED;
    if (Class == DEBUG_CLASS_UNINITIALIZED) {
        ULONG Qualifier;
        g_ExtControl->GetDebuggeeType(&Class,&Qualifier);
    }
    return Class;
}

#ifndef FEATURE_PAL

// Check if a file exist
BOOL FileExist (const char *filename)
{
    WIN32_FIND_DATA FindFileData;
    HANDLE handle = FindFirstFile (filename, &FindFileData);
    if (handle != INVALID_HANDLE_VALUE) {
        FindClose (handle);
        return TRUE;
    }
    else
        return FALSE;
}


BOOL FileExist (const WCHAR *filename)
{
    WIN32_FIND_DATAW FindFileData;
    HANDLE handle = FindFirstFileW (filename, &FindFileData);
    if (handle != INVALID_HANDLE_VALUE) {
        FindClose (handle);
        return TRUE;
    }
    else
        return FALSE;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find out if a dll is bbt-ized          *  
*                                                                      *
\**********************************************************************/
BOOL IsRetailBuild (size_t base)
{
    IMAGE_DOS_HEADER DosHeader;
    if (g_ExtData->ReadVirtual(TO_CDADDR(base), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
        return FALSE;
    IMAGE_NT_HEADERS32 Header32;
    if (g_ExtData->ReadVirtual(TO_CDADDR(base + DosHeader.e_lfanew), &Header32, sizeof(Header32), NULL) != S_OK)
        return FALSE;
    // If there is no COMHeader, this can not be managed code.
    if (Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress == 0)
        return FALSE;

    size_t debugDirAddr = base + Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress;
    size_t nSize = Header32.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
    IMAGE_DEBUG_DIRECTORY debugDir;
    size_t nbytes = 0;
    while (nbytes < nSize) {
        if (g_ExtData->ReadVirtual(TO_CDADDR(debugDirAddr+nbytes), &debugDir, sizeof(debugDir), NULL) != S_OK)
            return FALSE;
        if (debugDir.Type == 0xA) {
            return TRUE;
        }
        nbytes += sizeof(debugDir);
    }
    return FALSE;
}

#endif // !FEATURE_PAL

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to read memory from the debugee's         *  
*    address space.  If the initial read fails, it attempts to read    *
*    only up to the edge of the page containing "offset".              *
*                                                                      *
\**********************************************************************/
BOOL SafeReadMemory (TADDR offset, PVOID lpBuffer, ULONG cb,
                     PULONG lpcbBytesRead)
{
    BOOL bRet = FALSE;

    bRet = SUCCEEDED(g_ExtData->ReadVirtual(TO_CDADDR(offset), lpBuffer, cb,
                                            lpcbBytesRead));
    
    if (!bRet)
    {
        cb   = (ULONG)(NextOSPageAddress(offset) - offset);
        bRet = SUCCEEDED(g_ExtData->ReadVirtual(TO_CDADDR(offset), lpBuffer, cb,
                                                lpcbBytesRead));
    }
    return bRet;
}

ULONG OSPageSize ()
{
    static ULONG pageSize = 0;
    if (pageSize == 0)
        g_ExtControl->GetPageSize(&pageSize);

    return pageSize;
}

size_t NextOSPageAddress (size_t addr)
{
    size_t pageSize = OSPageSize();
    return (addr+pageSize)&(~(pageSize-1));
}


/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to get the address of MethodDesc          *  
*    given an ip address                                               *
*                                                                      *
\**********************************************************************/
void IP2MethodDesc (DWORD_PTR IP, DWORD_PTR &methodDesc, JITTypes &jitType,
                    DWORD_PTR &gcinfoAddr)
{

    CLRDATA_ADDRESS EIP = TO_CDADDR(IP);
    DacpCodeHeaderData codeHeaderData;
    
    methodDesc = NULL;
    gcinfoAddr = NULL;
    
    if (codeHeaderData.Request(g_sos, EIP) != S_OK)
    {        
        return;
    }

    methodDesc = (DWORD_PTR) codeHeaderData.MethodDescPtr;
    jitType = (JITTypes) codeHeaderData.JITType;
    gcinfoAddr = (DWORD_PTR) codeHeaderData.GCInfo;    
}

BOOL IsValueField (DacpFieldDescData *pFD)
{
    return (pFD->Type == ELEMENT_TYPE_VALUETYPE);
}

void DisplayDataMember (DacpFieldDescData* pFD, DWORD_PTR dwAddr, BOOL fAlign=TRUE)
{
    if (dwAddr > 0)
    {
        // we must have called this function for a "real" (non-zero size) data type
        PREFIX_ASSUME(gElementTypeInfo[pFD->Type] != 0);

        DWORD_PTR dwTmp = dwAddr;
        bool bVTStatic = (pFD->bIsStatic && pFD->Type == ELEMENT_TYPE_VALUETYPE);
        
        if (gElementTypeInfo[pFD->Type] != NO_SIZE || bVTStatic)
        {
            union Value
            {
                char ch;
                short Short;
                DWORD_PTR ptr;
                int Int;
                unsigned int UInt;
                __int64 Int64;
                unsigned __int64 UInt64;
                float Float;
                double Double;
            } value;

            ZeroMemory(&value, sizeof(value));
            if (bVTStatic)
            {
                // static VTypes are boxed
                moveBlock (value, dwTmp, gElementTypeInfo[ELEMENT_TYPE_CLASS]);
            }
            else
            {
                moveBlock (value, dwTmp, gElementTypeInfo[pFD->Type]);
            }

            switch (pFD->Type) 
            {
                case ELEMENT_TYPE_I1:
                    // there's no ANSI conformant type specifier for 
                    // signed char, so use the next best thing, 
                    // signed short (sign extending)
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "hd", (short)value.ch);
                    else
                        ExtOut("%d", value.ch);
                    break;
                case ELEMENT_TYPE_I2:
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "hd", value.Short);
                    else
                        ExtOut("%d", value.Short);
                    break;
                case ELEMENT_TYPE_I4:
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "d", value.Int);
                    else
                        ExtOut("%d", value.Int);
                    break;
                case ELEMENT_TYPE_I8:
                    ExtOut("%I64d", value.Int64);
                    break;
                case ELEMENT_TYPE_U1:
                case ELEMENT_TYPE_BOOLEAN:
                    if (fAlign)
                    // there's no ANSI conformant type specifier for 
                    // unsigned char, so use the next best thing, 
                    // unsigned short, not extending the sign
                        ExtOut("%" POINTERSIZE "hu", (USHORT)value.Short);
                    else
                        ExtOut("%u", value.ch);
                    break;
                case ELEMENT_TYPE_U2:
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "hu", value.Short);
                    else
                        ExtOut("%u", value.Short);
                    break;
                case ELEMENT_TYPE_U4:
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "u", value.UInt);
                    else
                        ExtOut("%u", value.UInt);
                    break;
                case ELEMENT_TYPE_U8:
                    ExtOut("%I64u", value.UInt64);
                    break;
                case ELEMENT_TYPE_I:
                case ELEMENT_TYPE_U:
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "p", SOS_PTR(value.ptr));
                    else
                        ExtOut("%p", SOS_PTR(value.ptr));
                    break;
                case ELEMENT_TYPE_R4:
                    ExtOut("%f", value.Float);
                    break;
                case ELEMENT_TYPE_R8:
                    ExtOut("%f", value.Double);
                    break;
                case ELEMENT_TYPE_CHAR:
                    if (fAlign)
                        ExtOut("%" POINTERSIZE "hx", value.Short);
                    else
                        ExtOut("%x", value.Short);
                    break;
                case ELEMENT_TYPE_VALUETYPE:
                    if (value.ptr)
                        DMLOut(DMLValueClass(pFD->MTOfType, dwTmp));
                    else
                        ExtOut("%p", SOS_PTR(0));
                    break;
                default:
                    if (value.ptr)
                        DMLOut(DMLObject(value.ptr));
                    else
                        ExtOut("%p", SOS_PTR(0));
                    break;
            }
        }
        else
        {
            if (pFD->Type == ELEMENT_TYPE_VALUETYPE)
                DMLOut(DMLValueClass(pFD->MTOfType, dwTmp));
            else
                ExtOut("%p", SOS_PTR(0));
        }
    }
    else
    {
        ExtOut("%" POINTERSIZE "s", " ");
    }
}

void GetStaticFieldPTR(DWORD_PTR* pOutPtr, DacpDomainLocalModuleData* pDLMD, DacpMethodTableData* pMTD, DacpFieldDescData* pFDD, BYTE* pFlags = 0)
{
    DWORD_PTR dwTmp;

    if (pFDD->Type == ELEMENT_TYPE_VALUETYPE
            || pFDD->Type == ELEMENT_TYPE_CLASS)
    {
        dwTmp = (DWORD_PTR) pDLMD->pGCStaticDataStart + pFDD->dwOffset;
    }
    else
    {
        dwTmp = (DWORD_PTR) pDLMD->pNonGCStaticDataStart + pFDD->dwOffset;
    }

    *pOutPtr = 0;
    
    if (pMTD->bIsDynamic)
    {
        ExtOut("dynamic statics NYI");
        return;
    }
    else
    {
        if (pFlags && pMTD->bIsShared)
        {
            BYTE flags;
            DWORD_PTR pTargetFlags = (DWORD_PTR) pDLMD->pClassData + RidFromToken(pMTD->cl) - 1;            
            move_xp (flags, pTargetFlags);

            *pFlags = flags;
        }
               
        
        *pOutPtr = dwTmp;            
    }
    return;
}

void GetDLMFlags(DacpDomainLocalModuleData* pDLMD, DacpMethodTableData* pMTD, BYTE* pFlags)
{   
    if (pMTD->bIsDynamic)
    {
        ExtOut("dynamic statics NYI");
        return;
    }
    else
    {
        if (pFlags)
        {
            BYTE flags;
            DWORD_PTR pTargetFlags = (DWORD_PTR) pDLMD->pClassData + RidFromToken(pMTD->cl) - 1;            
            move_xp (flags, pTargetFlags);

            *pFlags = flags;
        }         
    }
    return;
}

void GetThreadStaticFieldPTR(DWORD_PTR* pOutPtr, DacpThreadLocalModuleData* pTLMD, DacpMethodTableData* pMTD, DacpFieldDescData* pFDD, BYTE* pFlags = 0)
{
    DWORD_PTR dwTmp;

    if (pFDD->Type == ELEMENT_TYPE_VALUETYPE
            || pFDD->Type == ELEMENT_TYPE_CLASS)
    {
        dwTmp = (DWORD_PTR) pTLMD->pGCStaticDataStart + pFDD->dwOffset;
    }
    else
    {
        dwTmp = (DWORD_PTR) pTLMD->pNonGCStaticDataStart + pFDD->dwOffset;
    }

    *pOutPtr = 0;
    
    if (pMTD->bIsDynamic)
    {
        ExtOut("dynamic thread statics NYI");
        return;
    }
    else
    {
        if (pFlags)
        {
            BYTE flags;
            DWORD_PTR pTargetFlags = (DWORD_PTR) pTLMD->pClassData + RidFromToken(pMTD->cl) - 1;            
            move_xp (flags, pTargetFlags);

            *pFlags = flags;
        }
                       
        *pOutPtr = dwTmp;            
    }
    return;
}

void DisplaySharedStatic(ULONG64 dwModuleDomainID, DacpMethodTableData* pMT, DacpFieldDescData *pFD)
{
    DacpAppDomainStoreData adsData;
    if (adsData.Request(g_sos)!=S_OK)
    {
        ExtOut("Unable to get AppDomain information\n");        
    }

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

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

#if defined(_TARGET_WIN64_)
    ExtOut("                                 >> Domain:Value ");
#else
    ExtOut("    >> Domain:Value ");
#endif
    // Skip the SystemDomain and SharedDomain
    for (int i = 0; i < adsData.DomainCount ; i ++)
    {
        DacpAppDomainData appdomainData;
        if (appdomainData.Request(g_sos,pArray[i])!=S_OK)
        {
            ExtOut("Unable to get AppDomain %lx\n",pArray[i]);
            return;
        }

        DacpDomainLocalModuleData vDomainLocalModule;
        if (g_sos->GetDomainLocalModuleDataFromAppDomain(appdomainData.AppDomainPtr, (int)dwModuleDomainID, &vDomainLocalModule) != S_OK)
        {
            DMLOut(" %s:NotInit ", DMLDomain(pArray[i]));
            continue;
        }

        DWORD_PTR dwTmp;
        BYTE Flags = 0;
        GetStaticFieldPTR(&dwTmp, &vDomainLocalModule , pMT, pFD, &Flags);

        if ((Flags&1) == 0) {
            // We have not initialized this yet.
            DMLOut(" %s:NotInit ", DMLDomain(pArray[i]));
            continue;
        }
        else if (Flags & 2) {
            // We have not initialized this yet.
            DMLOut(" %s:FailInit", DMLDomain(pArray[i]));
            continue;
        }

        DMLOut(" %s:", DMLDomain(appdomainData.AppDomainPtr));
        DisplayDataMember(pFD, dwTmp, FALSE);               
    }    
    ExtOut(" <<\n");
}

void DisplayThreadStatic (DacpModuleData* pModule, DacpMethodTableData* pMT, DacpFieldDescData *pFD, BOOL fIsShared)
{
    SIZE_T dwModuleIndex = (SIZE_T)pModule->dwModuleIndex;
    SIZE_T dwModuleDomainID = (SIZE_T)pModule->dwModuleID;

    DacpThreadStoreData ThreadStore;
    ThreadStore.Request(g_sos);

    ExtOut("    >> Thread:Value");
    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread)
    {
        DacpThreadData vThread;
        if (vThread.Request(g_sos, CurThread) != S_OK)
        {
            ExtOut("  error getting thread %p, aborting this field\n", SOS_PTR(CurThread));
            return;
        }
        
        if (vThread.osThreadId != 0)
        {   
            CLRDATA_ADDRESS appDomainAddr = vThread.domain;

            // Get the DLM (we need this to check the ClassInit flags).
            // It's annoying that we have to issue one request for
            // domain-neutral modules and domain-specific modules.
            DacpDomainLocalModuleData vDomainLocalModule;                
            if (fIsShared)
            {
                if (g_sos->GetDomainLocalModuleDataFromAppDomain(appDomainAddr, (int)dwModuleDomainID, &vDomainLocalModule) != S_OK)
                {
                    // Not initialized, go to next thread
                    // and continue looping
                    CurThread = vThread.nextThread;
                    continue;
                }
            }
            else
            {
                if (g_sos->GetDomainLocalModuleDataFromModule(pMT->Module, &vDomainLocalModule) != S_OK)
                {
                    // Not initialized, go to next thread
                    // and continue looping
                    CurThread = vThread.nextThread;
                    continue;
                }
            }

            // Get the TLM
            DacpThreadLocalModuleData vThreadLocalModule;
            if (g_sos->GetThreadLocalModuleData(CurThread, (int)dwModuleIndex, &vThreadLocalModule) != S_OK)
            {
                // Not initialized, go to next thread
                // and continue looping
                CurThread = vThread.nextThread;
                continue;
            }
            
            DWORD_PTR dwTmp;
            BYTE Flags = 0;
            GetThreadStaticFieldPTR(&dwTmp, &vThreadLocalModule, pMT, pFD, &Flags);
         
            if ((Flags&4) == 0) 
            {
                // Not allocated, go to next thread
                // and continue looping
                CurThread = vThread.nextThread;
                continue;
            }

            Flags = 0;
            GetDLMFlags(&vDomainLocalModule, pMT, &Flags);

            if ((Flags&1) == 0) 
            {
                // Not initialized, go to next thread
                // and continue looping
                CurThread = vThread.nextThread;
                continue;
            }
            
            ExtOut(" %x:", vThread.osThreadId);
            DisplayDataMember(pFD, dwTmp, FALSE);               
        }

        // Go to next thread
        CurThread = vThread.nextThread;
    }
    ExtOut(" <<\n");
}

void DisplayContextStatic (DacpFieldDescData *pFD, size_t offset, BOOL fIsShared)
{
    ExtOut("\nDisplay of context static variables is not implemented yet\n");
    /*
    int numDomain;
    DWORD_PTR *domainList = NULL;
    GetDomainList (domainList, numDomain);
    ToDestroy des0 ((void**)&domainList);
    AppDomain vAppDomain;
    Context vContext;
    
    ExtOut("    >> Domain:Value");
    for (int i = 0; i < numDomain; i ++)
    {
        DWORD_PTR dwAddr = domainList[i];
        if (dwAddr == 0) {
            continue;
        }
        vAppDomain.Fill (dwAddr);
        if (vAppDomain.m_pDefaultContext == 0)
            continue;
        dwAddr = (DWORD_PTR)vAppDomain.m_pDefaultContext;
        vContext.Fill (dwAddr);
        
        if (fIsShared)
            dwAddr = (DWORD_PTR)vContext.m_pSharedStaticData;
        else
            dwAddr = (DWORD_PTR)vContext.m_pUnsharedStaticData;
        if (dwAddr == 0)
            continue;
        dwAddr += offsetof(STATIC_DATA, dataPtr);
        dwAddr += offset;
        if (safemove (dwAddr, dwAddr) == 0)
            continue;
        if (dwAddr == 0)
            // We have not initialized this yet.
            continue;
        
        dwAddr += pFD->dwOffset;
        if (pFD->Type == ELEMENT_TYPE_CLASS
            || pFD->Type == ELEMENT_TYPE_VALUETYPE)
        {
            if (safemove (dwAddr, dwAddr) == 0)
                continue;
        }
        if (dwAddr == 0)
            // We have not initialized this yet.
            continue;
        ExtOut(" %p:", (ULONG64)domainList[i]);
        DisplayDataMember (pFD, dwAddr, FALSE);
    }
    ExtOut(" <<\n");
    */
}

const char * ElementTypeName(unsigned type)
{
    switch (type) {
    case ELEMENT_TYPE_PTR:
        return "PTR";
        break;
    case ELEMENT_TYPE_BYREF:
        return "BYREF";
        break;
    case ELEMENT_TYPE_VALUETYPE:
        return "VALUETYPE";
        break;
    case ELEMENT_TYPE_CLASS:
        return "CLASS";
        break;
    case ELEMENT_TYPE_VAR:
        return "VAR";
        break;
    case ELEMENT_TYPE_ARRAY:
        return "ARRAY";
        break;
    case ELEMENT_TYPE_FNPTR:
        return "FNPTR";
        break;
    case ELEMENT_TYPE_SZARRAY:
        return "SZARRAY";
        break;
    case ELEMENT_TYPE_MVAR:
        return "MVAR";
        break;
    default:
        if ((type >= _countof(CorElementTypeName)) || (CorElementTypeName[type] == NULL))
        {
            return "";
        }
        return CorElementTypeName[type];
        break;
    }
} // ElementTypeName

const char * ElementTypeNamespace(unsigned type)
{
    if ((type >= _countof(CorElementTypeName)) || (CorElementTypeNamespace[type] == NULL))
    {
        return "";
    }
    return CorElementTypeNamespace[type];
}

void ComposeName_s(CorElementType Type, __out_ecount(capacity_buffer) LPSTR buffer, size_t capacity_buffer)
{
    const char *p = ElementTypeNamespace(Type);
    if ((p) && (*p != '\0'))
    {
        strcpy_s(buffer,capacity_buffer,p);
        strcat_s(buffer,capacity_buffer,".");
        strcat_s(buffer,capacity_buffer,ElementTypeName(Type));
    }
    else
    {
        strcpy_s(buffer,capacity_buffer,ElementTypeName(Type));
    }
}

// NOTE: pszName is changed
// INPUT            MAXCHARS        RETURN
// HelloThere       5               ...re
// HelloThere       8               ...There
LPWSTR FormatTypeName (__out_ecount (maxChars) LPWSTR pszName, UINT maxChars)
{
    UINT iStart = 0;
    UINT iLen = (int) _wcslen(pszName);
    if (iLen > maxChars)
    {
        iStart = iLen - maxChars;
        UINT numDots = (maxChars < 3) ? maxChars : 3;
        for (UINT i=0; i < numDots; i++)
            pszName[iStart+i] = '.';        
    }
    return pszName + iStart;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump all fields of a managed object.   *  
*    dwStartAddr specifies the beginning memory address.               *
*    bFirst is used to avoid printing header everytime.                *
*                                                                      *
\**********************************************************************/
void DisplayFields(CLRDATA_ADDRESS cdaMT, DacpMethodTableData *pMTD, DacpMethodTableFieldData *pMTFD, DWORD_PTR dwStartAddr, BOOL bFirst, BOOL bValueClass)
{
    static DWORD numInstanceFields = 0;
    if (bFirst)
    {
        ExtOutIndent();
        ExtOut("%" POINTERSIZE "s %8s %8s %20s %2s %8s %" POINTERSIZE "s %s\n", 
            "MT", "Field", "Offset", "Type", "VT", "Attr", "Value", "Name");
        numInstanceFields = 0;
    }
    
    BOOL fIsShared = pMTD->bIsShared;

    if (pMTD->ParentMethodTable)
    {
        DacpMethodTableData vParentMethTable;
        if (vParentMethTable.Request(g_sos,pMTD->ParentMethodTable) != S_OK)
        {
            ExtOut("Invalid parent MethodTable\n");
            return;
        }            

        DacpMethodTableFieldData vParentMethTableFields;
        if (vParentMethTableFields.Request(g_sos,pMTD->ParentMethodTable) != S_OK)
        {
            ExtOut("Invalid parent EEClass\n");
            return;
        }            

        DisplayFields(pMTD->ParentMethodTable, &vParentMethTable, &vParentMethTableFields, dwStartAddr, FALSE, bValueClass);
    }

    DWORD numStaticFields = 0;
    CLRDATA_ADDRESS dwAddr = pMTFD->FirstField;
    DacpFieldDescData vFieldDesc;

    // Get the module name
    DacpModuleData module;
    if (module.Request(g_sos, pMTD->Module)!=S_OK)
        return;    

    ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
    
    while (numInstanceFields < pMTFD->wNumInstanceFields
           || numStaticFields < pMTFD->wNumStaticFields)
    {
        if (IsInterrupt())
            return;

        ExtOutIndent ();
        
        if ((vFieldDesc.Request(g_sos, dwAddr)!=S_OK) ||
            (vFieldDesc.Type >= ELEMENT_TYPE_MAX))
        {
            ExtOut("Unable to display fields\n");
            return;
        }
        dwAddr = vFieldDesc.NextField;

        DWORD offset = vFieldDesc.dwOffset;
        if(!((vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal || fIsShared) && vFieldDesc.bIsStatic))
        {
            if (!bValueClass)
            {
                offset += sizeof(BaseObject);
            }
        }

        DMLOut("%s %8x %8x ", DMLMethodTable(vFieldDesc.MTOfType),
                 TokenFromRid(vFieldDesc.mb, mdtFieldDef),
                 offset);

        char ElementName[mdNameLen];
        if ((vFieldDesc.Type == ELEMENT_TYPE_VALUETYPE || 
            vFieldDesc.Type == ELEMENT_TYPE_CLASS) && vFieldDesc.MTOfType)
        {
            NameForMT_s((DWORD_PTR)vFieldDesc.MTOfType, g_mdName, mdNameLen);            
            ExtOut("%20.20S ", FormatTypeName(g_mdName, 20));            
        }
        else 
        {       
            if (vFieldDesc.Type == ELEMENT_TYPE_CLASS && vFieldDesc.TokenOfType != mdTypeDefNil)
            {
                // Get the name from Metadata!!!
                NameForToken_s(TokenFromRid(vFieldDesc.TokenOfType, mdtTypeDef), pImport, g_mdName, mdNameLen, false);
                ExtOut("%20.20S ", FormatTypeName(g_mdName, 20));
            }
            else
            {
                // If ET type from signature is different from fielddesc, then the signature one is more descriptive. 
                // For example, E_T_STRING in field desc will be E_T_CLASS. In minidump's case, we won't have
                // the method table for it.
                ComposeName_s(vFieldDesc.Type != vFieldDesc.sigType ? vFieldDesc.sigType : vFieldDesc.Type, ElementName, sizeof(ElementName)/sizeof(ElementName[0]));
                ExtOut("%20.20s ", ElementName); 
            }
        }
        
        ExtOut("%2s ", (IsElementValueType(vFieldDesc.Type)) ? "1" : "0");

        if (vFieldDesc.bIsStatic && (vFieldDesc.bIsThreadLocal || vFieldDesc.bIsContextLocal))
        {
            numStaticFields ++;
            if (fIsShared)
                ExtOut("%8s %" POINTERSIZE "s", "shared", vFieldDesc.bIsThreadLocal ? "TLstatic" : "CLstatic");
            else
                ExtOut("%8s ", vFieldDesc.bIsThreadLocal ? "TLstatic" : "CLstatic");

            NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
            ExtOut(" %S\n", g_mdName);

            if (IsMiniDumpFile())
            {
                ExtOut(" <no information>\n");
            }
            else
            {
                if (vFieldDesc.bIsThreadLocal)
                {
                    DacpModuleData vModule;
                    if (vModule.Request(g_sos,pMTD->Module) == S_OK)
                    {
                        DisplayThreadStatic(&vModule, pMTD, &vFieldDesc, fIsShared);
                    }
                }
                else if (vFieldDesc.bIsContextLocal)
                {
                    DisplayContextStatic(&vFieldDesc,
                                         pMTFD->wContextStaticOffset,
                                         fIsShared);
                }
            }
    
        }
        else if (vFieldDesc.bIsStatic)
        {
            numStaticFields ++;

            if (fIsShared)
            {
                ExtOut("%8s %" POINTERSIZE "s", "shared", "static");

                NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
                ExtOut(" %S\n", g_mdName);

                if (IsMiniDumpFile())
                {
                    ExtOut(" <no information>\n");
                }
                else
                {
                    DacpModuleData vModule;
                    if (vModule.Request(g_sos,pMTD->Module) == S_OK)
                    {
                        DisplaySharedStatic(vModule.dwModuleID, pMTD, &vFieldDesc);
                    }
                }
            }
            else
            {
                ExtOut("%8s ", "static");
                
                DacpDomainLocalModuleData vDomainLocalModule;
                
                // The MethodTable isn't shared, so the module must not be loaded domain neutral.  We can
                // get the specific DomainLocalModule instance without needing to know the AppDomain in advance.
                if (g_sos->GetDomainLocalModuleDataFromModule(pMTD->Module, &vDomainLocalModule) != S_OK)
                {
                    ExtOut(" <no information>\n");
                }
                else
                {
                    DWORD_PTR dwTmp;
                    GetStaticFieldPTR(&dwTmp, &vDomainLocalModule, pMTD, &vFieldDesc);
                    DisplayDataMember(&vFieldDesc, dwTmp);

                    NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
                    ExtOut(" %S\n", g_mdName);
                }
            }
        }
        else
        {
            numInstanceFields ++;

            ExtOut("%8s ", "instance");

            if (dwStartAddr > 0)
            {
                DWORD_PTR dwTmp = dwStartAddr + vFieldDesc.dwOffset + (bValueClass ? 0 : sizeof(BaseObject));
                DisplayDataMember(&vFieldDesc, dwTmp);
            }
            else
            {
                ExtOut(" %8s", " ");
            }


            NameForToken_s(TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
            ExtOut(" %S\n", g_mdName);
        }
        
    }
    
    return;
}

// Return value: -1 = error, 
//                0 = field not found, 
//              > 0 = offset to field from objAddr
int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, __in_z LPCWSTR wszFieldName, BOOL bFirst)
{
    TADDR mt = NULL;
    if FAILED(GetMTOfObject(TO_TADDR(cdaObj), &mt))
        return -1;

    return GetObjFieldOffset(cdaObj, TO_CDADDR(mt), wszFieldName, bFirst);
}

// Return value: -1 = error, 
//                0 = field not found, 
//              > 0 = offset to field from objAddr
int GetObjFieldOffset(CLRDATA_ADDRESS cdaObj, CLRDATA_ADDRESS cdaMT, __in_z LPCWSTR wszFieldName,
                        BOOL bFirst/*=TRUE*/)
{

#define EXITPOINT(EXPR) do { if(!(EXPR)) { return -1; } } while (0)
    
    DacpObjectData objData;
    DacpMethodTableData dmtd;
    DacpMethodTableFieldData vMethodTableFields;
    DacpFieldDescData vFieldDesc;
    DacpModuleData module;
    static DWORD numInstanceFields = 0; // Static due to recursion visiting parents

    if (bFirst)
    {
        numInstanceFields = 0;
    }
    
    EXITPOINT(objData.Request(g_sos, cdaObj) == S_OK);    
    EXITPOINT(dmtd.Request(g_sos, cdaMT) == S_OK);

    if (dmtd.ParentMethodTable)
    {
        DWORD retVal = GetObjFieldOffset (cdaObj, dmtd.ParentMethodTable, 
                                          wszFieldName, FALSE);
        if (retVal != 0)
        {
            // return in case of error or success.
            // Fall through for field-not-found.
            return retVal;
        }
    }
    
    EXITPOINT (vMethodTableFields.Request(g_sos,cdaMT) == S_OK);
    EXITPOINT (module.Request(g_sos,dmtd.Module) == S_OK);
        
    CLRDATA_ADDRESS dwAddr = vMethodTableFields.FirstField;            
    ToRelease<IMetaDataImport> pImport = MDImportForModule(&module);
        
    while (numInstanceFields < vMethodTableFields.wNumInstanceFields)
    {        
        EXITPOINT (vFieldDesc.Request(g_sos, dwAddr) == S_OK);

        if (!vFieldDesc.bIsStatic)
        {
            DWORD offset = vFieldDesc.dwOffset + sizeof(BaseObject);          
            NameForToken_s (TokenFromRid(vFieldDesc.mb, mdtFieldDef), pImport, g_mdName, mdNameLen, false);
            if (_wcscmp (wszFieldName, g_mdName) == 0)
            {
                return offset;
            }
            numInstanceFields ++;                        
        }

        dwAddr = vFieldDesc.NextField;        
    }

    // Field name not found...
    return 0;

#undef EXITPOINT    
}

// Returns an AppDomain address if AssemblyPtr is loaded into that domain only. Otherwise
// returns NULL
CLRDATA_ADDRESS IsInOneDomainOnly(CLRDATA_ADDRESS AssemblyPtr)
{
    CLRDATA_ADDRESS appDomain = NULL;

    DacpAppDomainStoreData adstore;
    if (adstore.Request(g_sos) != S_OK)
    {
        ExtOut("Unable to get appdomain store\n");
        return NULL;
    }    

    size_t AllocSize;
    if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), adstore.DomainCount, AllocSize))
    {
        ReportOOM();        
        return NULL;
    }

    ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adstore.DomainCount];
    if (pArray==NULL)
    {
        ReportOOM();        
        return NULL;
    }
    
    if (g_sos->GetAppDomainList(adstore.DomainCount, pArray, NULL)!=S_OK)
    {
        ExtOut ("Failed to get appdomain list\n");
        return NULL;
    }

    for (int i = 0; i < adstore.DomainCount; i++)
    {
        if (IsInterrupt())
            return NULL;

        DacpAppDomainData dadd;
        if (dadd.Request(g_sos, pArray[i]) != S_OK)
        {
            ExtOut ("Unable to get AppDomain %p\n", SOS_PTR(pArray[i]));
            return NULL;
        }

        if (dadd.AssemblyCount)
        {
            size_t AssemblyAllocSize;
            if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), dadd.AssemblyCount, AssemblyAllocSize))
            {
                ReportOOM();                        
                return NULL;
            }

            ArrayHolder<CLRDATA_ADDRESS> pAsmArray = new CLRDATA_ADDRESS[dadd.AssemblyCount];
            if (pAsmArray==NULL)
            {
                ReportOOM();                        
                return NULL;
            }
    
            if (g_sos->GetAssemblyList(dadd.AppDomainPtr,dadd.AssemblyCount,pAsmArray, NULL)!=S_OK)
            {
                ExtOut("Unable to get array of Assemblies\n");
                return NULL;  
            }
      
            for (LONG n = 0; n < dadd.AssemblyCount; n ++)
            {
                if (IsInterrupt())
                    return NULL;

                if (AssemblyPtr == pAsmArray[n])
                {
                    if (appDomain != NULL)
                    {
                        // We have found more than one AppDomain that loaded this
                        // assembly, we must return NULL.
                        return NULL;
                    }
                    appDomain = dadd.AppDomainPtr;
                }                
            }    
        }
    } 

    
    return appDomain;
}

CLRDATA_ADDRESS GetAppDomainForMT(CLRDATA_ADDRESS mtPtr)
{
    DacpMethodTableData mt;
    if (mt.Request(g_sos, mtPtr) != S_OK)
    {
        return NULL;
    }
    
    DacpModuleData module;
    if (module.Request(g_sos, mt.Module) != S_OK)
    {
        return NULL;
    }

    DacpAssemblyData assembly;
    if (assembly.Request(g_sos, module.Assembly) != S_OK)
    {
        return NULL;
    }

    DacpAppDomainStoreData adstore;
    if (adstore.Request(g_sos) != S_OK)
    {
        return NULL;
    }

    return (assembly.ParentDomain == adstore.sharedDomain) ?
            IsInOneDomainOnly(assembly.AssemblyPtr) :
            assembly.ParentDomain;
}

CLRDATA_ADDRESS GetAppDomain(CLRDATA_ADDRESS objPtr)
{
    CLRDATA_ADDRESS appDomain = NULL;
    
    DacpObjectData objData;
    if (objData.Request(g_sos,objPtr) != S_OK)
    {        
        return NULL;
    }

    // First check  eeclass->module->assembly->domain.
    // Then check the object flags word
    // finally, search threads for a reference to the object, and look at the thread context.

    DacpMethodTableData mt;
    if (mt.Request(g_sos,objData.MethodTable) != S_OK)
    {
        return NULL;
    }

    DacpModuleData module;
    if (module.Request(g_sos,mt.Module) != S_OK)
    {
        return NULL;
    }

    DacpAssemblyData assembly;
    if (assembly.Request(g_sos,module.Assembly) != S_OK)
    {
        return NULL;
    }

    DacpAppDomainStoreData adstore;
    if (adstore.Request(g_sos) != S_OK)
    {
        return NULL;
    }    
    
    if (assembly.ParentDomain == adstore.sharedDomain)
    {
        sos::Object obj(TO_TADDR(objPtr));
        ULONG value = 0;
        if (!obj.TryGetHeader(value))
        {
            return NULL;
        }
        
        DWORD adIndex = (value >> SBLK_APPDOMAIN_SHIFT) & SBLK_MASK_APPDOMAININDEX;
        if ( ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0) || adIndex==0)
        {
            // No AppDomainID information. We'll make use of a heuristic.
            // If the assembly is in the shared domain, we can report it as
            // being in domain X if the only other domain that has the assembly
            // loaded is domain X.
            appDomain = IsInOneDomainOnly(assembly.AssemblyPtr);
            if (appDomain == NULL && ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) != 0))
            {
                if ((value & BIT_SBLK_IS_HASHCODE) == 0)
                {
                    UINT index = value & MASK_SYNCBLOCKINDEX;
                    // We have a syncblock, the appdomain ID may be in there.
                    DacpSyncBlockData syncBlockData;
                    if (syncBlockData.Request(g_sos,index) == S_OK)
                    {
                        appDomain = syncBlockData.appDomainPtr;
                    }
                }
            }
        }
        else if ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0)
        {            
            size_t AllocSize;
            if (!ClrSafeInt<size_t>::multiply(sizeof(CLRDATA_ADDRESS), adstore.DomainCount, AllocSize))
            {
                return NULL;
            }
            // we know we have a non-zero adIndex. Find the appdomain.
            ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[adstore.DomainCount];
            if (pArray==NULL)
            {
                return NULL;
            }
            
            if (g_sos->GetAppDomainList(adstore.DomainCount, pArray, NULL)!=S_OK)
            {
                return NULL;
            }

            for (int i = 0; i < adstore.DomainCount; i++)
            {
                DacpAppDomainData dadd;
                if (dadd.Request(g_sos, pArray[i]) != S_OK)
                {
                    return NULL;
                }
                if (dadd.dwId == adIndex)
                {
                    appDomain = pArray[i];
                    break;
                }
            } 
        }
    }
    else
    {
        appDomain = assembly.ParentDomain;
    }

    return appDomain;
}

HRESULT FileNameForModule (DWORD_PTR pModuleAddr, __out_ecount (MAX_LONGPATH) WCHAR *fileName)
{
    DacpModuleData ModuleData;
    fileName[0] = L'\0';
    
    HRESULT hr = ModuleData.Request(g_sos, TO_CDADDR(pModuleAddr));
    if (SUCCEEDED(hr))
    {
        hr = FileNameForModule(&ModuleData,fileName);
    }
    
    return hr;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find the file name given a Module.     *  
*                                                                      *
\**********************************************************************/
// fileName should be at least MAX_LONGPATH
HRESULT FileNameForModule (DacpModuleData *pModule, __out_ecount (MAX_LONGPATH) WCHAR *fileName)
{
    fileName[0] = L'\0';
    
    HRESULT hr = S_OK;
    CLRDATA_ADDRESS dwAddr = pModule->File;
    if (dwAddr == 0)
    {
        // TODO:  We have dynamic module
        return E_NOTIMPL;
    }
    
    CLRDATA_ADDRESS base = 0;
    hr = g_sos->GetPEFileBase(dwAddr, &base);
    if (SUCCEEDED(hr))
    {
        hr = g_sos->GetPEFileName(dwAddr, MAX_LONGPATH, fileName, NULL);
        if (SUCCEEDED(hr))
        {
            if (fileName[0] != W('\0'))
                return hr; // done
        }
#ifndef FEATURE_PAL
        // Try the base *
        if (base)
        {
            hr = DllsName((ULONG_PTR) base, fileName);
        }
#endif // !FEATURE_PAL
    }
    
    // If we got here, either DllsName worked, or we couldn't find a name
    return hr;
}

void AssemblyInfo(DacpAssemblyData *pAssembly)
{
    ExtOut("ClassLoader:        %p\n", SOS_PTR(pAssembly->ClassLoader));
    if ((ULONG64)pAssembly->AssemblySecDesc != NULL)
        ExtOut("SecurityDescriptor: %p\n", SOS_PTR(pAssembly->AssemblySecDesc));
    ExtOut("  Module Name\n");
    
    ArrayHolder<CLRDATA_ADDRESS> Modules = new CLRDATA_ADDRESS[pAssembly->ModuleCount];
    if (Modules == NULL 
        || g_sos->GetAssemblyModuleList(pAssembly->AssemblyPtr, pAssembly->ModuleCount, Modules, NULL) != S_OK)
    {
       ReportOOM();        
       return;
    }
    
    for (UINT n=0;n<pAssembly->ModuleCount;n++)
    {
        if (IsInterrupt())
        {
            return;
        }

        CLRDATA_ADDRESS ModuleAddr = Modules[n];
        DMLOut("%s    " WIN86_8SPACES, DMLModule(ModuleAddr));
        DacpModuleData moduleData;
        if (moduleData.Request(g_sos,ModuleAddr)==S_OK)
        {
            WCHAR fileName[MAX_LONGPATH];
            FileNameForModule (&moduleData, fileName);
            if (fileName[0])
            {
                ExtOut("%S\n", fileName);
            }
            else
            {
                ExtOut("%S\n", (moduleData.bIsReflection) ? W("Dynamic Module") : W("Unknown Module"));
            }
        }        
    }
}

const char *GetStageText(DacpAppDomainDataStage stage)
{
    switch(stage)
    {
        case STAGE_CREATING:
            return "CREATING";
        case STAGE_READYFORMANAGEDCODE:
            return "READYFORMANAGEDCODE";
        case STAGE_ACTIVE:
            return "ACTIVE";
        case STAGE_OPEN:
            return "OPEN";
        case STAGE_UNLOAD_REQUESTED:
            return "UNLOAD_REQUESTED";
        case STAGE_EXITING:
            return "EXITING";
        case STAGE_EXITED:
            return "EXITED";
        case STAGE_FINALIZING:
            return "FINALIZING";
        case STAGE_FINALIZED:
            return "FINALIZED";
        case STAGE_HANDLETABLE_NOACCESS:
            return "HANDLETABLE_NOACCESS";
        case STAGE_CLEARED:
            return "CLEARED";
        case STAGE_COLLECTED:
            return "COLLECTED";
        case STAGE_CLOSED:
            return "CLOSED";
    }
    return "UNKNOWN";
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to dump the contents of a domain.         *  
*                                                                      *
\**********************************************************************/
void DomainInfo (DacpAppDomainData *pDomain)
{
    ExtOut("LowFrequencyHeap:   %p\n", SOS_PTR(pDomain->pLowFrequencyHeap));
    ExtOut("HighFrequencyHeap:  %p\n", SOS_PTR(pDomain->pHighFrequencyHeap));
    ExtOut("StubHeap:           %p\n", SOS_PTR(pDomain->pStubHeap));
    ExtOut("Stage:              %s\n", GetStageText(pDomain->appDomainStage));
    if ((ULONG64)pDomain->AppSecDesc != NULL)
        ExtOut("SecurityDescriptor: %p\n", SOS_PTR(pDomain->AppSecDesc));
    ExtOut("Name:               ");

    if (g_sos->GetAppDomainName(pDomain->AppDomainPtr, mdNameLen, g_mdName, NULL)!=S_OK)
    {
        ExtOut("Error getting AppDomain friendly name\n");
    }
    else
    {
        ExtOut("%S\n", (g_mdName[0] != L'\0') ? g_mdName : W("None"));
    }

    if (pDomain->AssemblyCount == 0)
        return;
    
    ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[pDomain->AssemblyCount];
    if (pArray==NULL)
    {
        ReportOOM();
        return;
    }

    if (g_sos->GetAssemblyList(pDomain->AppDomainPtr,pDomain->AssemblyCount,pArray, NULL)!=S_OK)
    {
        ExtOut("Unable to get array of Assemblies\n");
        return;  
    }

    LONG n;
    // Assembly vAssembly;
    for (n = 0; n < pDomain->AssemblyCount; n ++)
    {
        if (IsInterrupt())
            return;
        
        if (n != 0)
            ExtOut("\n");

        DMLOut("Assembly:           %s", DMLAssembly(pArray[n]));
        DacpAssemblyData assemblyData;
        if (assemblyData.Request(g_sos, pArray[n], pDomain->AppDomainPtr) == S_OK)
        {
            if (assemblyData.isDynamic)
                ExtOut(" (Dynamic)");
            
            ExtOut(" [");
            if (g_sos->GetAssemblyName(pArray[n], mdNameLen, g_mdName, NULL) == S_OK)
                ExtOut("%S", g_mdName);
            ExtOut("]\n");

            AssemblyInfo(&assemblyData);
        }
    }    

    ExtOut("\n");
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find the name of a MethodDesc using    *  
*    metadata API.                                                     *
*                                                                      *
\**********************************************************************/
BOOL NameForMD_s (DWORD_PTR pMD, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName)
{
    mdName[0] = L'\0';
    CLRDATA_ADDRESS StartAddr = TO_CDADDR(pMD);
    DacpMethodDescData MethodDescData;

    // don't need to check for minidump file as all commands are seals
    // We also do not have EEJitManager to validate anyway.
    //
    if (!IsMiniDumpFile() && MethodDescData.Request(g_sos,StartAddr) != S_OK)
    {
        ExtOut("%p is not a MethodDesc\n", SOS_PTR(StartAddr));
        return FALSE;
    }

    if (g_sos->GetMethodDescName(StartAddr, mdNameLen, mdName, NULL) != S_OK)
    {
        wcscpy_s(mdName, capacity_mdName, W("UNKNOWN"));
        return FALSE;
    }
    return TRUE;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find the name of a MethodTable using   *  
*    metadata API.                                                     *
*                                                                      *
\**********************************************************************/
BOOL NameForMT_s(DWORD_PTR MTAddr, __out_ecount (capacity_mdName) WCHAR *mdName, size_t capacity_mdName)
{
    HRESULT hr = g_sos->GetMethodTableName(TO_CDADDR(MTAddr), (ULONG32)capacity_mdName, mdName, NULL);
    return SUCCEEDED(hr);
}

WCHAR *CreateMethodTableName(TADDR mt, TADDR cmt)
{
    bool array = false;
    WCHAR *res = NULL;
    
    if (mt == sos::MethodTable::GetFreeMT())
    {
        res = new WCHAR[5];
        wcscpy_s(res, 5, W("Free"));
        return res;
    }
    
    if (mt == sos::MethodTable::GetArrayMT() && cmt != NULL)
    {
        mt = cmt;
        array = true;
    }
    
    unsigned int needed = 0;
    HRESULT hr = g_sos->GetMethodTableName(mt, 0, NULL, &needed);
    
    // If failed, we will return null.
    if (SUCCEEDED(hr))
    {
        // +2 for [], if we need it.
        res = new WCHAR[needed+2];
        hr = g_sos->GetMethodTableName(mt, needed, res, NULL);
        
        if (FAILED(hr))
        {
            delete [] res;
            res = NULL;
        }
        else if (array)
        {        
            res[needed-1] = '[';
            res[needed] = ']';
            res[needed+1] = 0;
        }
    }

    return res;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Return TRUE if str2 is a substring of str1 and str1 and str2      *  
*    share the same file path.
*                                                                      *
\**********************************************************************/
BOOL IsSameModuleName (const char *str1, const char *str2)
{
    if (strlen (str1) < strlen (str2))
        return FALSE;
    const char *ptr1 = str1 + strlen(str1)-1;
    const char *ptr2 = str2 + strlen(str2)-1;
    while (ptr2 >= str2)
    {
#ifndef FEATURE_PAL
        if (tolower(*ptr1) != tolower(*ptr2))
#else
        if (*ptr1 != *ptr2)
#endif
        {
            return FALSE;
        }
        ptr2--;
        ptr1--;
    }
    if (ptr1 >= str1 && *ptr1 != DIRECTORY_SEPARATOR_CHAR_A && *ptr1 != ':')
    {
        return FALSE;
    }
    return TRUE;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Return TRUE if moduleAddr is the address of a module.             *  
*                                                                      *
\**********************************************************************/
BOOL IsModule (DWORD_PTR moduleAddr)
{
    DacpModuleData module;
    return (module.Request(g_sos, TO_CDADDR(moduleAddr))==S_OK);
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Return TRUE if value is the address of a MethodTable.             *  
*    We verify that MethodTable and EEClass are right.
*                                                                      *
\**********************************************************************/
BOOL IsMethodTable (DWORD_PTR value)
{
    DacpMethodTableData mtabledata;
    if (mtabledata.Request(g_sos, TO_CDADDR(value))!=S_OK)
    {
        return FALSE;
    }
    
    return TRUE;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Return TRUE if value is the address of a MethodDesc.              *  
*    We verify that MethodTable and EEClass are right.
*                                                                      *
\**********************************************************************/
BOOL IsMethodDesc (DWORD_PTR value)
{    
    // Just by retrieving one successfully from the DAC, we know we have a MethodDesc.
    DacpMethodDescData MethodDescData;
    if (MethodDescData.Request(g_sos, TO_CDADDR(value)) != S_OK)
    {
        return FALSE;
    }
    
    return TRUE;
}

DacpUsefulGlobalsData g_special_usefulGlobals;

BOOL IsObjectArray (DacpObjectData *pData)
{
    if (pData->ObjectType == OBJ_ARRAY)
        return g_special_usefulGlobals.ArrayMethodTable == pData->MethodTable;
    
    return FALSE;
}

BOOL IsObjectArray (DWORD_PTR obj)
{
    DWORD_PTR mtAddr = NULL;
    if (SUCCEEDED(GetMTOfObject(obj, &mtAddr)))
        return TO_TADDR(g_special_usefulGlobals.ArrayMethodTable) == mtAddr;
    
    return FALSE;
}

BOOL IsStringObject (size_t obj)
{
    DWORD_PTR mtAddr = NULL;

    if (SUCCEEDED(GetMTOfObject(obj, &mtAddr)))
        return TO_TADDR(g_special_usefulGlobals.StringMethodTable) == mtAddr;

    return FALSE;
}

void DumpStackObjectsOutput(const char *location, DWORD_PTR objAddr, BOOL verifyFields)
{
    // rule out pointers that are outside of the gc heap.
    if (g_snapshot.GetHeap(objAddr) == NULL)
        return;

    DacpObjectData objectData;
    if (objectData.Request(g_sos, TO_CDADDR(objAddr)) != S_OK)
        return;

    if (sos::IsObject(objAddr, verifyFields != FALSE)
        && !sos::MethodTable::IsFreeMT(TO_TADDR(objectData.MethodTable)))
    {
        DMLOut("%-" POINTERSIZE "s %s ", location, DMLObject(objAddr));
        if (g_sos->GetObjectClassName(TO_CDADDR(objAddr), mdNameLen, g_mdName, NULL)==S_OK)
        {
            ExtOut("%S", g_mdName);

            if (IsStringObject(objAddr))
            {
                ExtOut("    ");
                StringObjectContent(objAddr, FALSE, 40);
            }
            else if (IsObjectArray(objAddr) && 
                     (g_sos->GetMethodTableName(objectData.ElementTypeHandle, mdNameLen, g_mdName, NULL) == S_OK))
            {
                ExtOut("    ");
                ExtOut("(%S[])", g_mdName);
            }
        }
        else
        {
            ExtOut("<unknown type>");
        }
        ExtOut("\n");
    }
}

void DumpStackObjectsOutput(DWORD_PTR ptr, DWORD_PTR objAddr, BOOL verifyFields)
{
    char location[64];
    sprintf_s(location, 64, "%p", (DWORD_PTR *)ptr);

    DumpStackObjectsOutput(location, objAddr, verifyFields);
}

void DumpStackObjectsInternal(size_t StackTop, size_t StackBottom, BOOL verifyFields)
{
    for (DWORD_PTR ptr = StackTop; ptr <= StackBottom; ptr += sizeof(DWORD_PTR))
    {       
        if (IsInterrupt())
            return;

        DWORD_PTR objAddr;
        move_xp(objAddr, ptr);

        DumpStackObjectsOutput(ptr, objAddr, verifyFields);
    }
}

void DumpRegObjectHelper(const char *regName, BOOL verifyFields)
{
    DWORD_PTR reg;
#ifdef FEATURE_PAL    
    if (FAILED(g_ExtRegisters->GetValueByName(regName, &reg)))
        return;
#else
    DEBUG_VALUE value;
    ULONG IREG;
    if (FAILED(g_ExtRegisters->GetIndexByName(regName, &IREG)) ||
        FAILED(g_ExtRegisters->GetValue(IREG, &value)))
        return;

#if defined(SOS_TARGET_X86) || defined(SOS_TARGET_ARM)
    reg = (DWORD_PTR) value.I32;
#elif defined(SOS_TARGET_AMD64) || defined(SOS_TARGET_ARM64)
    reg = (DWORD_PTR) value.I64;
#else
#error Unsupported target
#endif
#endif // FEATURE_PAL

    DumpStackObjectsOutput(regName, reg, verifyFields);
}

void DumpStackObjectsHelper (
                TADDR StackTop, 
                TADDR StackBottom, 
                BOOL verifyFields)
{
    ExtOut(g_targetMachine->GetDumpStackObjectsHeading());

    LPCSTR* regs;
    unsigned int cnt;
    g_targetMachine->GetGCRegisters(&regs, &cnt);

    for (size_t i = 0; i < cnt; ++i)
        DumpRegObjectHelper(regs[i], verifyFields);

    // Make certain StackTop is dword aligned:
    DumpStackObjectsInternal(StackTop & ~ALIGNCONST, StackBottom, verifyFields);
}

void AddToModuleList(DWORD_PTR * &moduleList, int &numModule, int &maxList,
                     DWORD_PTR dwModuleAddr)
{
    int i;
    for (i = 0; i < numModule; i ++)
    {
        if (moduleList[i] == dwModuleAddr)
            break;
    }
    if (i == numModule)
    {
        moduleList[numModule] = dwModuleAddr;
        numModule ++;
        if (numModule == maxList)
        {
            int listLength = 0;
            if (!ClrSafeInt<int>::multiply(maxList, 2, listLength))
            {
                ExtOut("<integer overflow>\n");
                numModule = 0;
                ControlC = 1;
                return;
            }
            DWORD_PTR *list = new DWORD_PTR [listLength];

            if (list == NULL)
            {
                numModule = 0;
                ControlC = 1;
                return;
            }
            memcpy (list, moduleList, maxList * sizeof(PVOID));
            delete[] moduleList;
            moduleList = list;
            maxList *= 2;
        }
    }
}

BOOL IsFusionLoadedModule (LPCSTR fusionName, LPCSTR mName)
{
    // The fusion name will be in this format:
    // <module name>, Version=<version>, Culture=<culture>, PublicKeyToken=<token>
    // If fusionName up to the comma matches mName (case insensitive),
    // we consider that a match was found.
    LPCSTR commaPos = strchr (fusionName, ',');
    if (commaPos)
    {
        // verify that fusionName and mName match up to a comma.
        while (*fusionName != ',')
        {
            if (*mName == '\0')
            {
                return FALSE;
            }
            
#ifndef FEATURE_PAL
            if (tolower(*fusionName) != tolower(*mName))
#else
            if (*fusionName != *mName)
#endif
            {
                return FALSE;
            }
            fusionName++;
            mName++;
        }
        return TRUE;        
    }
    return FALSE;
}
    
BOOL DebuggerModuleNamesMatch (CLRDATA_ADDRESS PEFileAddr, ___in __in_z LPSTR mName)
{
    // Another way to see if a module is the same is
    // to accept that mName may be the debugger's name for
    // a loaded module. We can get the debugger's name for
    // the module we are looking at right now, and compare
    // it with mName, if they match exactly, we can add
    // the module to the list.
    if (PEFileAddr)
    {
        CLRDATA_ADDRESS pebase = 0;
        if (g_sos->GetPEFileBase(PEFileAddr, &pebase) == S_OK)
        {
            if (pebase)
            {
                ULONG Index;
                ULONG64 base;
                if (g_ExtSymbols->GetModuleByOffset(pebase, 0, &Index, &base) == S_OK)
                {                                    
                    CHAR ModuleName[MAX_LONGPATH+1];

                    if (g_ExtSymbols->GetModuleNames(Index, base, NULL, 0, NULL, ModuleName, 
                        MAX_LONGPATH, NULL, NULL, 0, NULL) == S_OK)
                    {
                        if (_stricmp (ModuleName, mName) == 0)
                        {
                            return TRUE;
                        }
                    }
                }                                
            }
        }                        
    }
    return FALSE;
}

DWORD_PTR *ModuleFromName(__in_opt LPSTR mName, int *numModule)
{
    if (numModule == NULL)
        return NULL;

    DWORD_PTR *moduleList = NULL;
    *numModule = 0;

    DacpAppDomainStoreData adsData;
    if (adsData.Request(g_sos)!=S_OK)
        return NULL;

    ArrayHolder<CLRDATA_ADDRESS> pAssemblyArray = NULL;
    ArrayHolder<CLRDATA_ADDRESS> pModules = NULL;
    int arrayLength = 0;
    if (!ClrSafeInt<int>::addition(adsData.DomainCount, 2, arrayLength))
    {
        ExtOut("<integer overflow>\n");
        return NULL;
    }
    ArrayHolder<CLRDATA_ADDRESS> pArray = new CLRDATA_ADDRESS[arrayLength];

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

    pArray[0] = adsData.systemDomain;
    pArray[1] = adsData.sharedDomain;
    if (g_sos->GetAppDomainList(adsData.DomainCount, pArray.GetPtr()+2, NULL)!=S_OK)
    {
        ExtOut("Unable to get array of AppDomains\n");
        return NULL;
    }

    // List all domain
    size_t AllocSize;
    int maxList = arrayLength; // account for system and shared domains
    if (maxList <= 0 || !ClrSafeInt<size_t>::multiply(maxList, sizeof(PVOID), AllocSize))
    {
        ExtOut("Integer overflow error.\n");
        return NULL;
    }
    
    moduleList = new DWORD_PTR[maxList];
    if (moduleList == NULL)
    {
        ReportOOM();
        return NULL;
    }

    WCHAR StringData[MAX_LONGPATH];
    char fileName[sizeof(StringData)/2];
    
    // Search all domains to find a module
    for (int n = 0; n < adsData.DomainCount+2; n++)
    {
        if (IsInterrupt())
        {
            ExtOut("<interrupted>\n");
            goto Failure;
        }
        
        DacpAppDomainData appDomain;
        if (FAILED(appDomain.Request(g_sos,pArray[n])))
        {
            // Don't print a failure message here, 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

            // we will correctly give the answer that whatever module you were looking for, it isn't loaded yet
            goto Failure;
        }

        if (appDomain.AssemblyCount)
        {            
            pAssemblyArray = new CLRDATA_ADDRESS[appDomain.AssemblyCount];
            if (pAssemblyArray==NULL)
            {
                ReportOOM();
                goto Failure;
            }

            if (FAILED(g_sos->GetAssemblyList(appDomain.AppDomainPtr, appDomain.AssemblyCount, pAssemblyArray, NULL)))
            {
                ExtOut("Unable to get array of Assemblies for the given AppDomain..\n");
                goto Failure;
            }

            for (int nAssem = 0; nAssem < appDomain.AssemblyCount; nAssem ++)
            {
                if (IsInterrupt())
                {
                    ExtOut("<interrupted>\n");
                    goto Failure;
                }

                DacpAssemblyData assemblyData;
                if (FAILED(assemblyData.Request(g_sos, pAssemblyArray[nAssem])))
                {
                    ExtOut("Failed to request assembly.\n");
                    goto Failure;
                }

                pModules = new CLRDATA_ADDRESS[assemblyData.ModuleCount];
                if (FAILED(g_sos->GetAssemblyModuleList(assemblyData.AssemblyPtr, assemblyData.ModuleCount, pModules, NULL)))
                {
                    ExtOut("Failed to get the modules for the given assembly.\n");
                    goto Failure;
                }

                for (UINT nModule = 0; nModule < assemblyData.ModuleCount; nModule++)
                {
                    if (IsInterrupt())
                    {
                        ExtOut("<interrupted>\n");
                        goto Failure;
                    }

                    CLRDATA_ADDRESS ModuleAddr = pModules[nModule];
                    DacpModuleData ModuleData;
                    if (FAILED(ModuleData.Request(g_sos,ModuleAddr)))
                    {
                        ExtOut("Failed to request Module data from assembly.\n");
                        goto Failure;
                    }

                    FileNameForModule ((DWORD_PTR)ModuleAddr, StringData);
                    int m;
                    for (m = 0; StringData[m] != L'\0'; m++)
                    {
                        fileName[m] = (char)StringData[m];
                    }
                    fileName[m] = '\0';
                    
                    if ((mName == NULL) || 
                        IsSameModuleName(fileName, mName) ||
                        DebuggerModuleNamesMatch(ModuleData.File, mName) ||
                        IsFusionLoadedModule(fileName, mName))
                    {
                        AddToModuleList(moduleList, *numModule, maxList, (DWORD_PTR)ModuleAddr);
                    }    
                }                        

                pModules = NULL;
            }
            pAssemblyArray = NULL;
        }
    }

    return moduleList;
    
    // We do not want to return a half-constructed list.  Instead, we return NULL on a failure.
Failure:
    delete [] moduleList;
    return NULL;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Find the EE data given a name.                                    *  
*                                                                      *
\**********************************************************************/
void GetInfoFromName(DWORD_PTR ModulePtr, const char* name)
{
    ToRelease<IMetaDataImport> pImport = MDImportForModule (ModulePtr);    
    if (pImport == 0)
        return;

    static WCHAR wszName[MAX_CLASSNAME_LENGTH];
    size_t n;
    size_t length = strlen (name);
    for (n = 0; n <= length; n ++)
        wszName[n] = name[n];

    // First enumerate methods. We're taking advantage of the DAC's 
    // CLRDataModule::EnumMethodDefinitionByName which can parse
    // method names (whether in nested classes, or explicit interface
    // method implementations).
    ToRelease<IXCLRDataModule> ModuleDefinition;
    if (g_sos->GetModule(ModulePtr, &ModuleDefinition) == S_OK)
    {
        CLRDATA_ENUM h;
        if (ModuleDefinition->StartEnumMethodDefinitionsByName(wszName, 0, &h) == S_OK)
        {
            IXCLRDataMethodDefinition *pMeth = NULL;
            BOOL fStatus = FALSE;
            while (ModuleDefinition->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
            {
                if (fStatus)
                    ExtOut("-----------------------\n");

                mdTypeDef token;
                if (pMeth->GetTokenAndScope(&token, NULL) == S_OK)
                {
                    GetInfoFromModule(ModulePtr, token);
                    fStatus = TRUE;
                }
                pMeth->Release();
            }
            ModuleDefinition->EndEnumMethodDefinitionsByName(h);
            if (fStatus)
                return;
        }
    }

    // Now look for types, type members and fields
    mdTypeDef cl;
    mdToken tkEnclose = mdTokenNil;
    WCHAR *pName;
    WCHAR *pHead = wszName;
    while ( ((pName = _wcschr (pHead,L'+')) != NULL) ||
             ((pName = _wcschr (pHead,L'/')) != NULL)) {
        pName[0] = L'\0';
        if (FAILED(pImport->FindTypeDefByName(pHead,tkEnclose,&tkEnclose)))
            return;
        pHead = pName+1;
    }

    pName = pHead;

    // @todo:  Handle Nested classes correctly.
    if (SUCCEEDED (pImport->FindTypeDefByName (pName, tkEnclose, &cl)))
    {
        GetInfoFromModule(ModulePtr, cl);
        return;
    }
    
    // See if it is a method
    WCHAR *pwzMethod;
    if ((pwzMethod = _wcsrchr(pName, L'.')) == NULL)
        return;

    if (pwzMethod[-1] == L'.')
        pwzMethod --;
    pwzMethod[0] = L'\0';
    pwzMethod ++;
    
    // @todo:  Handle Nested classes correctly.
    if (SUCCEEDED(pImport->FindTypeDefByName (pName, tkEnclose, &cl)))
    {
        mdMethodDef token;
        ULONG cTokens;
        HCORENUM henum = NULL;

        // is Member?
        henum = NULL;
        if (SUCCEEDED (pImport->EnumMembersWithName (&henum, cl, pwzMethod,
                                                     &token, 1, &cTokens))
            && cTokens == 1)
        {
            ExtOut("Member (mdToken token) of\n");
            GetInfoFromModule(ModulePtr, cl);
            return;
        }

        // is Field?
        henum = NULL;
        if (SUCCEEDED (pImport->EnumFieldsWithName (&henum, cl, pwzMethod,
                                                     &token, 1, &cTokens))
            && cTokens == 1)
        {
            ExtOut("Field (mdToken token) of\n");
            GetInfoFromModule(ModulePtr, cl);
            return;
        }
    }
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Find the EE data given a token.                                   *  
*                                                                      *
\**********************************************************************/
DWORD_PTR GetMethodDescFromModule(DWORD_PTR ModuleAddr, ULONG token)
{
    if (TypeFromToken(token) != mdtMethodDef)
        return NULL;

    CLRDATA_ADDRESS md = 0;
    if (FAILED(g_sos->GetMethodDescFromToken(ModuleAddr, token, &md)))
    {
        return NULL;
    }
    else if (0 == md)
    {
        // a NULL ReturnValue means the method desc is not loaded yet
        return MD_NOT_YET_LOADED;
    } 
    else if ( !IsMethodDesc((DWORD_PTR)md))
    {
        return NULL;
    }
    
    return (DWORD_PTR)md;    
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Find the MethodDefinitions given a name.                          *  
*                                                                      *
\**********************************************************************/
HRESULT GetMethodDefinitionsFromName(TADDR ModulePtr, IXCLRDataModule* mod, const char *name, IXCLRDataMethodDefinition **ppOut, int numMethods, int *numMethodsNeeded)
{
    if (name == NULL)
        return E_FAIL;

    size_t n;
    size_t length = strlen (name);
    for (n = 0; n <= length; n ++)
        g_mdName[n] = name[n];

    CLRDATA_ENUM h;
    int methodCount = 0;
    if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
    {
        IXCLRDataMethodDefinition *pMeth = NULL;
        while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
        {
            methodCount++;
            pMeth->Release();
        }
        mod->EndEnumMethodDefinitionsByName(h);
    }

    if(numMethodsNeeded != NULL)
        *numMethodsNeeded = methodCount;
    if(ppOut == NULL)
        return S_OK;
    if(numMethods > methodCount)
        numMethods = methodCount;

    if (methodCount > 0)
    {
        if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
        {
            IXCLRDataMethodDefinition *pMeth = NULL;
            for (int i = 0; i < numMethods && mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK; i++)
            {
                ppOut[i] = pMeth;
            }
            mod->EndEnumMethodDefinitionsByName(h);
        }
    }
    
    return S_OK;
}

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Find the EE data given a name.                                    *  
*                                                                      *
\**********************************************************************/
HRESULT GetMethodDescsFromName(TADDR ModulePtr, IXCLRDataModule* mod, const char *name, DWORD_PTR **pOut,int *numMethods)
{
    if (name == NULL || pOut == NULL || numMethods == NULL)
        return E_FAIL;

    *pOut = NULL;
    *numMethods = 0;

    size_t n;
    size_t length = strlen (name);
    for (n = 0; n <= length; n ++)
        g_mdName[n] = name[n];

    CLRDATA_ENUM h;
    int methodCount = 0;
    if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
    {
        IXCLRDataMethodDefinition *pMeth = NULL;
        while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
        {
            methodCount++;
            pMeth->Release();
        }
        mod->EndEnumMethodDefinitionsByName(h);
    }

    if (methodCount > 0)
    {
        *pOut = new TADDR[methodCount];
        if (*pOut==NULL)
        {
            ReportOOM();
            return E_OUTOFMEMORY;
        }

        *numMethods = methodCount;

        if (mod->StartEnumMethodDefinitionsByName(g_mdName, 0, &h) == S_OK)
        {
            int i = 0;
            IXCLRDataMethodDefinition *pMeth = NULL;
            while (mod->EnumMethodDefinitionByName(&h, &pMeth) == S_OK)
            {
                mdTypeDef token;
                if (pMeth->GetTokenAndScope(&token, NULL) != S_OK)
                    (*pOut)[i] = NULL;
                (*pOut)[i] = GetMethodDescFromModule(ModulePtr, token);
                if ((*pOut)[i] == NULL)
                {
                    *numMethods = 0;
                    return E_FAIL;
                }
                i++;
                pMeth->Release();
            }
            mod->EndEnumMethodDefinitionsByName(h);
        }
    }
    
    return S_OK;
}
    
/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    Find the EE data given a token.                                   *  
*                                                                      *
\**********************************************************************/
void GetInfoFromModule (DWORD_PTR ModuleAddr, ULONG token, DWORD_PTR *ret)
{
    switch (TypeFromToken(token))
    {
        case mdtMethodDef:
            break;
        case mdtTypeDef:
            break;
        case mdtTypeRef:
            break;
        case mdtFieldDef:
            break;            
        default:
            ExtOut("This token type is not supported\n");
            return;
            break;
    }
    
    CLRDATA_ADDRESS md = 0;
    if (FAILED(g_sos->GetMethodDescFromToken(ModuleAddr, token, &md)) || !IsValidToken (ModuleAddr, token))
    {
        ExtOut("<invalid module token>\n");
        return;
    }
    
    if (ret != NULL)
    {
        *ret = (DWORD_PTR)md;
        return;
    }

    ExtOut("Token:       %p\n", SOS_PTR(token));
 
    switch (TypeFromToken(token))
    {
        case mdtFieldDef:
        {
            NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
            ExtOut("Field name:  %S\n", g_mdName);
            break;
        }
        case mdtMethodDef:
        {
            if (md)
            {
                DMLOut("MethodDesc:  %s\n", DMLMethodDesc(md));

                // Easiest to get full parameterized method name from ..::GetMethodName
                if (g_sos->GetMethodDescName(md, mdNameLen, g_mdName, NULL) != S_OK)
                {
                    // Fall back to just method name without parameters..
                    NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
                }
            }
            else
            {
                ExtOut("MethodDesc:  <not loaded yet>\n");  
                NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
            }
            
            ExtOut("Name:        %S\n", g_mdName);
            // Nice to have a little more data
            if (md)
            {
                DacpMethodDescData MethodDescData;
                if (MethodDescData.Request(g_sos, md) == S_OK)
                {
                    if (MethodDescData.bHasNativeCode)
                    {
                        DMLOut("JITTED Code Address: %s\n", DMLIP(MethodDescData.NativeCodeAddr));                
                    }
                    else
                    {
#ifndef FEATURE_PAL
                        if (IsDMLEnabled())
                            DMLOut("Not JITTED yet. Use <exec cmd=\"!bpmd -md %p\">!bpmd -md %p</exec> to break on run.\n",
                                SOS_PTR(md), SOS_PTR(md));
                        else
                            ExtOut("Not JITTED yet. Use !bpmd -md %p to break on run.\n", SOS_PTR(md));
#else
                        ExtOut("Not JITTED yet. Use 'bpmd -md %p' to break on run.\n", SOS_PTR(md));
#endif
                    }
                }
                else
                {
                    ExtOut ("<Error getting MethodDesc information>\n");
                }
            }
            else
            {
                ExtOut("Not JITTED yet.\n");    
            }
            break;
        }
        case mdtTypeDef:
        case mdtTypeRef:
        {
            if (md)
            {
                DMLOut("MethodTable: %s\n", DMLMethodTable(md));
                DacpMethodTableData mtabledata;
                if (mtabledata.Request(g_sos, md) == S_OK)
                {
                    DMLOut("EEClass:     %s\n", DMLClass(mtabledata.Class));
                }
                else
                {
                    ExtOut("EEClass:     <error getting EEClass>\n");
                }                
            }
            else
            {
                ExtOut("MethodTable: <not loaded yet>\n");
                ExtOut("EEClass:     <not loaded yet>\n");                
            }
            NameForToken_s(ModuleAddr, token, g_mdName, mdNameLen);
            ExtOut("Name:        %S\n", g_mdName);
            break;
        }
        default:
            break;
    }
    return;
}

BOOL IsMTForFreeObj(DWORD_PTR pMT)
{
    return (pMT == g_special_usefulGlobals.FreeMethodTable);
}

const char *EHTypeName(EHClauseType et)
{
    if (et == EHFault)
        return "FAULT";
    else if (et == EHFinally)
        return "FINALLY";
    else if (et == EHFilter)
        return "FILTER";
    else if (et == EHTyped)
        return "TYPED";
    else
        return "UNKNOWN";
}

void DumpRejitData(DacpReJitData * pReJitData)
{
    ExtOut("    ReJITID %p: ", SOS_PTR(pReJitData->rejitID));
    DMLOut("CodeAddr = %s", DMLIP(pReJitData->NativeCodeAddr));                

    LPCSTR szFlags;
    switch (pReJitData->flags)
    {
    default:
    case DacpReJitData::kUnknown:
        szFlags = "";
        break;

    case DacpReJitData::kRequested:
        szFlags = " (READY to jit on next call)";
        break;

    case DacpReJitData::kActive:
        szFlags = " (CURRENT)";
        break;

    case DacpReJitData::kReverted:
        szFlags = " (reverted)";
        break;
    }
    ExtOut("%s\n", szFlags);
}

// For !ip2md requests, this function helps us ensure that rejitted version corresponding
// to the specified IP always gets dumped. It may have already been dumped if it was the
// current rejit version (which is always dumped) or one of the reverted versions that we
// happened to dump before we clipped their number down to kcRejitDataRevertedMax.
BOOL ShouldDumpRejitDataRequested(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData)
{
    if (pMethodDescData->rejitDataRequested.rejitID == 0)
        return FALSE;

    if (pMethodDescData->rejitDataRequested.rejitID == pMethodDescData->rejitDataCurrent.rejitID)
        return FALSE;

    for (ULONG i=0; i < cRevertedRejitData; i++)
    {
        if (pMethodDescData->rejitDataRequested.rejitID == pRevertedRejitData[i].rejitID)
            return FALSE;
    }

    return TRUE;
}


void DumpAllRejitDataIfNecessary(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData)
{
    // If there's no rejit info to output, then skip
    if ((pMethodDescData->rejitDataCurrent.rejitID == 0) &&
        (pMethodDescData->rejitDataRequested.rejitID == 0) &&
        (cRevertedRejitData == 0))
    {
        return;
    }
    ExtOut("ReJITed versions:\n");

    // Dump CURRENT rejit info
    DumpRejitData(&pMethodDescData->rejitDataCurrent);

    // Dump reverted rejit infos
    for (ULONG i=0; i < cRevertedRejitData; i++)
    {
        DumpRejitData(&pRevertedRejitData[i]);
    }

    // For !ip2md, ensure we dump the rejit version corresponding to the specified IP
    // (if not already dumped)
    if (ShouldDumpRejitDataRequested(pMethodDescData, pRevertedRejitData, cRevertedRejitData))
        DumpRejitData(&pMethodDescData->rejitDataRequested);

    // If we maxed out the reverted versions we dumped, let user know there may be more
    if (cRevertedRejitData == kcMaxRevertedRejitData)
        ExtOut("    (... possibly more reverted versions ...)\n");
}

void DumpMDInfoFromMethodDescData(DacpMethodDescData * pMethodDescData, DacpReJitData * pRevertedRejitData, UINT cRevertedRejitData, BOOL fStackTraceFormat)
{
    static WCHAR wszNameBuffer[1024]; // should be large enough
    BOOL bFailed = FALSE;
    if (g_sos->GetMethodDescName(pMethodDescData->MethodDescPtr, 1024, wszNameBuffer, NULL) != S_OK)
    {
        wcscpy_s(wszNameBuffer, _countof(wszNameBuffer), W("UNKNOWN"));        
        bFailed = TRUE;        
    }

    if (!fStackTraceFormat)
    {
        ExtOut("Method Name:  %S\n", wszNameBuffer);

        DacpMethodTableData mtdata;
        if (SUCCEEDED(mtdata.Request(g_sos, pMethodDescData->MethodTablePtr)))
        {
            DMLOut("Class:        %s\n", DMLClass(mtdata.Class));
        }            

        DMLOut("MethodTable:  %s\n", DMLMethodTable(pMethodDescData->MethodTablePtr));
        ExtOut("mdToken:      %p\n", SOS_PTR(pMethodDescData->MDToken));
        DMLOut("Module:       %s\n", DMLModule(pMethodDescData->ModulePtr));
        ExtOut("IsJitted:     %s\n", pMethodDescData->bHasNativeCode ? "yes" : "no");
        DMLOut("CodeAddr:     %s\n", DMLIP(pMethodDescData->NativeCodeAddr));                

        DacpMethodDescTransparencyData transparency;
        if (SUCCEEDED(transparency.Request(g_sos, pMethodDescData->MethodDescPtr)))
        {
            ExtOut("Transparency: %s\n", GetTransparency(transparency));
        }

        DumpAllRejitDataIfNecessary(pMethodDescData, pRevertedRejitData, cRevertedRejitData);
    }
    else
    {
        if (!bFailed)
        {
            ExtOut("%S", wszNameBuffer);
        }
        else
        {
            // Only clutter the display with module/token for cases where we
            // can't get the MethodDesc name for some reason.
            DMLOut("Unknown MethodDesc (Module %s, mdToken %08x)", 
                    DMLModule(pMethodDescData->ModulePtr),
                    pMethodDescData->MDToken);
        }
    }
}

void DumpMDInfo(DWORD_PTR dwMethodDescAddr, CLRDATA_ADDRESS dwRequestedIP /* = 0 */, BOOL fStackTraceFormat /*  = FALSE */)
{
    DacpMethodDescData MethodDescData;
    DacpReJitData revertedRejitData[kcMaxRevertedRejitData];
    ULONG cNeededRevertedRejitData;
    if (g_sos->GetMethodDescData(
        TO_CDADDR(dwMethodDescAddr), 
        dwRequestedIP,
        &MethodDescData, 
        _countof(revertedRejitData),
        revertedRejitData,
        &cNeededRevertedRejitData) != S_OK)
    {
        ExtOut("%p is not a MethodDesc\n", SOS_PTR(dwMethodDescAddr));
        return;
    }

    DumpMDInfoFromMethodDescData(&MethodDescData, revertedRejitData, cNeededRevertedRejitData, fStackTraceFormat);
}

void GetDomainList (DWORD_PTR *&domainList, int &numDomain)
{
    DacpAppDomainStoreData adsData;

    numDomain = 0;            
    
    if (adsData.Request(g_sos)!=S_OK)
    {
        return;
    }

    // Do prefast integer checks before the malloc.
    size_t AllocSize;
    LONG DomainAllocCount;
    if (!ClrSafeInt<LONG>::addition(adsData.DomainCount, 2, DomainAllocCount) ||
        !ClrSafeInt<size_t>::multiply(DomainAllocCount, sizeof(PVOID), AllocSize) ||
        (domainList = new DWORD_PTR[DomainAllocCount]) == NULL)
    {
        return;
    }

    domainList[numDomain++] = (DWORD_PTR) adsData.systemDomain;
    domainList[numDomain++] = (DWORD_PTR) adsData.sharedDomain;
    
    CLRDATA_ADDRESS *pArray = new CLRDATA_ADDRESS[adsData.DomainCount];
    if (pArray==NULL)
    {
        return;
    }

    if (g_sos->GetAppDomainList(adsData.DomainCount, pArray, NULL)!=S_OK)
    {
        delete [] pArray;
        return;
    }

    for (int n=0;n<adsData.DomainCount;n++)
    {
        if (IsInterrupt())
            break;
        domainList[numDomain++] = (DWORD_PTR) pArray[n];
    }

    delete [] pArray;
}


HRESULT GetThreadList(DWORD_PTR **threadList, int *numThread)
{
    _ASSERTE(threadList != NULL);
    _ASSERTE(numThread != NULL);

    if (threadList == NULL || numThread == NULL)
    {
        return E_FAIL;
    }

    *numThread = 0;

    DacpThreadStoreData ThreadStore;
    if ( ThreadStore.Request(g_sos) != S_OK)
    {
        ExtOut("Failed to request threads from the thread store.");
        return E_FAIL;
    }
     
    *threadList = new DWORD_PTR[ThreadStore.threadCount];
    if (*threadList == NULL)
    {
        ReportOOM();
        return E_OUTOFMEMORY;
    }
    
    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread != NULL)
    {
        if (IsInterrupt())
            return S_FALSE;

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

        (*threadList)[(*numThread)++] = (DWORD_PTR)CurThread;
        CurThread = Thread.nextThread;
    }

    return S_OK;
}

CLRDATA_ADDRESS GetCurrentManagedThread ()
{
    DacpThreadStoreData ThreadStore;
    ThreadStore.Request(g_sos);

    ULONG Tid;
    g_ExtSystem->GetCurrentThreadSystemId(&Tid);
    
    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread)
    {
        DacpThreadData Thread;
        if (Thread.Request(g_sos, CurThread) != S_OK)
        {
            return NULL;
        }        
        
        if (Thread.osThreadId == Tid)
        {        
            return CurThread;
        }
        
        CurThread = Thread.nextThread;
    }
    return NULL;
}


void ReloadSymbolWithLineInfo()
{
#ifndef FEATURE_PAL
    static BOOL bLoadSymbol = FALSE;
    if (!bLoadSymbol)
    {
        ULONG Options;
        g_ExtSymbols->GetSymbolOptions(&Options);
        if (!(Options & SYMOPT_LOAD_LINES))
        {
            g_ExtSymbols->AddSymbolOptions(SYMOPT_LOAD_LINES);
            
            if (SUCCEEDED(g_ExtSymbols->GetModuleByModuleName(MSCOREE_SHIM_A, 0, NULL, NULL)))
                g_ExtSymbols->Reload("/f " MSCOREE_SHIM_A);
            
            EEFLAVOR flavor = GetEEFlavor();
            if (flavor == MSCORWKS)
                g_ExtSymbols->Reload("/f " MAIN_CLR_DLL_NAME_A);
        }
        
        // reload mscoree.pdb and clrjit.pdb to get line info
        bLoadSymbol = TRUE;
    }
#endif
}

// Return 1 if the function is our stub
// Return MethodDesc if the function is managed
// Otherwise return 0
size_t FunctionType (size_t EIP)
{
    ULONG64 base = 0;
    ULONG   ulLoaded, ulUnloaded, ulIndex;

    // Get the number of loaded and unloaded modules
    if (FAILED(g_ExtSymbols->GetNumberModules(&ulLoaded, &ulUnloaded)))
        return 0;


    if (SUCCEEDED(g_ExtSymbols->GetModuleByOffset(TO_CDADDR(EIP), 0, &ulIndex, &base)) && base != 0)
    {
        if (ulIndex < ulLoaded)
        {
            IMAGE_DOS_HEADER DosHeader;
            if (g_ExtData->ReadVirtual(TO_CDADDR(base), &DosHeader, sizeof(DosHeader), NULL) != S_OK)
                return 0;
            IMAGE_NT_HEADERS Header;
            if (g_ExtData->ReadVirtual(TO_CDADDR(base + DosHeader.e_lfanew), &Header, sizeof(Header), NULL) != S_OK)
                return 0;
            // If there is no COMHeader, this can not be managed code.
            if (Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress == 0)
                return 0;
            
            IMAGE_COR20_HEADER ComPlusHeader;
            if (g_ExtData->ReadVirtual(TO_CDADDR(base + Header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COMHEADER].VirtualAddress),
                                       &ComPlusHeader, sizeof(ComPlusHeader), NULL) != S_OK)
                return 0;
            
            // If there is no Precompiled image info, it can not be prejit code
            if (ComPlusHeader.ManagedNativeHeader.VirtualAddress == 0) {
                return 0;
            }
        }
    }

    CLRDATA_ADDRESS dwStartAddr = TO_CDADDR(EIP);
    CLRDATA_ADDRESS pMD;
    if (g_sos->GetMethodDescPtrFromIP(dwStartAddr, &pMD) != S_OK)
    {
        return 1;
    }

    return (size_t) pMD;
}

#ifndef FEATURE_PAL

//
// Gets version info for the CLR in the debuggee process.
//
BOOL GetEEVersion(VS_FIXEDFILEINFO *pFileInfo)
{
    _ASSERTE(g_ExtSymbols2);
    _ASSERTE(pFileInfo);
    // Grab the version info directly from the module.
    return g_ExtSymbols2->GetModuleVersionInformation(DEBUG_ANY_ID,
                                                   moduleInfo[GetEEFlavor()].baseAddr,
                                                   "\\", pFileInfo, sizeof(VS_FIXEDFILEINFO), NULL) == S_OK;
}

extern HMODULE g_hInstance;
BOOL GetSOSVersion(VS_FIXEDFILEINFO *pFileInfo)
{
    _ASSERTE(pFileInfo);
    
    WCHAR wszFullPath[MAX_LONGPATH];
    DWORD cchFullPath = GetModuleFileNameW(g_hInstance, wszFullPath, _countof(wszFullPath));
    
    DWORD dwHandle = 0;
    DWORD infoSize = GetFileVersionInfoSizeW(wszFullPath, &dwHandle);
    if (infoSize)
    {
        ArrayHolder<BYTE> pVersionInfo = new BYTE[infoSize];
        if (pVersionInfo)
        {
            if (GetFileVersionInfoW(wszFullPath, NULL, infoSize, pVersionInfo))
            {
                VS_FIXEDFILEINFO *pTmpFileInfo = NULL;
                UINT uLen = 0;
                if (VerQueryValue(pVersionInfo, "\\", (LPVOID *) &pTmpFileInfo, &uLen))
                {
                    *pFileInfo = *pTmpFileInfo; // Copy the info
                    return TRUE;
                }
            }
        }
    }
    
    return FALSE;
}

#endif // !FEATURE_PAL
    
size_t ObjectSize(DWORD_PTR obj,BOOL fIsLargeObject)
{
    DWORD_PTR dwMT;
    MOVE(dwMT, obj);
    return ObjectSize(obj, dwMT, FALSE, fIsLargeObject);
}

size_t ObjectSize(DWORD_PTR obj, DWORD_PTR mt, BOOL fIsValueClass, BOOL fIsLargeObject)
{
    BOOL bContainsPointers;
    size_t size = 0;
    if (!GetSizeEfficient(obj, mt, fIsLargeObject, size, bContainsPointers))
    {
        return 0;
    }
    return size;
}

// This takes an array of values and sets every non-printable character
// to be a period.
void Flatten(__out_ecount(len) char *data, unsigned int len)
{
    for (unsigned int i = 0; i < len; ++i)
        if (data[i] < 32 || data[i] > 126)
            data[i] = '.';
    data[len] = 0;
}

void CharArrayContent(TADDR pos, ULONG num, bool widechar)
{
    if (!pos || num <= 0)
        return;

    if (widechar)
    {
        ArrayHolder<WCHAR> data = new WCHAR[num+1];
        if (!data)
        {
            ReportOOM();
            return;
        }

        ULONG readLen = 0;
        if (!SafeReadMemory(pos, data, num<<1, &readLen))
            return;

        Flatten(data.GetPtr(), readLen >> 1);
        ExtOut("%S", data.GetPtr());
    }
    else
    {
        ArrayHolder<char> data = new char[num+1];
        if (!data)
        {
            ReportOOM();
            return;
        }

        ULONG readLen = 0;
        if (!SafeReadMemory(pos, data, num, &readLen))
            return;

        _ASSERTE(readLen <= num);
        Flatten(data, readLen);
        
        ExtOut("%s", data.GetPtr());
    }
}

void StringObjectContent(size_t obj, BOOL fLiteral, const int length)
{
    DacpObjectData objData;
    if (objData.Request(g_sos, TO_CDADDR(obj))!=S_OK)
    {
        ExtOut("<Invalid Object>");
        return;
    }
    
    strobjInfo stInfo;

    if (MOVE(stInfo,obj) != S_OK)
    {
        ExtOut ("Error getting string data\n");
        return;
    }

    if (objData.Size > 0x200000 ||
        stInfo.m_StringLength > 0x200000)
    {
        ExtOut ("<String is invalid or too large to print>\n");
        return;
    }
    
    ArrayHolder<WCHAR> pwszBuf = new WCHAR[stInfo.m_StringLength+1];
    if (pwszBuf == NULL)
    {
        return;
    }
    
    DWORD_PTR dwAddr = (DWORD_PTR)pwszBuf.GetPtr();
    if (g_sos->GetObjectStringData(TO_CDADDR(obj), stInfo.m_StringLength+1, pwszBuf, NULL)!=S_OK)
    {
        ExtOut("Error getting string data\n");
        return;
    }

    if (!fLiteral) 
    {
        pwszBuf[stInfo.m_StringLength] = L'\0';
        ExtOut ("%S", pwszBuf.GetPtr());
    }
    else
    {
        ULONG32 count = stInfo.m_StringLength;
        WCHAR buffer[256];
        WCHAR out[512];
        while (count) 
        {
            DWORD toRead = 255;
            if (count < toRead)
                toRead = count;

            ULONG bytesRead;
            wcsncpy_s(buffer,_countof(buffer),(LPWSTR) dwAddr, toRead);
            bytesRead = toRead*sizeof(WCHAR);
            DWORD wcharsRead = bytesRead/2;
            buffer[wcharsRead] = L'\0';
            
            ULONG j,k=0;
            for (j = 0; j < wcharsRead; j ++) 
            {
                if (_iswprint (buffer[j])) {
                    out[k] = buffer[j];
                    k ++;
                }
                else
                {
                    out[k++] = L'\\';
                    switch (buffer[j]) {
                    case L'\n':
                        out[k++] = L'n';
                        break;
                    case L'\0':
                        out[k++] = L'0';
                        break;
                    case L'\t':
                        out[k++] = L't';
                        break;
                    case L'\v':
                        out[k++] = L'v';
                        break;
                    case L'\b':
                        out[k++] = L'b';
                        break;
                    case L'\r':
                        out[k++] = L'r';
                        break;
                    case L'\f':
                        out[k++] = L'f';
                        break;
                    case L'\a':
                        out[k++] = L'a';
                        break;
                    case L'\\':
                        break;
                    case L'\?':
                        out[k++] = L'?';
                        break;
                    default:
                        out[k++] = L'?';
                        break;
                    }
                }
            }

            out[k] = L'\0';
            ExtOut ("%S", out);

            count -= wcharsRead;
            dwAddr += bytesRead;
        }
    }
}

#ifdef _TARGET_WIN64_

#include <limits.h>

__int64 str64hex(const char *ptr)
{
    __int64 value = 0;
    unsigned char nCount = 0;
    
    if(ptr==NULL)
        return 0;

    // Ignore leading 0x if present
    if (*ptr=='0' && toupper(*(ptr+1))=='X') {
        ptr = ptr + 2;
    }

    while (1) {        

        char digit;
        
        if (isdigit(*ptr)) {
            digit = *ptr - '0';
        } else if (isalpha(*ptr)) {
            digit = (((char)toupper(*ptr)) - 'A') + 10;
            if (digit >= 16) {
                break; // terminate
            }
        } else {
            break;
        }

        if (nCount>15) {
            return _UI64_MAX;     // would be an overflow
        }
            
        value = value << 4;        
        value |= digit;

        ptr++;
        nCount++;
    }
    
    return value;    
}

#endif // _TARGET_WIN64_

BOOL GetValueForCMD (const char *ptr, const char *end, ARGTYPE type, size_t *value)
{   
    if (type == COSTRING) {
        // Allocate memory for the length of the string. Whitespace terminates
        // User must free the string data. 
        char *pszValue = NULL;
        size_t dwSize = (end - ptr);    
        pszValue= new char[dwSize+1];
        if (pszValue == NULL)
        {
            return FALSE;
        }
        strncpy_s(pszValue,dwSize+1,ptr,dwSize); // _TRUNCATE
        *value = (size_t) pszValue;               
    } else {
        char *last;
        if (type == COHEX) {
#ifdef _TARGET_WIN64_
            *value = str64hex(ptr);
#else
            *value = strtoul(ptr,&last,16);
#endif
        }
        else {     
#ifdef _TARGET_WIN64_
            *value = _atoi64(ptr);
#else
            *value = strtoul(ptr,&last,10);
#endif
        }

#ifdef _TARGET_WIN64_
        last = (char *) ptr;
        // Ignore leading 0x if present
        if (*last=='0' && toupper(*(last+1))=='X') {
            last = last + 2;
        }

        while (isdigit(*last) || (toupper(*last)>='A' && toupper(*last)<='F')) {
            last++;
        }
#endif

        if (last != end) {
            return FALSE;
        }
    }

    return TRUE;
}

void SetValueForCMD (void *vptr, ARGTYPE type, size_t value)
{
    switch (type) {
    case COBOOL:
        *(BOOL*)vptr = (BOOL) value;
        break;
    case COSIZE_T:
    case COSTRING:
    case COHEX:
        *(SIZE_T*)vptr = value;
        break;
    }
}

BOOL GetCMDOption(const char *string, CMDOption *option, size_t nOption,
                  CMDValue *arg, size_t maxArg, size_t *nArg)
{
    const char *end;
    const char *ptr = string;
    BOOL endofOption = FALSE;

    for (size_t n = 0; n < nOption; n ++)
    {
        if (IsInterrupt())
            return FALSE;
        
        option[n].hasSeen = FALSE;
    }

    if (nArg) {
        *nArg = 0;
    }

    while (ptr[0] != '\0')
    {
        if (IsInterrupt())
            return FALSE;
        
        // skip any space
        if (isspace (ptr[0])) {
            while (isspace (ptr[0]))
            {
                if (IsInterrupt())
                    return FALSE;
        
                ptr ++;
            }
            
            continue;
        }

        end = ptr;

        // Arguments can be quoted with ". We'll remove the quotes and
        // allow spaces to exist in the string.
        BOOL bQuotedArg = FALSE;
        if (ptr[0] == '\'' && ptr[1] != '-')
        {            
            bQuotedArg = TRUE;

            // skip quote
            ptr++;
            end++;
            
            while (end[0] != '\'' && end[0] != '\0')
            {
                if (IsInterrupt())
                    return FALSE;
            
                end ++;
            }
            if (end[0] != '\'')
            {
                // Error, th ere was a start quote but no end quote
                ExtOut ("Missing quote in %s\n", ptr);
                return FALSE;
            }
        }
        else // whitespace terminates
        {
            while (!isspace(end[0]) && end[0] != '\0')
            {
                if (IsInterrupt())
                    return FALSE;
            
                end ++;
            }
        }

#ifndef FEATURE_PAL
        if (ptr[0] != '-' && ptr[0] != '/') {
#else
        if (ptr[0] != '-') {
#endif
            if (maxArg == 0) {
                ExtOut ("Incorrect argument: %s\n", ptr);
                return FALSE;
            }
            endofOption = TRUE;
            if (*nArg >= maxArg) {
                ExtOut ("Incorrect argument: %s\n", ptr);
                return FALSE;
            }
            
            size_t value;
            if (!GetValueForCMD (ptr,end,arg[*nArg].type,&value)) {

                char oldChar = *end;
                *(char *)end = '\0';
                value = (size_t)GetExpression (ptr);
                *(char *)end = oldChar;
                
                /*

                    It is silly to do this, what if 0 is a valid expression for
                    the command?
                    
                if (value == 0) {
                    ExtOut ("Invalid argument: %s\n", ptr);
                    return FALSE;
                }
                */
            }

            SetValueForCMD (arg[*nArg].vptr, arg[*nArg].type, value);

            (*nArg) ++;
        }
        else if (endofOption) {
            ExtOut ("Wrong option: %s\n", ptr);
            return FALSE;
        }
        else {
            char buffer[80];
            if (end-ptr > 79) {
                ExtOut ("Invalid option %s\n", ptr);
                return FALSE;
            }
            strncpy_s (buffer,_countof(buffer), ptr, end-ptr);

            size_t n;
            for (n = 0; n < nOption; n ++)
            {
                if (IsInterrupt())
                    return FALSE;
        
                if (_stricmp (buffer, option[n].name) == 0) {
                    if (option[n].hasSeen) {
                        ExtOut ("Invalid option: option specified multiple times: %s\n", buffer);
                        return FALSE;
                    }
                    option[n].hasSeen = TRUE;
                    if (option[n].hasValue) {
                        // skip any space
                        ptr = end;
                        if (isspace (ptr[0])) {
                            while (isspace (ptr[0]))
                            {
                                if (IsInterrupt())
                                    return FALSE;
        
                                ptr ++;
                            }
                        }
                        if (ptr[0] == '\0') {
                            ExtOut ("Missing value for option %s\n", buffer);
                            return FALSE;
                        }
                        end = ptr;
                        while (!isspace(end[0]) && end[0] != '\0')
                        {
                            if (IsInterrupt())
                                return FALSE;
        
                            end ++;
                        }

                        size_t value;
                        if (!GetValueForCMD (ptr,end,option[n].type,&value)) {

                            char oldChar = *end;
                            *(char *)end = '\0';
                            value = (size_t)GetExpression (ptr);
                            *(char *)end = oldChar;
                        }

                        SetValueForCMD (option[n].vptr,option[n].type,value);
                    }
                    else {
                        SetValueForCMD (option[n].vptr,option[n].type,TRUE);
                    }
                    break;
                }
            }
            if (n == nOption) {
                ExtOut ("Unknown option: %s\n", buffer);
                return FALSE;
            }
        }

        ptr = end;
        if (bQuotedArg)
        {
            ptr++;
        }
    }
    return TRUE;
}

ReadVirtualCache g_special_rvCacheSpace;
ReadVirtualCache *rvCache = &g_special_rvCacheSpace;

void ResetGlobals(void)
{
    // There are some globals used in SOS that exist for efficiency in one command,
    // but should be reset because the next execution of an SOS command could be on
    // another managed process. Reset them to a default state here, as this command
    // is called on every SOS entry point.
    g_sos->GetUsefulGlobals(&g_special_usefulGlobals);
    g_special_mtCache.Clear();
    g_special_rvCacheSpace.Clear();
    Output::ResetIndent();
}

//---------------------------------------------------------------------------------------
//
// Loads private DAC interface, and points g_clrData to it.
//
// Return Value:
//      HRESULT indicating success or failure
//
HRESULT LoadClrDebugDll(void)
{
    HRESULT hr = S_OK;
#ifdef FEATURE_PAL
    static IXCLRDataProcess* s_clrDataProcess = NULL;
    if (s_clrDataProcess == NULL)
    {
        int err = PAL_InitializeDLL();
        if(err != 0)
        {
            return CORDBG_E_UNSUPPORTED;
        }
        char dacModulePath[MAX_LONGPATH];
        strcpy_s(dacModulePath, _countof(dacModulePath), g_ExtServices->GetCoreClrDirectory());
        strcat_s(dacModulePath, _countof(dacModulePath), MAKEDLLNAME_A("mscordaccore"));

        HMODULE hdac = LoadLibraryA(dacModulePath);
        if (hdac == NULL)
        {
            return CORDBG_E_MISSING_DEBUGGER_EXPORTS;
        }
        PFN_CLRDataCreateInstance pfnCLRDataCreateInstance = (PFN_CLRDataCreateInstance)GetProcAddress(hdac, "CLRDataCreateInstance");
        if (pfnCLRDataCreateInstance == NULL)
        {
            FreeLibrary(hdac);
            return CORDBG_E_MISSING_DEBUGGER_EXPORTS;
        }
        ICLRDataTarget *target = new DataTarget();
        hr = pfnCLRDataCreateInstance(__uuidof(IXCLRDataProcess), target, (void**)&s_clrDataProcess);
        if (FAILED(hr))
        {
            s_clrDataProcess = NULL;
            return hr;
        }
        ULONG32 flags = 0;
        s_clrDataProcess->GetOtherNotificationFlags(&flags);
        flags |= (CLRDATA_NOTIFY_ON_MODULE_LOAD | CLRDATA_NOTIFY_ON_MODULE_UNLOAD | CLRDATA_NOTIFY_ON_EXCEPTION);
        s_clrDataProcess->SetOtherNotificationFlags(flags);
    }
    g_clrData = s_clrDataProcess;
    g_clrData->AddRef();
    g_clrData->Flush();
#else
    WDBGEXTS_CLR_DATA_INTERFACE Query;

    Query.Iid = &__uuidof(IXCLRDataProcess);
    if (!Ioctl(IG_GET_CLR_DATA_INTERFACE, &Query, sizeof(Query)))
    {
        return E_FAIL;
    }

    g_clrData = (IXCLRDataProcess*)Query.Iface;
#endif
    hr = g_clrData->QueryInterface(__uuidof(ISOSDacInterface), (void**)&g_sos);
    if (FAILED(hr))
    {
        g_sos = NULL;
        return hr;
    }
    return S_OK;
}

#ifndef FEATURE_PAL

// This structure carries some input/output data to the FindFileInPathCallback below
typedef struct _FindFileCallbackData
{
    DWORD timestamp;
    DWORD filesize;
    HMODULE hModule;
} FindFileCallbackData;


// A callback used by SymFindFileInPath - called once for each file that matches
// the initial search criteria and allows the user to do arbitrary processing
// This implementation checks that filesize and timestamp are correct, then
// saves the loaded module handle
// Parameters
//           filename - the full path the file which was found
//           context - a user specified pointer to arbitrary data, in this case a FindFileCallbackData
// Return Value
//           TRUE if the search should continue (the file is no good)
//           FALSE if the search should stop (the file is good)
BOOL
FindFileInPathCallback(
    ___in PCWSTR filename,
    ___in PVOID context
    )
{
    HRESULT hr;
    FindFileCallbackData* pCallbackData;
    pCallbackData = (FindFileCallbackData*)context;
    if (!pCallbackData)
        return TRUE;

    pCallbackData->hModule = LoadLibraryExW(
        filename,
        NULL,                               //  __reserved
        LOAD_WITH_ALTERED_SEARCH_PATH);     // Ensure we check the dir in wszFullPath first
    if (pCallbackData->hModule == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
        ExtOut("Unable to load '%S'.  HRESULT = 0x%x.\n", filename, hr);
        return TRUE;
    }
    
    // Did we load the right one?
    MODULEINFO modInfo = {0};
    if (!GetModuleInformation(
        GetCurrentProcess(),
        pCallbackData->hModule,
        &modInfo,
        sizeof(modInfo)))
    {
        ExtOut("Failed to read module information for '%S'.  HRESULT = 0x%x.\n", filename, HRESULT_FROM_WIN32(GetLastError()));
        FreeLibrary(pCallbackData->hModule);
        return TRUE;
    }

    IMAGE_DOS_HEADER * pDOSHeader = (IMAGE_DOS_HEADER *) modInfo.lpBaseOfDll;
    IMAGE_NT_HEADERS * pNTHeaders = (IMAGE_NT_HEADERS *) (((LPBYTE) modInfo.lpBaseOfDll) + pDOSHeader->e_lfanew);
    DWORD dwSizeActual = pNTHeaders->OptionalHeader.SizeOfImage;
    DWORD dwTimeStampActual = pNTHeaders->FileHeader.TimeDateStamp;
    if ((dwSizeActual != pCallbackData->filesize) || (dwTimeStampActual != pCallbackData->timestamp))
    {
        ExtOut("Found '%S', but it does not match the CLR being debugged.\n", filename);
        ExtOut("Size: Expected '0x%x', Actual '0x%x'\n", pCallbackData->filesize, dwSizeActual);
        ExtOut("Time stamp: Expected '0x%x', Actual '0x%x'\n", pCallbackData->timestamp, dwTimeStampActual);
        FreeLibrary(pCallbackData->hModule);
        return TRUE;
    }

    ExtOut("Loaded %S\n", filename);
    return FALSE;
}

#endif // FEATURE_PAL

//---------------------------------------------------------------------------------------
// Provides a way for the public CLR debugging interface to find the appropriate
// mscordbi.dll, DAC, etc.
class SOSLibraryProvider : public ICLRDebuggingLibraryProvider
{
public:
    SOSLibraryProvider() : m_ref(0)
    {
    }

    virtual ~SOSLibraryProvider() {}

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(
        REFIID InterfaceId,
        PVOID* pInterface)
    {
        if (InterfaceId == IID_IUnknown)
        {
            *pInterface = static_cast<IUnknown *>(this);
        }
        else if (InterfaceId == IID_ICLRDebuggingLibraryProvider)
        {
            *pInterface = static_cast<ICLRDebuggingLibraryProvider *>(this);
        }
        else
        {
            *pInterface = NULL;
            return E_NOINTERFACE;
        }

        AddRef();
        return S_OK;
    }
    
    virtual ULONG STDMETHODCALLTYPE AddRef()
    {
        return InterlockedIncrement(&m_ref);    
    }

    virtual ULONG STDMETHODCALLTYPE Release()
    {
        LONG ref = InterlockedDecrement(&m_ref);
        if (ref == 0)
        {
            delete this;
        }
        return ref;
    }



    // Called by the shim to locate and load mscordacwks and mscordbi
    // Parameters:
    //    pwszFileName - the name of the file to load
    //    dwTimestamp - the expected timestamp of the file
    //    dwSizeOfImage - the expected SizeOfImage (a PE header data value)
    //    phModule - a handle to loaded module
    //
    // Return Value
    //    S_OK if the file was loaded, or any error if not
    virtual HRESULT STDMETHODCALLTYPE ProvideLibrary(
        const WCHAR * pwszFileName,
        DWORD dwTimestamp,
        DWORD dwSizeOfImage,
        HMODULE * phModule)
    {
#ifndef FEATURE_PAL
        HRESULT hr;
        FindFileCallbackData callbackData = {0};
        callbackData.timestamp = dwTimestamp;
        callbackData.filesize = dwSizeOfImage;

        if ((phModule == NULL) || (pwszFileName == NULL))
        {
            return E_INVALIDARG;
        }

        HMODULE dacModule;
        if(g_sos == NULL)
        {
            // we ensure that windbg loads DAC first so that we can be sure to use the same one
            return E_UNEXPECTED;
        }
        if (FAILED(hr = g_sos->GetDacModuleHandle(&dacModule)))
        {
            ExtOut("Failed to get the dac module handle. hr=0x%x.\n", hr);
            return hr;
        }

        WCHAR dacPath[MAX_LONGPATH];
        DWORD len = GetModuleFileNameW(dacModule, dacPath, MAX_LONGPATH);
        if(len == 0 || len == MAX_LONGPATH)
        {
            ExtOut("GetModuleFileName(dacModuleHandle) failed. Last error = 0x%x\n", GetLastError());
            return E_FAIL;
        }

        // if we are looking for the DAC, just load the one windbg already found
        if(_wcsncmp(pwszFileName, W("mscordac"), _wcslen(W("mscordac")))==0)
        {
            FindFileInPathCallback(dacPath, &callbackData);
            *phModule = callbackData.hModule;
            return hr;
        }

        ULONG64 hProcess;
        hr = g_ExtSystem->GetCurrentProcessHandle(&hProcess);
        if (FAILED(hr))
        {
            ExtOut("IDebugSystemObjects::GetCurrentProcessHandle HRESULT=0x%x.\n", hr);
            return hr;
        }

        ToRelease<IDebugSymbols3> spSym3(NULL);
        hr = g_ExtSymbols->QueryInterface(__uuidof(IDebugSymbols3), (void**)&spSym3);
        if (FAILED(hr))
        {
            ExtOut("Unable to query IDebugSymbol3 HRESULT=0x%x.\n", hr);
            return hr;
        }

        ULONG pathSize = 0;
        hr = spSym3->GetSymbolPathWide(NULL, 0, &pathSize);
        if(FAILED(hr)) //S_FALSE if the path doesn't fit, but if the path was size 0 perhaps we would get S_OK?
        {
            ExtOut("Unable to get symbol path length. IDebugSymbols3::GetSymbolPathWide HRESULT=0x%x.\n", hr);
            return hr;
        }

        ArrayHolder<WCHAR> symbolPath = new WCHAR[pathSize+MAX_LONGPATH+1];



        hr = spSym3->GetSymbolPathWide(symbolPath, pathSize, NULL);
        if(S_OK != hr)
        {
            ExtOut("Unable to get symbol path. IDebugSymbols3::GetSymbolPathWide HRESULT=0x%x.\n", hr);
            return hr;
        }
        
        WCHAR foundPath[MAX_LONGPATH];
        BOOL rc = SymFindFileInPathW((HANDLE)hProcess,
                                symbolPath,
                                pwszFileName,
                                (PVOID)(ULONG_PTR) dwTimestamp,
                                dwSizeOfImage,
                                0,
                                SSRVOPT_DWORD,
                                foundPath,
                                (PFINDFILEINPATHCALLBACKW) &FindFileInPathCallback,
                                (PVOID) &callbackData
                               );
        if(!rc)
        {
            hr = HRESULT_FROM_WIN32(GetLastError());
            ExtOut("SymFindFileInPath failed for %S. HRESULT=0x%x.\nPlease ensure that %S is on your symbol path.", pwszFileName, hr, pwszFileName);
        }

        *phModule = callbackData.hModule;
        return hr;
#else
        WCHAR modulePath[MAX_LONGPATH];
        int length = MultiByteToWideChar(CP_ACP, 0, g_ExtServices->GetCoreClrDirectory(), -1, modulePath, _countof(modulePath));
        if (0 >= length)
        {
            ExtOut("MultiByteToWideChar(coreclrDirectory) failed. Last error = 0x%x\n", GetLastError());
            return E_FAIL;
        }
        wcscat_s(modulePath, _countof(modulePath), pwszFileName);

        *phModule = LoadLibraryW(modulePath);
        if (*phModule == NULL)
        {
            HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
            ExtOut("Unable to load '%S'.  HRESULT = 0x%x.\n", pwszFileName, hr);
            return hr;
        }
        return S_OK;
#endif // FEATURE_PAL
    }

protected:
    LONG m_ref;
};

//---------------------------------------------------------------------------------------
// Data target for the debugged process.   Provided to OpenVirtualProcess in order to
// get an ICorDebugProcess back
// 
class SOSDataTarget : public ICorDebugMutableDataTarget
#ifdef FEATURE_PAL
, public ICorDebugDataTarget4
#endif
{
public:
    SOSDataTarget() : m_ref(0)
    {
    }

    virtual ~SOSDataTarget() {}

    virtual HRESULT STDMETHODCALLTYPE QueryInterface(
        REFIID InterfaceId,
        PVOID* pInterface)
    {
        if (InterfaceId == IID_IUnknown)
        {
            *pInterface = static_cast<IUnknown *>(static_cast<ICorDebugDataTarget *>(this));
        }
        else if (InterfaceId == IID_ICorDebugDataTarget)
        {
            *pInterface = static_cast<ICorDebugDataTarget *>(this);
        }
        else if (InterfaceId == IID_ICorDebugMutableDataTarget)
        {
            *pInterface = static_cast<ICorDebugMutableDataTarget *>(this);
        }
#ifdef FEATURE_PAL
        else if (InterfaceId == IID_ICorDebugDataTarget4)
        {
            *pInterface = static_cast<ICorDebugDataTarget4 *>(this);
        }
#endif
        else
        {
            *pInterface = NULL;
            return E_NOINTERFACE;
        }

        AddRef();
        return S_OK;
    }
    
    virtual ULONG STDMETHODCALLTYPE AddRef()
    {
        return InterlockedIncrement(&m_ref);    
    }

    virtual ULONG STDMETHODCALLTYPE Release()
    {
        LONG ref = InterlockedDecrement(&m_ref);
        if (ref == 0)
        {
            delete this;
        }
        return ref;
    }

    //
    // ICorDebugDataTarget.
    //

    virtual HRESULT STDMETHODCALLTYPE GetPlatform(CorDebugPlatform * pPlatform)
    {
        ULONG platformKind = g_targetMachine->GetPlatform();
#ifdef FEATURE_PAL        
        if(platformKind == IMAGE_FILE_MACHINE_I386)
            *pPlatform = CORDB_PLATFORM_POSIX_X86;
        else if(platformKind == IMAGE_FILE_MACHINE_AMD64)
            *pPlatform = CORDB_PLATFORM_POSIX_AMD64;
        else if(platformKind == IMAGE_FILE_MACHINE_ARMNT)
            *pPlatform = CORDB_PLATFORM_POSIX_ARM;
        else
            return E_FAIL;
#else
        if(platformKind == IMAGE_FILE_MACHINE_I386)
            *pPlatform = CORDB_PLATFORM_WINDOWS_X86;
        else if(platformKind == IMAGE_FILE_MACHINE_AMD64)
            *pPlatform = CORDB_PLATFORM_WINDOWS_AMD64;
        else if(platformKind == IMAGE_FILE_MACHINE_ARMNT)
            *pPlatform = CORDB_PLATFORM_WINDOWS_ARM;
        else if(platformKind == IMAGE_FILE_MACHINE_ARM64)
            *pPlatform = CORDB_PLATFORM_WINDOWS_ARM64;
        else
            return E_FAIL;        
#endif        
    
        return S_OK;
    }

    virtual HRESULT STDMETHODCALLTYPE ReadVirtual( 
        CORDB_ADDRESS address,
        BYTE * pBuffer,
        ULONG32 request,
        ULONG32 * pcbRead)
    {
        if (g_ExtData == NULL)
        {
            return E_UNEXPECTED;
        }
        return g_ExtData->ReadVirtual(address, pBuffer, request, (PULONG) pcbRead);
    }

    virtual HRESULT STDMETHODCALLTYPE GetThreadContext(
        DWORD dwThreadOSID,
        ULONG32 contextFlags,
        ULONG32 contextSize,
        BYTE * context)
    {
#ifdef FEATURE_PAL
        if (g_ExtSystem == NULL)
        {
            return E_UNEXPECTED;
        }
        return g_ExtSystem->GetThreadContextById(dwThreadOSID, contextFlags, contextSize, context);
#else
        ULONG ulThreadIDOrig;
        ULONG ulThreadIDRequested;
        HRESULT hr;
        HRESULT hrRet;

        hr = g_ExtSystem->GetCurrentThreadId(&ulThreadIDOrig);
        if (FAILED(hr))
        {
            return hr;
        }

        hr = g_ExtSystem->GetThreadIdBySystemId(dwThreadOSID, &ulThreadIDRequested);
        if (FAILED(hr))
        {
            return hr;
        }

        hr = g_ExtSystem->SetCurrentThreadId(ulThreadIDRequested);
        if (FAILED(hr))
        {
            return hr;
        }

        // Prepare context structure
        ZeroMemory(context, contextSize);
        ((CONTEXT*) context)->ContextFlags = contextFlags;

        // Ok, do it!
        hrRet = g_ExtAdvanced3->GetThreadContext((LPVOID) context, contextSize);

        // This is cleanup; failure here doesn't mean GetThreadContext should fail
        // (that's determined by hrRet).
        g_ExtSystem->SetCurrentThreadId(ulThreadIDOrig);

        return hrRet;
#endif // FEATURE_PAL
    }

    //
    // ICorDebugMutableDataTarget.
    //
    virtual HRESULT STDMETHODCALLTYPE WriteVirtual(CORDB_ADDRESS address,
                                                   const BYTE * pBuffer,
                                                   ULONG32 bytesRequested)
    {
        if (g_ExtData == NULL)
        {
            return E_UNEXPECTED;
        }
        return g_ExtData->WriteVirtual(address, (PVOID)pBuffer, bytesRequested, NULL);
    }

    virtual HRESULT STDMETHODCALLTYPE SetThreadContext(DWORD dwThreadID,
                                                       ULONG32 contextSize,
                                                       const BYTE * pContext)
    {
        return E_NOTIMPL;
    }

    virtual HRESULT STDMETHODCALLTYPE ContinueStatusChanged(DWORD dwThreadId,
                                                            CORDB_CONTINUE_STATUS continueStatus)
    {
        return E_NOTIMPL;
    }

#ifdef FEATURE_PAL
    //
    // ICorDebugDataTarget4
    //
    virtual HRESULT STDMETHODCALLTYPE VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context)
    {
        if (g_ExtServices == NULL)
        {
            return E_UNEXPECTED;
        }
        return g_ExtServices->VirtualUnwind(threadId, contextSize, context);

    }
#endif // FEATURE_PAL

protected:
    LONG m_ref;
};

HRESULT InitCorDebugInterfaceFromModule(ULONG64 ulBase, ICLRDebugging * pClrDebugging)
{
    HRESULT hr;

    ToRelease<ICorDebugMutableDataTarget> pSOSDataTarget = new SOSDataTarget;
    pSOSDataTarget->AddRef();

    ToRelease<ICLRDebuggingLibraryProvider> pSOSLibraryProvider = new SOSLibraryProvider;
    pSOSLibraryProvider->AddRef();

    CLR_DEBUGGING_VERSION clrDebuggingVersionRequested = {0};
    clrDebuggingVersionRequested.wMajor = 4;

    CLR_DEBUGGING_VERSION clrDebuggingVersionActual = {0};

    CLR_DEBUGGING_PROCESS_FLAGS clrDebuggingFlags = (CLR_DEBUGGING_PROCESS_FLAGS)0;

    ToRelease<IUnknown> pUnkProcess;

    hr = pClrDebugging->OpenVirtualProcess(
        ulBase,
        pSOSDataTarget,
        pSOSLibraryProvider,
        &clrDebuggingVersionRequested,
        IID_ICorDebugProcess,
        &pUnkProcess,
        &clrDebuggingVersionActual,
        &clrDebuggingFlags);
    if (FAILED(hr))
    {
        return hr;
    }

    ICorDebugProcess * pCorDebugProcess = NULL;
    hr = pUnkProcess->QueryInterface(IID_ICorDebugProcess, (PVOID*) &pCorDebugProcess);
    if (FAILED(hr))
    {
        return hr;
    }

    // Transfer memory ownership of refcount to global
    g_pCorDebugProcess = pCorDebugProcess;
    return S_OK;
}

//---------------------------------------------------------------------------------------
//
// Unloads public ICorDebug interfaces, and clears g_pCorDebugProcess
// This is only needed once after CLR unloads, not after every InitCorDebugInterface call
//
VOID UninitCorDebugInterface()
{
    if(g_pCorDebugProcess != NULL)
    {
        g_pCorDebugProcess->Detach();
        g_pCorDebugProcess->Release();
        g_pCorDebugProcess = NULL;
    }
}

//---------------------------------------------------------------------------------------
//
// Loads public ICorDebug interfaces, and points g_pCorDebugProcess to them
// This should be called at least once per windbg stop state to ensure that
// the interface is available and that it doesn't hold stale data. Calling it
// more than once isn't an error, but does have perf overhead from needlessly
// flushing memory caches.
//
// Return Value:
//      HRESULT indicating success or failure
//

HRESULT InitCorDebugInterface()
{
    HMODULE hModule = NULL;
    HRESULT hr;
    ToRelease<ICLRDebugging> pClrDebugging;

    // we may already have an ICorDebug instance we can use
    if(g_pCorDebugProcess != NULL)
    {
        // ICorDebugProcess4 is currently considered a private experimental interface on ICorDebug, it might go away so
        // we need to be sure to handle its absense gracefully
        ToRelease<ICorDebugProcess4> pProcess4 = NULL;
        if(SUCCEEDED(g_pCorDebugProcess->QueryInterface(__uuidof(ICorDebugProcess4), (void**)&pProcess4)))
        {
            // FLUSH_ALL is more expensive than PROCESS_RUNNING, but this allows us to be safe even if things
            // like IDNA are in use where we might be looking at non-sequential snapshots of process state
            if(SUCCEEDED(pProcess4->ProcessStateChanged(FLUSH_ALL)))
            {
                // we already have an ICorDebug instance loaded and flushed, nothing more to do
                return S_OK;
            }
        }

        // this is a very heavy handed way of reseting
        UninitCorDebugInterface();
    }

    // SOS now has a statically linked version of the loader code that is normally found in mscoree/mscoreei.dll
    // Its not much code and takes a big step towards 0 install dependencies
    // Need to pick the appropriate SKU of CLR to detect
#if defined(FEATURE_CORESYSTEM)
    GUID skuId = CLR_ID_ONECORE_CLR;
#elif defined(FEATURE_CORECLR)
    GUID skuId = CLR_ID_CORECLR;
#else
    GUID skuId = CLR_ID_V4_DESKTOP;
#endif
    CLRDebuggingImpl* pDebuggingImpl = new CLRDebuggingImpl(skuId);
    hr = pDebuggingImpl->QueryInterface(IID_ICLRDebugging, (LPVOID *)&pClrDebugging);
    if (FAILED(hr))
    {
        delete pDebuggingImpl;
        return hr;
    }

#ifndef FEATURE_PAL
    ULONG cLoadedModules;
    ULONG cUnloadedModules;
    hr = g_ExtSymbols->GetNumberModules(&cLoadedModules, &cUnloadedModules);
    if (FAILED(hr))
    {
        return hr;
    }

    ULONG64 ulBase;
    for (ULONG i = 0; i < cLoadedModules; i++)
    {
        hr = g_ExtSymbols->GetModuleByIndex(i, &ulBase);
        if (FAILED(hr))
        {
            return hr;
        }

        // Dunno if this is a CLR module or not (or even if it's the particular one the
        // user cares about during inproc SxS scenarios).  For now, just try to use it
        // to grab an ICorDebugProcess.  If it works, great.  Else, continue the loop
        // until we find the first one that works.
        hr = InitCorDebugInterfaceFromModule(ulBase, pClrDebugging);
        if (SUCCEEDED(hr))
        {
            return hr;
        }

        // On failure, just iterate to the next module and try again...
    }

    // Still here?  Didn't find the right module.
    // TODO: Anything useful to return or log here?
    return E_FAIL;
#else
    ULONG64 ulBase;
    hr = g_ExtSymbols->GetModuleByModuleName(MAIN_CLR_DLL_NAME_A, 0, NULL, &ulBase);
    if (SUCCEEDED(hr))
    {
        hr = InitCorDebugInterfaceFromModule(ulBase, pClrDebugging);
    }
    return hr;
#endif // FEATURE_PAL
}


typedef enum
{
    GC_HEAP_INVALID = 0,
    GC_HEAP_WKS     = 1,
    GC_HEAP_SVR     = 2
} GC_HEAP_TYPE;

/**********************************************************************\
* Routine Description:                                                 *
*                                                                      *
*    This function is called to find out if runtime is server build    *  
*                                                                      *
\**********************************************************************/

DacpGcHeapData *g_pHeapData = NULL;
DacpGcHeapData g_HeapData;

BOOL InitializeHeapData()
{
    if (g_pHeapData == NULL)
    {        
        if (g_HeapData.Request(g_sos) != S_OK)
        {
            return FALSE;
        }
        g_pHeapData = &g_HeapData;
    }
    return TRUE;
}

BOOL IsServerBuild() 
{
    return InitializeHeapData() ? g_pHeapData->bServerMode : FALSE;	
}

UINT GetMaxGeneration()
{
    return InitializeHeapData() ? g_pHeapData->g_max_generation : 0;	
}

UINT GetGcHeapCount()
{
    return InitializeHeapData() ? g_pHeapData->HeapCount : 0;	
}

BOOL GetGcStructuresValid()
{
    // We don't want to use the cached HeapData, because this can change
    // each time the program runs for a while.
    DacpGcHeapData heapData;
    if (heapData.Request(g_sos) != S_OK)
    {
        return FALSE;
    }

    return heapData.bGcStructuresValid;
}

void GetAllocContextPtrs(AllocInfo *pallocInfo)
{
    // gets the allocation contexts for all threads. This provides information about how much of 
    // the current allocation quantum has been allocated and the heap to which the quantum belongs. 
    // The allocation quantum is a fixed size chunk of zeroed memory from which allocations will come
    // until it's filled. Each managed thread has its own allocation context. 
     
    pallocInfo->num = 0;
    pallocInfo->array = NULL;    
    
    // get the thread store (See code:ClrDataAccess::RequestThreadStoreData for details)
    DacpThreadStoreData ThreadStore;
    if ( ThreadStore.Request(g_sos) != S_OK)
    {
        return;
    }

    int numThread = ThreadStore.threadCount;
    if (numThread)
    {
        pallocInfo->array = new needed_alloc_context[numThread];
        if (pallocInfo->array == NULL)
        {
            return;
        }
    }

    // get details for each thread in the thread store
    CLRDATA_ADDRESS CurThread = ThreadStore.firstThread;
    while (CurThread != NULL)
    {
        if (IsInterrupt())
            return;

        DacpThreadData Thread;
        // Get information about the thread (we're getting the values of several of the
        // fields of the Thread instance from the target) See code:ClrDataAccess::RequestThreadData for
        // details
        if (Thread.Request(g_sos, CurThread) != S_OK)
        {
            return;
        }

        if (Thread.allocContextPtr != 0)
        {
            // get a list of all the allocation contexts 
            int j;      
            for (j = 0; j < pallocInfo->num; j ++)
            {
                if (pallocInfo->array[j].alloc_ptr == (BYTE *) Thread.allocContextPtr)
                    break;
            }
            if (j == pallocInfo->num)
            {
                pallocInfo->num ++;
                pallocInfo->array[j].alloc_ptr = (BYTE *) Thread.allocContextPtr;
                pallocInfo->array[j].alloc_limit = (BYTE *) Thread.allocContextLimit;
            }
        }
        
        CurThread = Thread.nextThread;
    }
}

HRESULT ReadVirtualCache::Read(TADDR taOffset, PVOID Buffer, ULONG BufferSize, PULONG lpcbBytesRead)
{
    // sign extend the passed in Offset so we can use it in when calling 
    // IDebugDataSpaces::ReadVirtual()

    CLRDATA_ADDRESS Offset = TO_CDADDR(taOffset);
    // Offset can be any random ULONG64, as it can come from VerifyObjectMember(), and this
    // can pass random pointer values in case of GC heap corruption
    HRESULT ret;
    ULONG cbBytesRead = 0;

    if (BufferSize == 0)
        return S_OK;

    if (BufferSize > CACHE_SIZE)
    {
        // Don't even try with the cache
        return g_ExtData->ReadVirtual(Offset, Buffer, BufferSize, lpcbBytesRead);
    }

    if ((m_cacheValid)
        && (taOffset >= m_startCache) 
        && (taOffset <= m_startCache + m_cacheSize - BufferSize))

    {
        // It is within the cache
        memcpy(Buffer,(LPVOID) ((ULONG64)m_cache + (taOffset - m_startCache)), BufferSize);

        if (lpcbBytesRead != NULL)
        {
           *lpcbBytesRead = BufferSize;
        }
 
        return S_OK;
    }
 
    m_cacheValid = FALSE;
    m_startCache = taOffset;

    // avoid an int overflow
    if (m_startCache + CACHE_SIZE < m_startCache)
        m_startCache = (TADDR)(-CACHE_SIZE);

    ret = g_ExtData->ReadVirtual(TO_CDADDR(m_startCache), m_cache, CACHE_SIZE, &cbBytesRead);
    if (ret != S_OK)
    {
        return ret;
    }
    
    m_cacheSize = cbBytesRead;     
    m_cacheValid = TRUE;
    memcpy(Buffer, (LPVOID) ((ULONG64)m_cache + (taOffset - m_startCache)), BufferSize);

    if (lpcbBytesRead != NULL)
    {
        *lpcbBytesRead = cbBytesRead;
    }

    return S_OK;
}

HRESULT GetMTOfObject(TADDR obj, TADDR *mt)
{
    if (!mt)
        return E_POINTER;

    // Read the MethodTable and if we succeed, get rid of the mark bits.
    HRESULT hr = rvCache->Read(obj, mt, sizeof(TADDR), NULL);
    if (SUCCEEDED(hr))
        *mt &= ~3;

    return hr;
}

#ifndef FEATURE_PAL

StressLogMem::~StressLogMem ()
{
    MemRange * range = list;
    
    while (range)
    {
        MemRange * temp = range->next;
        delete range;
        range = temp;
    }
}

bool StressLogMem::Init (ULONG64 stressLogAddr, IDebugDataSpaces* memCallBack)
{
    size_t ThreadStressLogAddr = NULL;
    HRESULT hr = memCallBack->ReadVirtual(UL64_TO_CDA(stressLogAddr + offsetof (StressLog, logs)), 
            &ThreadStressLogAddr, sizeof (ThreadStressLogAddr), 0);
    if (hr != S_OK)
    {
        return false;
    }    
   
    while(ThreadStressLogAddr != NULL) 
    {
        size_t ChunkListHeadAddr = NULL;
        hr = memCallBack->ReadVirtual(TO_CDADDR(ThreadStressLogAddr + ThreadStressLog::OffsetOfListHead ()), 
            &ChunkListHeadAddr, sizeof (ChunkListHeadAddr), 0);
        if (hr != S_OK || ChunkListHeadAddr == NULL)
        {
            return false;
        }

        size_t StressLogChunkAddr = ChunkListHeadAddr;
        
        do
        {
            AddRange (StressLogChunkAddr, sizeof (StressLogChunk));
            hr = memCallBack->ReadVirtual(TO_CDADDR(StressLogChunkAddr + offsetof (StressLogChunk, next)), 
                &StressLogChunkAddr, sizeof (StressLogChunkAddr), 0);
            if (hr != S_OK)
            {
                return false;
            }
            if (StressLogChunkAddr == NULL)
            {
                return true;
            }            
        } while (StressLogChunkAddr != ChunkListHeadAddr);

        hr = memCallBack->ReadVirtual(TO_CDADDR(ThreadStressLogAddr + ThreadStressLog::OffsetOfNext ()), 
            &ThreadStressLogAddr, sizeof (ThreadStressLogAddr), 0);
        if (hr != S_OK)
        {
            return false;
        }        
    }

    return true;
}

bool StressLogMem::IsInStressLog (ULONG64 addr)
{
    MemRange * range = list;
    while (range)
    {
        if (range->InRange (addr))
            return true;
        range = range->next;
    }

    return false;
}

#endif // !FEATURE_PAL

unsigned int Output::g_bSuppressOutput = 0;
unsigned int Output::g_Indent = 0;
bool Output::g_bDbgOutput = false;
bool Output::g_bDMLExposed = false;
unsigned int Output::g_DMLEnable = 0;

template <class T, int count, int size> const int StaticData<T, count, size>::Count = count;
template <class T, int count, int size> const int StaticData<T, count, size>::Size  = size;

StaticData<char, 4, 1024> CachedString::cache;

CachedString::CachedString()
: mPtr(0), mRefCount(0), mIndex(~0), mSize(cache.Size)
{
    Create();
}

CachedString::CachedString(const CachedString &rhs)
: mPtr(0), mRefCount(0), mIndex(~0), mSize(cache.Size)
{
    Copy(rhs);
}

CachedString::~CachedString()
{
    Clear();
}

const CachedString &CachedString::operator=(const CachedString &rhs)
{
    Clear();
    Copy(rhs);
    return *this;
}

void CachedString::Copy(const CachedString &rhs)
{
    if (rhs.IsOOM())
    {
        SetOOM();
    }
    else
    {
        mPtr = rhs.mPtr;
        mIndex = rhs.mIndex;
        mSize = rhs.mSize;

        if (rhs.mRefCount)
        {
            mRefCount = rhs.mRefCount;
            (*mRefCount)++;
        }
        else
        {
            // We only create count the first time we copy it, so
            // we initialize it to 2.
            mRefCount = rhs.mRefCount = new unsigned int(2);
            if (!mRefCount)
                SetOOM();
        }
    }
}

void CachedString::Clear()
{
    if (!mRefCount || --*mRefCount == 0)
    {
        if (mIndex == -1)
        {
            if (mPtr)
                delete [] mPtr;
        }
        else if (mIndex >= 0 && mIndex < cache.Count)
        {
            cache.InUse[mIndex] = false;
        }

        if (mRefCount)
            delete mRefCount;
    }

    mPtr = 0;
    mIndex = ~0;
    mRefCount = 0;
    mSize = cache.Size;
}


void CachedString::Create()
{
    mIndex = -1;
    mRefCount = 0;

    // First try to find a string in the cache to use.
    for (int i = 0; i < cache.Count; ++i)
        if (!cache.InUse[i])
        {
            cache.InUse[i] = true;
            mPtr = cache.Data[i];
            mIndex = i;
            break;
        }

    // We did not find a string to use, so we'll create a new one.
    if (mIndex == -1)
    {
        mPtr = new char[cache.Size];
        if (!mPtr)
            SetOOM();
    }
}


void CachedString::SetOOM()
{
    Clear();
    mIndex = -2;
}

void CachedString::Allocate(int size)
{
    Clear();
    mPtr = new char[size];
    
    if (mPtr)
    {
        mSize = size;
        mIndex = -1;
    }
    else
    {
        SetOOM();
    }
}

size_t CountHexCharacters(CLRDATA_ADDRESS val)
{
    size_t ret = 0;

    while (val)
    {
        val >>= 4;
        ret++;
    }

    return ret;
}

void WhitespaceOut(int count)
{
    static const int FixedIndentWidth = 0x40;
    static const char FixedIndentString[FixedIndentWidth+1] =
        "                                                                ";

    if (count <= 0)
        return;

    int mod = count & 0x3F;
    count &= ~0x3F;

    if (mod > 0)
        g_ExtControl->Output(DEBUG_OUTPUT_NORMAL, "%.*s", mod, FixedIndentString);

    for ( ; count > 0; count -= FixedIndentWidth)
        g_ExtControl->Output(DEBUG_OUTPUT_NORMAL, FixedIndentString);
}

void DMLOut(PCSTR format, ...)
{
    if (Output::IsOutputSuppressed())
        return;

    va_list args;
    va_start(args, format);
    ExtOutIndent();

#ifndef FEATURE_PAL
    if (IsDMLEnabled() && !Output::IsDMLExposed())
    {
        g_ExtControl->ControlledOutputVaList(DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL, format, args);
    }
    else
#endif
    {
        g_ExtControl->OutputVaList(DEBUG_OUTPUT_NORMAL, format, args);
    }

    va_end(args);
}

void IfDMLOut(PCSTR format, ...)
{
#ifndef FEATURE_PAL
    if (Output::IsOutputSuppressed() || !IsDMLEnabled())
        return;

    va_list args;
    
    va_start(args, format);
    ExtOutIndent();
    g_ExtControl->ControlledOutputVaList(DEBUG_OUTCTL_AMBIENT_DML, DEBUG_OUTPUT_NORMAL, format, args);
    va_end(args);
#endif
}

void ExtOut(PCSTR Format, ...)
{
    if (Output::IsOutputSuppressed())
        return;

    va_list Args;
    
    va_start(Args, Format);
    ExtOutIndent();
    g_ExtControl->OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
    va_end(Args);
}

void ExtWarn(PCSTR Format, ...)
{
    if (Output::IsOutputSuppressed())
        return;

    va_list Args;
    
    va_start(Args, Format);
    g_ExtControl->OutputVaList(DEBUG_OUTPUT_WARNING, Format, Args);
    va_end(Args);
}

void ExtErr(PCSTR Format, ...)
{
    va_list Args;
    
    va_start(Args, Format);
    g_ExtControl->OutputVaList(DEBUG_OUTPUT_ERROR, Format, Args);
    va_end(Args);
}


void ExtDbgOut(PCSTR Format, ...)
{
#ifdef _DEBUG
    if (Output::g_bDbgOutput)
    {
        va_list Args;

        va_start(Args, Format);
        ExtOutIndent();
        g_ExtControl->OutputVaList(DEBUG_OUTPUT_NORMAL, Format, Args);
        va_end(Args);
    }
#endif
}

const char * const DMLFormats[] =
{
    NULL,                                           // DML_None (do not use)
    "<exec cmd=\"!DumpMT /d %s\">%s</exec>",        // DML_MethodTable
    "<exec cmd=\"!DumpMD /d %s\">%s</exec>",        // DML_MethodDesc
    "<exec cmd=\"!DumpClass /d %s\">%s</exec>",     // DML_EEClass
    "<exec cmd=\"!DumpModule /d %s\">%s</exec>",    // DML_Module
    "<exec cmd=\"!U /d %s\">%s</exec>",             // DML_IP
    "<exec cmd=\"!DumpObj /d %s\">%s</exec>",       // DML_Object
    "<exec cmd=\"!DumpDomain /d %s\">%s</exec>",    // DML_Domain
    "<exec cmd=\"!DumpAssembly /d %s\">%s</exec>",  // DML_Assembly
    "<exec cmd=\"~~[%s]s\">%s</exec>",              // DML_ThreadID
    "<exec cmd=\"!DumpVC /d %s %s\">%s</exec>",     // DML_ValueClass
    "<exec cmd=\"!DumpHeap /d -mt %s\">%s</exec>",  // DML_DumpHeapMT
    "<exec cmd=\"!ListNearObj /d %s\">%s</exec>",   // DML_ListNearObj
    "<exec cmd=\"!ThreadState %s\">%s</exec>",      // DML_ThreadState
    "<exec cmd=\"!PrintException /d %s\">%s</exec>",// DML_PrintException
    "<exec cmd=\"!DumpRCW /d %s\">%s</exec>",       // DML_RCWrapper
    "<exec cmd=\"!DumpCCW /d %s\">%s</exec>",       // DML_CCWrapper
    "<exec cmd=\"!ClrStack -i %S %d\">%S</exec>",   // DML_ManagedVar
};

void ConvertToLower(__out_ecount(len) char *buffer, size_t len)
{
    for (size_t i = 0; i < len && buffer[i]; ++i)
        buffer[i] = (char)tolower(buffer[i]);
}

/* Build a hex display of addr.
 */
int GetHex(CLRDATA_ADDRESS addr, __out_ecount(len) char *out, size_t len, bool fill)
{
    int count = sprintf_s(out, len, fill ? "%p" : "%x", (size_t)addr);
    
    ConvertToLower(out, len);
    
    return count;
}

CachedString Output::BuildHexValue(CLRDATA_ADDRESS addr, FormatType type, bool fill)
{
    CachedString ret;
    if (ret.IsOOM())
    {
        ReportOOM();
        return ret;
    }

    if (IsDMLEnabled())
    {
        char hex[POINTERSIZE_BYTES*2 + 1];
        GetHex(addr, hex, _countof(hex), fill);
        sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hex, hex);
    }
    else
    {
        GetHex(addr, ret, ret.GetStrLen(), fill);
    }

    return ret;
}

CachedString Output::BuildVCValue(CLRDATA_ADDRESS mt, CLRDATA_ADDRESS addr, FormatType type, bool fill)
{
    _ASSERTE(type == DML_ValueClass);
    CachedString ret;
    if (ret.IsOOM())
    {
        ReportOOM();
        return ret;
    }

    if (IsDMLEnabled())
    {
        char hexaddr[POINTERSIZE_BYTES*2 + 1];
        char hexmt[POINTERSIZE_BYTES*2 + 1];

        GetHex(addr, hexaddr, _countof(hexaddr), fill);
        GetHex(mt, hexmt, _countof(hexmt), fill);

        sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], hexmt, hexaddr, hexaddr);
    }
    else
    {
        GetHex(addr, ret, ret.GetStrLen(), fill);
    }

    return ret;
}

CachedString Output::BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, __in_z LPCWSTR simpleName, FormatType type)
{
    _ASSERTE(type == DML_ManagedVar);
    CachedString ret;
    if (ret.IsOOM())
    {
        ReportOOM();
        return ret;
    }

    // calculate the number of digits in frame (this assumes base-10 display of frames)
    int numFrameDigits = 0;
    if (frame > 0)
    {
        ULONG tempFrame = frame;
        while (tempFrame > 0)
        {
            ++numFrameDigits;
            tempFrame /= 10;
        }
    }
    else
    {
        numFrameDigits = 1;
    }
    
    size_t totalStringLength = strlen(DMLFormats[type]) + _wcslen(expansionName) + numFrameDigits + _wcslen(simpleName) + 1;
    if (totalStringLength > ret.GetStrLen())
    {
        ret.Allocate(static_cast<int>(totalStringLength));
        if (ret.IsOOM())
        {
            ReportOOM();
            return ret;
        }
    }
    
    if (IsDMLEnabled())
    {
        sprintf_s(ret, ret.GetStrLen(), DMLFormats[type], expansionName, frame, simpleName);
    }
    else
    {
        sprintf_s(ret, ret.GetStrLen(), "%S", simpleName);
    }

    return ret;
}

CachedString Output::BuildManagedVarValue(__in_z LPCWSTR expansionName, ULONG frame, int indexInArray, FormatType type)
{
    WCHAR indexString[24];
    swprintf_s(indexString, _countof(indexString), W("[%d]"), indexInArray);
    return BuildManagedVarValue(expansionName, frame, indexString, type);
}

EnableDMLHolder::EnableDMLHolder(BOOL enable)
    : mEnable(enable)
{
#ifndef FEATURE_PAL
    // If the user has not requested that we use DML, it's still possible that
    // they have instead specified ".prefer_dml 1".  If enable is false,
    // we will check here for .prefer_dml.  Since this class is only used once
    // per command issued to SOS, this should only check the setting once per
    // sos command issued.
    if (!mEnable && Output::g_DMLEnable <= 0)
    {
        ULONG opts;
        HRESULT hr = g_ExtControl->GetEngineOptions(&opts);
        mEnable = SUCCEEDED(hr) && (opts & DEBUG_ENGOPT_PREFER_DML) == DEBUG_ENGOPT_PREFER_DML;
    }

    if (mEnable)
    {
        Output::g_DMLEnable++;
    }
#endif // FEATURE_PAL
}

EnableDMLHolder::~EnableDMLHolder()
{
#ifndef FEATURE_PAL
    if (mEnable)
        Output::g_DMLEnable--;
#endif
}

bool IsDMLEnabled()
{
    return Output::g_DMLEnable > 0;
}

NoOutputHolder::NoOutputHolder(BOOL bSuppress)
    : mSuppress(bSuppress)
{
    if (mSuppress)
        Output::g_bSuppressOutput++;
}

NoOutputHolder::~NoOutputHolder()
{
    if (mSuppress)
        Output::g_bSuppressOutput--;
}

//
// Code to support mapping RVAs to managed code line numbers.
//

// 
// Retrieves the IXCLRDataMethodInstance* instance associated with the
// passed in native offset.
HRESULT
GetClrMethodInstance(
    ___in ULONG64 NativeOffset,
    ___out IXCLRDataMethodInstance** Method)
{
    HRESULT Status;
    CLRDATA_ENUM MethEnum;

    Status = g_clrData->StartEnumMethodInstancesByAddress(NativeOffset, NULL, &MethEnum);

    if (Status == S_OK)
    {
        Status = g_clrData->EnumMethodInstanceByAddress(&MethEnum, Method);
        g_clrData->EndEnumMethodInstancesByAddress(MethEnum);
    }

    // Any alternate success is a true failure here.
    return (Status == S_OK || FAILED(Status)) ? Status : E_NOINTERFACE;
}

// 
// Enumerates over the IL address map associated with the passed in 
// managed method, and returns the highest non-epilog offset.
HRESULT
GetLastMethodIlOffset(
    ___in IXCLRDataMethodInstance* Method, 
    ___out PULONG32 MethodOffs)
{
    HRESULT Status;
    CLRDATA_IL_ADDRESS_MAP MapLocal[16];
    CLRDATA_IL_ADDRESS_MAP* Map = MapLocal;
    ULONG32 MapCount = _countof(MapLocal);
    ULONG32 MapNeeded;
    ULONG32 HighestOffset;

    for (;;)
    {
        if ((Status = Method->GetILAddressMap(MapCount, &MapNeeded, Map)) != S_OK)
        {
            return Status;
        }

        if (MapNeeded <= MapCount)
        {
            break;
        }

        // Need more map entries.
        if (Map != MapLocal)
        {
            // Already went around and the answer changed,
            // which should not be possible.
            delete[] Map;
            return E_UNEXPECTED;
        }

        Map = new CLRDATA_IL_ADDRESS_MAP[MapNeeded];
        if (!Map)
        {
            return E_OUTOFMEMORY;
        }

        MapCount = MapNeeded;
    }

    HighestOffset = 0;
    for (size_t i = 0; i < MapNeeded; i++)
    {
        if (Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_NO_MAPPING &&
            Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_PROLOG &&
            Map[i].ilOffset != (ULONG32)CLRDATA_IL_OFFSET_EPILOG &&
            Map[i].ilOffset > HighestOffset)
        {
            HighestOffset = Map[i].ilOffset;
        }
    }

    if (Map != MapLocal)
    {
        delete[] Map;
    }

    *MethodOffs = HighestOffset;
    return S_OK;
}

// 
// Convert a native offset (possibly already associated with a managed
// method identified by the passed in IXCLRDataMethodInstance) to a
// triplet (ImageInfo, MethodToken, MethodOffset) that can be used to 
// represent an "IL offset".
HRESULT
ConvertNativeToIlOffset(
    ___in ULONG64 native,
    ___out IXCLRDataModule** ppModule,
    ___out mdMethodDef* methodToken,
    ___out PULONG32 methodOffs)
{
    ToRelease<IXCLRDataMethodInstance> pMethodInst(NULL);
    HRESULT Status;

    if ((Status = GetClrMethodInstance(native, &pMethodInst)) != S_OK)
    {
        return Status;
    }

    if ((Status = pMethodInst->GetILOffsetsByAddress(native, 1, NULL, methodOffs)) != S_OK)
    {
        *methodOffs = 0;
    }
    else
    {
        switch((LONG)*methodOffs)
        {
        case CLRDATA_IL_OFFSET_NO_MAPPING:
            return E_NOINTERFACE;
            
        case CLRDATA_IL_OFFSET_PROLOG:
            // Treat all of the prologue as part of
            // the first source line.
            *methodOffs = 0;
            break;
            
        case CLRDATA_IL_OFFSET_EPILOG:
            // Back up until we find the last real
            // IL offset.
            if ((Status = GetLastMethodIlOffset(pMethodInst, methodOffs)) != S_OK)
            {
                return Status;
            }
            break;
        }
    }

    return pMethodInst->GetTokenAndScope(methodToken, ppModule);
}

// Based on a native offset, passed in the first argument this function
// identifies the corresponding source file name and line number.
HRESULT
GetLineByOffset(
    ___in ULONG64 offset,
    ___out ULONG *pLinenum,
    __out_ecount(cchFileName) WCHAR* pwszFileName,
    ___in ULONG cchFileName)
{
    HRESULT Status = S_OK;
    ULONG32 methodToken;
    ULONG32 methodOffs;

    // Find the image, method token and IL offset that correspond to "offset"
    ToRelease<IXCLRDataModule> pModule(NULL);
    IfFailRet(ConvertNativeToIlOffset(offset, &pModule, &methodToken, &methodOffs));

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

    SymbolReader symbolReader;
    IfFailRet(symbolReader.LoadSymbols(pMDImport, pModule));

    return symbolReader.GetLineByILOffset(methodToken, methodOffs, pLinenum, pwszFileName, cchFileName);
}

void TableOutput::ReInit(int numColumns, int defaultColumnWidth, Alignment alignmentDefault, int indent, int padding)
{
    Clear();

    mColumns = numColumns;
    mDefaultWidth = defaultColumnWidth;
    mIndent = indent;
    mPadding = padding;
    mCurrCol = 0;
    mDefaultAlign = alignmentDefault;
}

void TableOutput::SetWidths(int columns, ...)
{
    SOS_Assert(columns > 0);
    SOS_Assert(columns <= mColumns);

    AllocWidths();

    va_list list;
    va_start(list, columns);

    for (int i = 0; i < columns; ++i)
        mWidths[i] = va_arg(list, int);

    va_end(list);
}

void TableOutput::SetColWidth(int col, int width)
{
    SOS_Assert(col >= 0 && col < mColumns);
    SOS_Assert(width >= 0);

    AllocWidths();

    mWidths[col] = width;
}

void TableOutput::SetColAlignment(int col, Alignment align)
{
    SOS_Assert(col >= 0 && col < mColumns);

    if (!mAlignments)
    {
        mAlignments = new Alignment[mColumns];
        for (int i = 0; i < mColumns; ++i)
            mAlignments[i] = mDefaultAlign;
    }

    mAlignments[col] = align;
}



void TableOutput::Clear()
{
    if (mAlignments)
    {
        delete [] mAlignments;
        mAlignments = 0;
    }

    if (mWidths)
    {
        delete [] mWidths;
        mWidths = 0;
    }
}

void TableOutput::AllocWidths()
{
    if (!mWidths)
    {
        mWidths = new int[mColumns];
        for (int i = 0; i < mColumns; ++i)
            mWidths[i] = mDefaultWidth;
    }
}

int TableOutput::GetColumnWidth(int col)
{
    SOS_Assert(col < mColumns);

    if (mWidths)
        return mWidths[col];

    return mDefaultWidth;
}

Alignment TableOutput::GetColAlign(int col)
{
    SOS_Assert(col < mColumns);
    if (mAlignments)
        return mAlignments[col];

    return mDefaultAlign;
}

const char *TableOutput::GetWhitespace(int amount)
{
    static char WhiteSpace[256] = "";
    static int count = 0;

    if (count == 0)
    {
        count = _countof(WhiteSpace);
        for (int i = 0; i < count-1; ++i)
            WhiteSpace[i] = ' ';
        WhiteSpace[count-1] = 0;
    }

    SOS_Assert(amount < count);
    return &WhiteSpace[count-amount-1];
}

void TableOutput::OutputBlankColumns(int col)
{
    if (col < mCurrCol)
    {
        ExtOut("\n");
        mCurrCol = 0;
    }

    int whitespace = 0;
    for (int i = mCurrCol; i < col; ++i)
        whitespace += GetColumnWidth(i) + mPadding;

    ExtOut(GetWhitespace(whitespace));
}

void TableOutput::OutputIndent()
{
    if (mIndent)
        ExtOut(GetWhitespace(mIndent));
}

#ifndef FEATURE_PAL

PEOffsetMemoryReader::PEOffsetMemoryReader(TADDR moduleBaseAddress) :
    m_moduleBaseAddress(moduleBaseAddress),
    m_refCount(1)
    {}

HRESULT __stdcall PEOffsetMemoryReader::QueryInterface(REFIID riid, VOID** ppInterface)
{
    if(riid == __uuidof(IDiaReadExeAtOffsetCallback))
    {
        *ppInterface = static_cast<IDiaReadExeAtOffsetCallback*>(this);
        AddRef();
        return S_OK;
    }
    else if(riid == __uuidof(IUnknown))
    {
        *ppInterface = static_cast<IUnknown*>(this);
        AddRef();
        return S_OK;
    }
    else
    {
        return E_NOINTERFACE;
    }
}

ULONG __stdcall PEOffsetMemoryReader::AddRef()
{
    return InterlockedIncrement((volatile LONG *) &m_refCount);
}

ULONG __stdcall PEOffsetMemoryReader::Release()
{
    ULONG count = InterlockedDecrement((volatile LONG *) &m_refCount);
    if(count == 0)
    {
        delete this;
    }
    return count;
}
    
// IDiaReadExeAtOffsetCallback implementation
HRESULT __stdcall PEOffsetMemoryReader::ReadExecutableAt(DWORDLONG fileOffset, DWORD cbData, DWORD* pcbData, BYTE data[])
{
    return SafeReadMemory(m_moduleBaseAddress + fileOffset, data, cbData, pcbData) ? S_OK : E_FAIL;
}

PERvaMemoryReader::PERvaMemoryReader(TADDR moduleBaseAddress) :
    m_moduleBaseAddress(moduleBaseAddress),
    m_refCount(1)
    {}

HRESULT __stdcall PERvaMemoryReader::QueryInterface(REFIID riid, VOID** ppInterface)
{
    if(riid == __uuidof(IDiaReadExeAtRVACallback))
    {
        *ppInterface = static_cast<IDiaReadExeAtRVACallback*>(this);
        AddRef();
        return S_OK;
    }
    else if(riid == __uuidof(IUnknown))
    {
        *ppInterface = static_cast<IUnknown*>(this);
        AddRef();
        return S_OK;
    }
    else
    {
        return E_NOINTERFACE;
    }
}

ULONG __stdcall PERvaMemoryReader::AddRef()
{
    return InterlockedIncrement((volatile LONG *) &m_refCount);
}

ULONG __stdcall PERvaMemoryReader::Release()
{
    ULONG count = InterlockedDecrement((volatile LONG *) &m_refCount);
    if(count == 0)
    {
        delete this;
    }
    return count;
}
    
// IDiaReadExeAtOffsetCallback implementation
HRESULT __stdcall PERvaMemoryReader::ReadExecutableAtRVA(DWORD relativeVirtualAddress, DWORD cbData, DWORD* pcbData, BYTE data[])
{
    return SafeReadMemory(m_moduleBaseAddress + relativeVirtualAddress, data, cbData, pcbData) ? S_OK : E_FAIL;
}

#endif // FEATURE_PAL

HRESULT SymbolReader::LoadSymbols(___in IMetaDataImport* pMD, ___in ICorDebugModule* pModule)
{
    HRESULT Status = S_OK;
    BOOL isDynamic = FALSE;
    BOOL isInMemory = FALSE;
    IfFailRet(pModule->IsDynamic(&isDynamic));
    IfFailRet(pModule->IsInMemory(&isInMemory));

    if (isDynamic)
    {
        // Dynamic and in memory assemblies are a special case which we will ignore for now
        ExtWarn("SOS Warning: Loading symbols for dynamic assemblies is not yet supported\n");
        return E_FAIL;
    }

    ULONG64 peAddress = 0;
    ULONG32 peSize = 0;
    IfFailRet(pModule->GetBaseAddress(&peAddress));
    IfFailRet(pModule->GetSize(&peSize));

    ULONG32 len = 0; 
    WCHAR moduleName[MAX_LONGPATH];
    IfFailRet(pModule->GetName(_countof(moduleName), &len, moduleName));

#ifndef FEATURE_PAL
    if (SUCCEEDED(LoadSymbolsForWindowsPDB(pMD, peAddress, moduleName, isInMemory)))
    {
        return S_OK;
    }
#endif // FEATURE_PAL
    return LoadSymbolsForPortablePDB(moduleName, isInMemory, isInMemory, peAddress, peSize, 0, 0);
}

HRESULT SymbolReader::LoadSymbols(___in IMetaDataImport* pMD, ___in IXCLRDataModule* pModule)
{
    DacpGetModuleData moduleData;
    HRESULT hr = moduleData.Request(pModule);
    if (FAILED(hr))
    {
        ExtOut("LoadSymbols moduleData.Request FAILED 0x%08x\n", hr);
        return hr;
    }

    if (moduleData.IsDynamic)
    {
        ExtWarn("SOS Warning: Loading symbols for dynamic assemblies is not yet supported\n");
        return E_FAIL;
    }

    ArrayHolder<WCHAR> pModuleName = new WCHAR[MAX_LONGPATH + 1];
    ULONG32 nameLen = 0;
    hr = pModule->GetFileName(MAX_LONGPATH, &nameLen, pModuleName);
    if (FAILED(hr))
    {
        ExtOut("LoadSymbols: IXCLRDataModule->GetFileName FAILED 0x%08x\n", hr);
        return hr;
    }

#ifndef FEATURE_PAL
    // TODO: in-memory windows PDB not supported
    hr = LoadSymbolsForWindowsPDB(pMD, moduleData.LoadedPEAddress, pModuleName, moduleData.IsFileLayout);
    if (SUCCEEDED(hr))
    {
        return hr;
    }
#endif // FEATURE_PAL

    return LoadSymbolsForPortablePDB(
        pModuleName, 
        moduleData.IsInMemory,
        moduleData.IsFileLayout,
        moduleData.LoadedPEAddress,
        moduleData.LoadedPESize, 
        moduleData.InMemoryPdbAddress,
        moduleData.InMemoryPdbSize);
}

#ifndef FEATURE_PAL

HRESULT SymbolReader::LoadSymbolsForWindowsPDB(___in IMetaDataImport* pMD, ___in ULONG64 peAddress, __in_z WCHAR* pModuleName, ___in BOOL isFileLayout)
{
    HRESULT Status = S_OK;

    if (m_pSymReader != NULL) 
        return S_OK;

    IfFailRet(CoInitialize(NULL));

    // We now need a binder object that will take the module and return a 
    // reader object
    ToRelease<ISymUnmanagedBinder3> pSymBinder;
    if (FAILED(Status = CreateInstanceCustom(CLSID_CorSymBinder_SxS, 
                        IID_ISymUnmanagedBinder3, 
                        W("diasymreader.dll"),
                        cciLatestFx|cciDacColocated|cciDbgPath, 
                        (void**)&pSymBinder)))
    {
        ExtOut("SOS Error: Unable to CoCreateInstance class=CLSID_CorSymBinder_SxS, interface=IID_ISymUnmanagedBinder3, hr=0x%x\n", Status);
        ExtOut("This usually means the installation of .Net Framework on your machine is missing or needs repair\n");
        return Status;
    }

    ToRelease<IDebugSymbols3> spSym3(NULL);
    Status = g_ExtSymbols->QueryInterface(__uuidof(IDebugSymbols3), (void**)&spSym3);
    if (FAILED(Status))
    {
        ExtOut("SOS Error: Unable to query IDebugSymbols3 HRESULT=0x%x.\n", Status);
        return Status;
    }

    ULONG pathSize = 0;
    Status = spSym3->GetSymbolPathWide(NULL, 0, &pathSize);
    if (FAILED(Status)) //S_FALSE if the path doesn't fit, but if the path was size 0 perhaps we would get S_OK?
    {
        ExtOut("SOS Error: Unable to get symbol path length. IDebugSymbols3::GetSymbolPathWide HRESULT=0x%x.\n", Status);
        return Status;
    }

    ArrayHolder<WCHAR> symbolPath = new WCHAR[pathSize];
    Status = spSym3->GetSymbolPathWide(symbolPath, pathSize, NULL);
    if (S_OK != Status)
    {
        ExtOut("SOS Error: Unable to get symbol path. IDebugSymbols3::GetSymbolPathWide HRESULT=0x%x.\n", Status);
        return Status;
    }

    ToRelease<IUnknown> pCallback = NULL;
    if (isFileLayout)
    {
        pCallback = (IUnknown*) new PEOffsetMemoryReader(TO_TADDR(peAddress));
    }
    else
    {
        pCallback = (IUnknown*) new PERvaMemoryReader(TO_TADDR(peAddress));
    }

    // TODO: this should be better integrated with windbg's symbol lookup
    Status = pSymBinder->GetReaderFromCallback(pMD, pModuleName, symbolPath, 
        AllowRegistryAccess | AllowSymbolServerAccess | AllowOriginalPathAccess | AllowReferencePathAccess, pCallback, &m_pSymReader);

    if (FAILED(Status) && m_pSymReader != NULL)
    {
        m_pSymReader->Release();
        m_pSymReader = NULL;
    }
    return Status;
}

#endif // FEATURE_PAL

//
// Pass to managed helper code to read in-memory PEs/PDBs
// Returns the number of bytes read.
//
int ReadMemoryForSymbols(ULONG64 address, char *buffer, int cb)
{
    ULONG read;
    if (SafeReadMemory(address, (PVOID)buffer, cb, &read))
    {
        return read;
    }
    return 0;
}

HRESULT SymbolReader::LoadSymbolsForPortablePDB(__in_z WCHAR* pModuleName, ___in BOOL isInMemory, ___in BOOL isFileLayout,
    ___in ULONG64 peAddress, ___in ULONG64 peSize, ___in ULONG64 inMemoryPdbAddress, ___in ULONG64 inMemoryPdbSize)
{
    HRESULT Status = S_OK;

    if (loadSymbolsForModuleDelegate == nullptr)
    {
        IfFailRet(PrepareSymbolReader());
    }

    // The module name needs to be null for in-memory PE's.
    ArrayHolder<char> szModuleName = nullptr;
    if (!isInMemory && pModuleName != nullptr)
    {
        szModuleName = new char[MAX_LONGPATH];
        if (WideCharToMultiByte(CP_ACP, 0, pModuleName, (int)(_wcslen(pModuleName) + 1), szModuleName, MAX_LONGPATH, NULL, NULL) == 0)
        {
            return E_FAIL;
        }
    }

    m_symbolReaderHandle = loadSymbolsForModuleDelegate(szModuleName, isFileLayout, peAddress, 
        (int)peSize, inMemoryPdbAddress, (int)inMemoryPdbSize, ReadMemoryForSymbols);

    if (m_symbolReaderHandle == 0)
    {
        return E_FAIL;
    }

    return Status;
}

#ifndef FEATURE_PAL

void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList)
{
    const char * const tpaExtensions[] = {
        "*.ni.dll",      // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir
        "*.dll",
        "*.ni.exe",
        "*.exe",
    };

    std::set<std::string> addedAssemblies;

    // Walk the directory for each extension separately so that we first get files with .ni.dll extension,
    // then files with .dll extension, etc.
    for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++)
    {
        const char* ext = tpaExtensions[extIndex];
        size_t extLength = strlen(ext);

        std::string assemblyPath(directory);
        assemblyPath.append(DIRECTORY_SEPARATOR_STR_A);
        assemblyPath.append(tpaExtensions[extIndex]);

        WIN32_FIND_DATAA data;
        HANDLE findHandle = FindFirstFileA(assemblyPath.c_str(), &data);

        if (findHandle != INVALID_HANDLE_VALUE) 
        {
            do
            {
                if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
                {

                    std::string filename(data.cFileName);
                    size_t extPos = filename.length() - extLength;
                    std::string filenameWithoutExt(filename.substr(0, extPos));

                    // Make sure if we have an assembly with multiple extensions present,
                    // we insert only one version of it.
                    if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end())
                    {
                        addedAssemblies.insert(filenameWithoutExt);

                        tpaList.append(directory);
                        tpaList.append(DIRECTORY_SEPARATOR_STR_A);
                        tpaList.append(filename);
                        tpaList.append(";");
                    }
                }
            } 
            while (0 != FindNextFileA(findHandle, &data));

            FindClose(findHandle);
        }
    }
}

bool GetEntrypointExecutableAbsolutePath(std::string& entrypointExecutable)
{
    ArrayHolder<char> hostPath = new char[MAX_LONGPATH+1];
    if (::GetModuleFileName(NULL, hostPath, MAX_LONGPATH) == 0)
    {
        return false;
    }

    entrypointExecutable.clear();
    entrypointExecutable.append(hostPath);

    return true;
}

#endif // FEATURE_PAL

HRESULT SymbolReader::PrepareSymbolReader()
{
    static bool attemptedSymbolReaderPreparation = false;
    if (attemptedSymbolReaderPreparation)
    {
        // If we already tried to set up the symbol reader, we won't try again.
        return E_FAIL;
    }

    attemptedSymbolReaderPreparation = true;

    std::string absolutePath;
    std::string coreClrPath;
    HRESULT Status;

#ifdef FEATURE_PAL
    coreClrPath = g_ExtServices->GetCoreClrDirectory();
    if (!GetAbsolutePath(coreClrPath.c_str(), absolutePath))
    {
        ExtErr("Error: Failed to get coreclr absolute path\n");
        return E_FAIL;
    }
    coreClrPath.append(DIRECTORY_SEPARATOR_STR_A);
    coreClrPath.append(MAIN_CLR_DLL_NAME_A);
#else
    ULONG index;
    Status = g_ExtSymbols->GetModuleByModuleName(MAIN_CLR_MODULE_NAME_A, 0, &index, NULL);
    if (FAILED(Status))
    {
        ExtErr("Error: Can't find coreclr module\n");
        return Status;
    }
    ArrayHolder<char> szModuleName = new char[MAX_LONGPATH + 1];
    Status = g_ExtSymbols->GetModuleNames(index, 0, szModuleName, MAX_LONGPATH, NULL, NULL, 0, NULL, NULL, 0, NULL);
    if (FAILED(Status))
    {
        ExtErr("Error: Failed to get coreclr module name\n");
        return Status;
    }
    coreClrPath = szModuleName;

    // Parse off the module name to get just the path
    size_t pos = coreClrPath.rfind(DIRECTORY_SEPARATOR_CHAR_A);
    if (pos == std::string::npos)
    {
        ExtErr("Error: Failed to parse coreclr module name\n");
        return E_FAIL;
    }
    absolutePath.assign(coreClrPath, 0, pos);
#endif // FEATURE_PAL

    HMODULE coreclrLib = LoadLibraryA(coreClrPath.c_str());
    if (coreclrLib == nullptr)
    {
        ExtErr("Error: Failed to load %s\n", coreClrPath.c_str());
        return E_FAIL;
    }

    void *hostHandle;
    unsigned int domainId;
    coreclr_initialize_ptr initializeCoreCLR = (coreclr_initialize_ptr)GetProcAddress(coreclrLib, "coreclr_initialize");
    if (initializeCoreCLR == nullptr)
    {
        ExtErr("Error: coreclr_initialize not found\n");
        return E_FAIL;
    }

    std::string tpaList;
    AddFilesFromDirectoryToTpaList(absolutePath.c_str(), tpaList);

    const char *propertyKeys[] = {
        "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS",
        "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch"};

    const char *propertyValues[] = {// TRUSTED_PLATFORM_ASSEMBLIES
                                    tpaList.c_str(),
                                    // APP_PATHS
                                    absolutePath.c_str(),
                                    // APP_NI_PATHS
                                    absolutePath.c_str(),
                                    // NATIVE_DLL_SEARCH_DIRECTORIES
                                    absolutePath.c_str(),
                                    // AppDomainCompatSwitch
                                    "UseLatestBehaviorWhenTFMNotSpecified"};

    std::string entryPointExecutablePath;
    if (!GetEntrypointExecutableAbsolutePath(entryPointExecutablePath))
    {
        ExtErr("Could not get full path to current executable");
        return E_FAIL;
    }

    Status = initializeCoreCLR(entryPointExecutablePath.c_str(), "sos", 
        sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, &hostHandle, &domainId);

    if (FAILED(Status))
    {
        ExtErr("Error: Fail to initialize CoreCLR %08x\n", Status);
        return Status;
    }

    coreclr_create_delegate_ptr createDelegate = (coreclr_create_delegate_ptr)GetProcAddress(coreclrLib, "coreclr_create_delegate");
    if (createDelegate == nullptr)
    {
        ExtErr("Error: coreclr_create_delegate not found\n");
        return E_FAIL;
    }

    IfFailRet(createDelegate(hostHandle, domainId, SymbolReaderDllName, SymbolReaderClassName, "LoadSymbolsForModule", (void **)&loadSymbolsForModuleDelegate));
    IfFailRet(createDelegate(hostHandle, domainId, SymbolReaderDllName, SymbolReaderClassName, "Dispose", (void **)&disposeDelegate));
    IfFailRet(createDelegate(hostHandle, domainId, SymbolReaderDllName, SymbolReaderClassName, "ResolveSequencePoint", (void **)&resolveSequencePointDelegate));
    IfFailRet(createDelegate(hostHandle, domainId, SymbolReaderDllName, SymbolReaderClassName, "GetLocalVariableName", (void **)&getLocalVariableNameDelegate));
    IfFailRet(createDelegate(hostHandle, domainId, SymbolReaderDllName, SymbolReaderClassName, "GetLineByILOffset", (void **)&getLineByILOffsetDelegate));

    return Status;
}

HRESULT SymbolReader::GetLineByILOffset(___in mdMethodDef methodToken, ___in ULONG64 ilOffset,
    ___out ULONG *pLinenum, __out_ecount(cchFileName) WCHAR* pwszFileName, ___in ULONG cchFileName)
{
    HRESULT Status = S_OK;

    if (m_symbolReaderHandle != 0)
    {
        _ASSERTE(getLineByILOffsetDelegate != nullptr);

        BSTR bstrFileName = SysAllocStringLen(0, MAX_LONGPATH);
        if (bstrFileName == nullptr)
        {
            return E_OUTOFMEMORY;
        }
        // Source lines with 0xFEEFEE markers are filtered out on the managed side.
        if ((getLineByILOffsetDelegate(m_symbolReaderHandle, methodToken, ilOffset, pLinenum, &bstrFileName) == FALSE) || (*pLinenum == 0))
        {
            SysFreeString(bstrFileName);
            return E_FAIL;
        }
        wcscpy_s(pwszFileName, cchFileName, bstrFileName);
        SysFreeString(bstrFileName);
        return S_OK;
    }

#ifndef FEATURE_PAL
    if (m_pSymReader == NULL)
        return E_FAIL;

    ToRelease<ISymUnmanagedMethod> pSymMethod(NULL);
    IfFailRet(m_pSymReader->GetMethod(methodToken, &pSymMethod));

    ULONG32 seqPointCount = 0;
    IfFailRet(pSymMethod->GetSequencePointCount(&seqPointCount));

    if (seqPointCount == 0)
        return E_FAIL;

    // allocate memory for the objects to be fetched
    ArrayHolder<ULONG32> offsets(new ULONG32[seqPointCount]);
    ArrayHolder<ULONG32> lines(new ULONG32[seqPointCount]);
    ArrayHolder<ULONG32> columns(new ULONG32[seqPointCount]);
    ArrayHolder<ULONG32> endlines(new ULONG32[seqPointCount]);
    ArrayHolder<ULONG32> endcolumns(new ULONG32[seqPointCount]);
    ArrayHolder<ToRelease<ISymUnmanagedDocument>> documents(new ToRelease<ISymUnmanagedDocument>[seqPointCount]);

    ULONG32 realSeqPointCount = 0;
    IfFailRet(pSymMethod->GetSequencePoints(seqPointCount, &realSeqPointCount, offsets, &(documents[0]), lines, columns, endlines, endcolumns));

    const ULONG32 HiddenLine = 0x00feefee;
    int bestSoFar = -1;

    for (int i = 0; i < (int)realSeqPointCount; i++)
    {
        if (offsets[i] > ilOffset)
            break;

        if (lines[i] != HiddenLine)
            bestSoFar = i;
    }

    if (bestSoFar != -1)
    {
        ULONG32 cchNeeded = 0;
        IfFailRet(documents[bestSoFar]->GetURL(cchFileName, &cchNeeded, pwszFileName));

        *pLinenum = lines[bestSoFar];
        return S_OK;
    }
#endif // FEATURE_PAL

    return E_FAIL;
}

HRESULT SymbolReader::GetNamedLocalVariable(___in ISymUnmanagedScope * pScope, ___in ICorDebugILFrame * pILFrame, ___in mdMethodDef methodToken, 
    ___in ULONG localIndex, __out_ecount(paramNameLen) WCHAR* paramName, ___in ULONG paramNameLen, ICorDebugValue** ppValue)
{
    HRESULT Status = S_OK;

    if (m_symbolReaderHandle != 0)
    {
        _ASSERTE(getLocalVariableNameDelegate != nullptr);

        BSTR wszParamName = SysAllocStringLen(0, mdNameLen);
        if (wszParamName == NULL)
        {
            return E_OUTOFMEMORY;
        }

        if (getLocalVariableNameDelegate(m_symbolReaderHandle, methodToken, localIndex, &wszParamName) == FALSE)
        {
            SysFreeString(wszParamName);
            return E_FAIL;
        }

        wcscpy_s(paramName, paramNameLen, wszParamName);
        SysFreeString(wszParamName);

        if (FAILED(pILFrame->GetLocalVariable(localIndex, ppValue)) || (*ppValue == NULL))
        {
            *ppValue = NULL;
            return E_FAIL;
        }
        return S_OK;
    }

#ifndef FEATURE_PAL
    if (m_pSymReader == NULL)
        return E_FAIL;

    if (pScope == NULL)
    {
        ToRelease<ISymUnmanagedMethod> pSymMethod;
        IfFailRet(m_pSymReader->GetMethod(methodToken, &pSymMethod));

        ToRelease<ISymUnmanagedScope> pScope;
        IfFailRet(pSymMethod->GetRootScope(&pScope));

        return GetNamedLocalVariable(pScope, pILFrame, methodToken, localIndex, paramName, paramNameLen, ppValue);
    }
    else
    {
        ULONG32 numVars = 0;
        IfFailRet(pScope->GetLocals(0, &numVars, NULL));

        ArrayHolder<ISymUnmanagedVariable*> pLocals = new ISymUnmanagedVariable*[numVars];
        IfFailRet(pScope->GetLocals(numVars, &numVars, pLocals));

        for (ULONG i = 0; i < numVars; i++)
        {
            ULONG32 varIndexInMethod = 0;
            if (SUCCEEDED(pLocals[i]->GetAddressField1(&varIndexInMethod)))
            {
                if (varIndexInMethod != localIndex)
                    continue;

                ULONG32 nameLen = 0;
                if (FAILED(pLocals[i]->GetName(paramNameLen, &nameLen, paramName)))
                        swprintf_s(paramName, paramNameLen, W("local_%d\0"), localIndex);

                if (SUCCEEDED(pILFrame->GetLocalVariable(varIndexInMethod, ppValue)) && (*ppValue != NULL))
                {
                    for(ULONG j = 0; j < numVars; j++) pLocals[j]->Release();
                    return S_OK;
                }
                else
                {
                    *ppValue = NULL;
                    for(ULONG j = 0; j < numVars; j++) pLocals[j]->Release();
                    return E_FAIL;
                }
            }
        }

        ULONG32 numChildren = 0;
        IfFailRet(pScope->GetChildren(0, &numChildren, NULL));

        ArrayHolder<ISymUnmanagedScope*> pChildren = new ISymUnmanagedScope*[numChildren];
        IfFailRet(pScope->GetChildren(numChildren, &numChildren, pChildren));

        for (ULONG i = 0; i < numChildren; i++)
        {
            if (SUCCEEDED(GetNamedLocalVariable(pChildren[i], pILFrame, methodToken, localIndex, paramName, paramNameLen, ppValue)))
            {
                for (ULONG j = 0; j < numChildren; j++) pChildren[j]->Release();
                return S_OK;
            }
        }

        for (ULONG j = 0; j < numChildren; j++) pChildren[j]->Release();
    }
#endif // FEATURE_PAL

    return E_FAIL;
}

HRESULT SymbolReader::GetNamedLocalVariable(___in ICorDebugFrame * pFrame, ___in ULONG localIndex, __out_ecount(paramNameLen) WCHAR* paramName, 
    ___in ULONG paramNameLen, ___out ICorDebugValue** ppValue)
{
    HRESULT Status = S_OK;

    *ppValue = NULL;
    paramName[0] = L'\0';

    ToRelease<ICorDebugILFrame> pILFrame;
    IfFailRet(pFrame->QueryInterface(IID_ICorDebugILFrame, (LPVOID*) &pILFrame));

    ToRelease<ICorDebugFunction> pFunction;
    IfFailRet(pFrame->GetFunction(&pFunction));

    mdMethodDef methodDef;
    ToRelease<ICorDebugClass> pClass;
    ToRelease<ICorDebugModule> pModule;
    IfFailRet(pFunction->GetClass(&pClass));
    IfFailRet(pFunction->GetModule(&pModule));
    IfFailRet(pFunction->GetToken(&methodDef));

    return GetNamedLocalVariable(NULL, pILFrame, methodDef, localIndex, paramName, paramNameLen, ppValue);
}

HRESULT SymbolReader::ResolveSequencePoint(__in_z WCHAR* pFilename, ___in ULONG32 lineNumber, ___in TADDR mod, ___out mdMethodDef* pToken, ___out ULONG32* pIlOffset)
{
    HRESULT Status = S_OK;

    if (m_symbolReaderHandle != 0)
    {
        _ASSERTE(resolveSequencePointDelegate != nullptr);

        char szName[mdNameLen];
        if (WideCharToMultiByte(CP_ACP, 0, pFilename, (int)(_wcslen(pFilename) + 1), szName, mdNameLen, NULL, NULL) == 0)
        { 
            return E_FAIL;
        }
        if (resolveSequencePointDelegate(m_symbolReaderHandle, szName, lineNumber, pToken, pIlOffset) == FALSE)
        {
            return E_FAIL;
        }
        return S_OK;
    }

#ifndef FEATURE_PAL
    if (m_pSymReader == NULL)
        return E_FAIL;

    ULONG32 cDocs = 0;
    ULONG32 cDocsNeeded = 0;
    ArrayHolder<ToRelease<ISymUnmanagedDocument>> pDocs = NULL;

    IfFailRet(m_pSymReader->GetDocuments(cDocs, &cDocsNeeded, NULL));
    pDocs = new ToRelease<ISymUnmanagedDocument>[cDocsNeeded];
    cDocs = cDocsNeeded;
    IfFailRet(m_pSymReader->GetDocuments(cDocs, &cDocsNeeded, &(pDocs[0])));

    ULONG32 filenameLen = (ULONG32) _wcslen(pFilename);

    for (ULONG32 i = 0; i < cDocs; i++)
    {
        ULONG32 cchUrl = 0;
        ULONG32 cchUrlNeeded = 0;
        ArrayHolder<WCHAR> pUrl = NULL;
        IfFailRet(pDocs[i]->GetURL(cchUrl, &cchUrlNeeded, pUrl));
        pUrl = new WCHAR[cchUrlNeeded];
        cchUrl = cchUrlNeeded;
        IfFailRet(pDocs[i]->GetURL(cchUrl, &cchUrlNeeded, pUrl));

        // If the URL is exactly as long as the filename then compare the two names directly
        if (cchUrl-1 == filenameLen)
        {
            if (0!=_wcsicmp(pUrl, pFilename))
                continue;
        }
        // does the URL suffix match [back]slash + filename?
        else if (cchUrl-1 > filenameLen)
        {
            WCHAR* slashLocation = pUrl + (cchUrl - filenameLen - 2);
            if (*slashLocation != L'\\' && *slashLocation != L'/')
                continue;
            if (0 != _wcsicmp(slashLocation+1, pFilename))
                continue;
        }
        // URL is too short to match
        else
            continue;

        ULONG32 closestLine = 0;
        if (FAILED(pDocs[i]->FindClosestLine(lineNumber, &closestLine)))
            continue;

        ToRelease<ISymUnmanagedMethod> pSymUnmanagedMethod;
        IfFailRet(m_pSymReader->GetMethodFromDocumentPosition(pDocs[i], closestLine, 0, &pSymUnmanagedMethod));
        IfFailRet(pSymUnmanagedMethod->GetToken(pToken));
        IfFailRet(pSymUnmanagedMethod->GetOffset(pDocs[i], closestLine, 0, pIlOffset));

        // If this IL 
        if (*pIlOffset == -1)
        {
            return E_FAIL;
        }
        return S_OK;
    }
#endif // FEATURE_PAL

    return E_FAIL;
}

static void AddAssemblyName(WString& methodOutput, CLRDATA_ADDRESS mdesc)
{
    DacpMethodDescData mdescData;
    if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
    {
        DacpModuleData dmd;
        if (SUCCEEDED(dmd.Request(g_sos, mdescData.ModulePtr)))
        {
            ToRelease<IXCLRDataModule> pModule;
            if (SUCCEEDED(g_sos->GetModule(mdescData.ModulePtr, &pModule)))
            {
                ArrayHolder<WCHAR> wszFileName = new WCHAR[MAX_LONGPATH + 1];
                ULONG32 nameLen = 0;
                if (SUCCEEDED(pModule->GetFileName(MAX_LONGPATH, &nameLen, wszFileName)))
                {
                    if (wszFileName[0] != W('\0'))
                    {
                        WCHAR *pJustName = _wcsrchr(wszFileName, DIRECTORY_SEPARATOR_CHAR_W);
                        if (pJustName == NULL)
                            pJustName = wszFileName - 1;
                        methodOutput += (pJustName + 1);
                        methodOutput += W("!");
                    }
                }
            }
        }
    }
}

WString GetFrameFromAddress(TADDR frameAddr, IXCLRDataStackWalk *pStackWalk, BOOL bAssemblyName)
{
    TADDR vtAddr;
    MOVE(vtAddr, frameAddr);

    WString frameOutput;
    frameOutput += W("[");

    if (SUCCEEDED(g_sos->GetFrameName(TO_CDADDR(vtAddr), mdNameLen, g_mdName, NULL)))
        frameOutput += g_mdName;
    else
        frameOutput += W("Frame");
        
    frameOutput += WString(W(": ")) + Pointer(frameAddr) + W("] ");

    // Print the frame's associated function info, if it has any.
    CLRDATA_ADDRESS mdesc = 0;
    if (SUCCEEDED(g_sos->GetMethodDescPtrFromFrame(frameAddr, &mdesc)))
    {
        if (SUCCEEDED(g_sos->GetMethodDescName(mdesc, mdNameLen, g_mdName, NULL)))
        {
            if (bAssemblyName)
            {
                AddAssemblyName(frameOutput, mdesc);
            }

            frameOutput += g_mdName;
        }
        else
        {
            frameOutput += W("<unknown method>");
        }
    }
    else if (pStackWalk)
    {
        // The Frame did not have direct function info, so try to get the method instance
        // (in this case a MethodDesc), and read the name from it.
        ToRelease<IXCLRDataFrame> frame;
        if (SUCCEEDED(pStackWalk->GetFrame(&frame)))
        {
            ToRelease<IXCLRDataMethodInstance> methodInstance;
            if (SUCCEEDED(frame->GetMethodInstance(&methodInstance)))
            {
                // GetName can return S_FALSE if mdNameLen is not large enough.  However we are already
                // passing a pretty big buffer in.  If this returns S_FALSE (meaning the buffer is too
                // small) then we should not output it anyway.
                if (methodInstance->GetName(0, mdNameLen, NULL, g_mdName) == S_OK)
                    frameOutput += g_mdName;
            }
        }
    }
    
    return frameOutput;
}

WString MethodNameFromIP(CLRDATA_ADDRESS ip, BOOL bSuppressLines, BOOL bAssemblyName, BOOL bDisplacement)
{
    ULONG linenum;
    WString methodOutput;
    CLRDATA_ADDRESS mdesc = 0;
    
    if (FAILED(g_sos->GetMethodDescPtrFromIP(ip, &mdesc)))
    {
        methodOutput = W("<unknown>");
    }
    else
    {
        DacpMethodDescData mdescData;
        if (SUCCEEDED(g_sos->GetMethodDescName(mdesc, mdNameLen, g_mdName, NULL)))
        {
            if (bAssemblyName)
            {
                AddAssemblyName(methodOutput, mdesc);
            }

            methodOutput += g_mdName;

            if (bDisplacement)
            {
                if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
                {
                    ULONG64 disp = (ip - mdescData.NativeCodeAddr);
                    if (disp)
                    {
                        methodOutput += W(" + ");
                        methodOutput += Decimal(disp);
                    }
                }
            }
        }
        else if (SUCCEEDED(mdescData.Request(g_sos, mdesc)))
        {
            DacpModuleData dmd;
            BOOL bModuleNameWorked = FALSE;
            ULONG64 addrInModule = ip;
            if (SUCCEEDED(dmd.Request(g_sos, mdescData.ModulePtr)))
            {
                CLRDATA_ADDRESS peFileBase = 0;
                if (SUCCEEDED(g_sos->GetPEFileBase(dmd.File, &peFileBase)))
                {
                    if (peFileBase)
                    {
                        addrInModule = peFileBase;
                    }
                }
            }
            ULONG Index;
            ULONG64 moduleBase;
            if (SUCCEEDED(g_ExtSymbols->GetModuleByOffset(UL64_TO_CDA(addrInModule), 0, &Index, &moduleBase)))
            {                                    
                ArrayHolder<char> szModuleName = new char[MAX_LONGPATH+1];

                if (SUCCEEDED(g_ExtSymbols->GetModuleNames(Index, moduleBase, NULL, 0, NULL, szModuleName, MAX_LONGPATH, NULL, NULL, 0, NULL)))
                {
                    MultiByteToWideChar (CP_ACP, 0, szModuleName, MAX_LONGPATH, g_mdName, _countof(g_mdName));
                    methodOutput += g_mdName;
                    methodOutput += W("!");
                }
            }
            methodOutput += W("<unknown method>");
        }
        else
        {
            methodOutput = W("<unknown>");
        }

        ArrayHolder<WCHAR> wszFileName = new WCHAR[MAX_LONGPATH];
        if (!bSuppressLines &&
            SUCCEEDED(GetLineByOffset(TO_CDADDR(ip), &linenum, wszFileName, MAX_LONGPATH)))
        {
            methodOutput += WString(W(" [")) + wszFileName + W(" @ ") + Decimal(linenum) + W("]");
        }
    }
    
    return methodOutput;
}

HRESULT GetGCRefs(ULONG osID, SOSStackRefData **ppRefs, unsigned int *pRefCnt, SOSStackRefError **ppErrors, unsigned int *pErrCount)
{
    if (ppRefs == NULL || pRefCnt == NULL)
        return E_POINTER;
    
    if (pErrCount)
        *pErrCount = 0;
    
    *pRefCnt = 0;
    unsigned int count = 0;
    ToRelease<ISOSStackRefEnum> pEnum;
    if (FAILED(g_sos->GetStackReferences(osID, &pEnum)) || FAILED(pEnum->GetCount(&count)))
    {
        ExtOut("Failed to enumerate GC references.\n");
                return E_FAIL;
    }
    
    *ppRefs = new SOSStackRefData[count];
    if (FAILED(pEnum->Next(count, *ppRefs, pRefCnt)))
    {
        ExtOut("Failed to enumerate GC references.\n");
        return E_FAIL;
    }
    
    SOS_Assert(count == *pRefCnt);
    
    // Enumerate errors found.  Any bad HRESULT recieved while enumerating errors is NOT a fatal error.
    // Hence we return S_FALSE if we encounter one.
    
    if (ppErrors && pErrCount)
    {
        ToRelease<ISOSStackRefErrorEnum> pErrors;
        if (FAILED(pEnum->EnumerateErrors(&pErrors)))
        {
            ExtOut("Failed to enumerate GC reference errors.\n");
            return S_FALSE;
        }
        
        if (FAILED(pErrors->GetCount(&count)))
        {
            ExtOut("Failed to enumerate GC reference errors.\n");
            return S_FALSE;
        }
        
        *ppErrors = new SOSStackRefError[count];
        if (FAILED(pErrors->Next(count, *ppErrors, pErrCount)))
        {
            ExtOut("Failed to enumerate GC reference errors.\n");
            *pErrCount = 0;
            return S_FALSE;
        }
                  
        SOS_Assert(count == *pErrCount);
    }
    return S_OK;
}


InternalFrameManager::InternalFrameManager() : m_cInternalFramesActual(0), m_iInternalFrameCur(0) {}

HRESULT InternalFrameManager::Init(ICorDebugThread3 * pThread3)
{
    _ASSERTE(pThread3 != NULL);

    return pThread3->GetActiveInternalFrames(
        _countof(m_rgpInternalFrame2),
        &m_cInternalFramesActual,
        &(m_rgpInternalFrame2[0]));
}

HRESULT InternalFrameManager::PrintPrecedingInternalFrames(ICorDebugFrame * pFrame)
{
    HRESULT Status;

    for (; m_iInternalFrameCur < m_cInternalFramesActual; m_iInternalFrameCur++)
    {
        BOOL bIsCloser = FALSE;
        IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->IsCloserToLeaf(pFrame, &bIsCloser));

        if (!bIsCloser)
        {
            // Current internal frame is now past pFrame, so we're done
            return S_OK;
        }

        IfFailRet(PrintCurrentInternalFrame());
    }

    // Exhausted list of internal frames.  Done!
    return S_OK;
}

HRESULT InternalFrameManager::PrintCurrentInternalFrame()
{
    _ASSERTE(m_iInternalFrameCur < m_cInternalFramesActual);

    HRESULT Status;

    CORDB_ADDRESS address;
    IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->GetAddress(&address));

    ToRelease<ICorDebugInternalFrame> pInternalFrame;
    IfFailRet(m_rgpInternalFrame2[m_iInternalFrameCur]->QueryInterface(IID_ICorDebugInternalFrame, (LPVOID *) &pInternalFrame));

    CorDebugInternalFrameType type;
    IfFailRet(pInternalFrame->GetFrameType(&type));

    LPCSTR szFrameType = NULL;
    switch(type)
    {
    default:
        szFrameType = "Unknown internal frame.";
        break;

    case STUBFRAME_M2U:
        szFrameType = "Managed to Unmanaged transition";
        break;

    case STUBFRAME_U2M:
        szFrameType = "Unmanaged to Managed transition";
        break;

    case STUBFRAME_APPDOMAIN_TRANSITION:
        szFrameType = "AppDomain transition";
        break;

    case STUBFRAME_LIGHTWEIGHT_FUNCTION:
        szFrameType = "Lightweight function";
        break;

    case STUBFRAME_FUNC_EVAL:
        szFrameType = "Function evaluation";
        break;

    case STUBFRAME_INTERNALCALL:
        szFrameType = "Internal call";
        break;

    case STUBFRAME_CLASS_INIT:
        szFrameType = "Class initialization";
        break;

    case STUBFRAME_EXCEPTION:
        szFrameType = "Exception";
        break;

    case STUBFRAME_SECURITY:
        szFrameType = "Security";
        break;

    case STUBFRAME_JIT_COMPILATION:
        szFrameType = "JIT Compilation";
        break;
    }

    DMLOut("%p %s ", SOS_PTR(address), SOS_PTR(0));
    ExtOut("[%s: %p]\n", szFrameType, SOS_PTR(address));

    return S_OK;
}