Welcome to mirror list, hosted at ThFree Co, Russian Federation.

util.cpp « vm « coreclr « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 64130d699ea9365b3f8d7d558d3b9d82ffccdeea (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ===========================================================================
// File: UTIL.CPP
//

// ===========================================================================


#include "common.h"
#include "excep.h"
#include "corhost.h"
#include "eventtrace.h"
#include "posterror.h"
#include "eemessagebox.h"

#include <shlobj.h>

#include "dlwrap.h"

#ifndef DACCESS_COMPILE

#ifdef CROSSGEN_COMPILE
void ClrFlsSetThreadType(TlsThreadTypeFlag flag)
{
}

void ClrFlsClearThreadType(TlsThreadTypeFlag flag)
{
}
#else // CROSSGEN_COMPILE

thread_local size_t t_ThreadType;

void ClrFlsSetThreadType(TlsThreadTypeFlag flag)
{
    LIMITED_METHOD_CONTRACT;

    t_ThreadType |= flag;

    // The historic location of ThreadType slot kept for compatibility with SOS
    // TODO: Introduce DAC API to make this hack unnecessary
#if defined(_MSC_VER) && defined(HOST_X86)
    // Workaround for https://developercommunity.visualstudio.com/content/problem/949233/tls-relative-fixup-overflow-tls-section-is-too-lar.html
    gCurrentThreadInfo.m_EETlsData = (void**)(((size_t)&t_ThreadType ^ 1) - (4 * TlsIdx_ThreadType + 1));
#else
    gCurrentThreadInfo.m_EETlsData = (void**)&t_ThreadType - TlsIdx_ThreadType;
#endif
}

void ClrFlsClearThreadType(TlsThreadTypeFlag flag)
{
    LIMITED_METHOD_CONTRACT;
    t_ThreadType &= ~flag;
}
#endif // CROSSGEN_COMPILE

thread_local size_t t_CantStopCount;

// Helper function that encapsulates the parsing rules.
//
// Called first with *pdstout == NULL to figure out how many args there are
// and the size of the required destination buffer.
//
// Called again with a nonnull *pdstout to fill in the actual buffer.
//
// Returns the # of arguments.
static UINT ParseCommandLine(LPCWSTR psrc, __inout LPWSTR *pdstout)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    UINT    argcount = 1;       // discovery of arg0 is unconditional, below
    LPWSTR  pdst     = *pdstout;
    BOOL    fDoWrite = (pdst != NULL);

    BOOL    fInQuotes;
    int     iSlash;

    /* A quoted program name is handled here. The handling is much
       simpler than for other arguments. Basically, whatever lies
       between the leading double-quote and next one, or a terminal null
       character is simply accepted. Fancier handling is not required
       because the program name must be a legal NTFS/HPFS file name.
       Note that the double-quote characters are not copied, nor do they
       contribute to numchars.

       This "simplification" is necessary for compatibility reasons even
       though it leads to mishandling of certain cases.  For example,
       "c:\tests\"test.exe will result in an arg0 of c:\tests\ and an
       arg1 of test.exe.  In any rational world this is incorrect, but
       we need to preserve compatibility.
    */

    LPCWSTR pStart = psrc;
    BOOL    skipQuote = FALSE;

    if (*psrc == W('\"'))
    {
        // scan from just past the first double-quote through the next
        // double-quote, or up to a null, whichever comes first
        while ((*(++psrc) != W('\"')) && (*psrc != W('\0')))
            continue;

        skipQuote = TRUE;
    }
    else
    {
        /* Not a quoted program name */

        while (!ISWWHITE(*psrc) && *psrc != W('\0'))
            psrc++;
    }

    // We have now identified arg0 as pStart (or pStart+1 if we have a leading
    // quote) through psrc-1 inclusive
    if (skipQuote)
        pStart++;
    while (pStart < psrc)
    {
        if (fDoWrite)
            *pdst = *pStart;

        pStart++;
        pdst++;
    }

    // And terminate it.
    if (fDoWrite)
        *pdst = W('\0');

    pdst++;

    // if we stopped on a double-quote when arg0 is quoted, skip over it
    if (skipQuote && *psrc == W('\"'))
        psrc++;

    while ( *psrc != W('\0'))
    {
LEADINGWHITE:

        // The outofarg state.
        while (ISWWHITE(*psrc))
            psrc++;

        if (*psrc == W('\0'))
            break;
        else
        if (*psrc == W('#'))
        {
            while (*psrc != W('\0') && *psrc != W('\n'))
                psrc++;     // skip to end of line

            goto LEADINGWHITE;
        }

        argcount++;
        fInQuotes = FALSE;

        while ((!ISWWHITE(*psrc) || fInQuotes) && *psrc != W('\0'))
        {
            switch (*psrc)
            {
            case W('\\'):
                iSlash = 0;
                while (*psrc == W('\\'))
                {
                    iSlash++;
                    psrc++;
                }

                if (*psrc == W('\"'))
                {
                    for ( ; iSlash >= 2; iSlash -= 2)
                    {
                        if (fDoWrite)
                            *pdst = W('\\');

                        pdst++;
                    }

                    if (iSlash & 1)
                    {
                        if (fDoWrite)
                            *pdst = *psrc;

                        psrc++;
                        pdst++;
                    }
                    else
                    {
                        fInQuotes = !fInQuotes;
                        psrc++;
                    }
                }
                else
                    for ( ; iSlash > 0; iSlash--)
                    {
                        if (fDoWrite)
                            *pdst = W('\\');

                        pdst++;
                    }

                break;

            case W('\"'):
                fInQuotes = !fInQuotes;
                psrc++;
                break;

            default:
                if (fDoWrite)
                    *pdst = *psrc;

                psrc++;
                pdst++;
            }
        }

        if (fDoWrite)
            *pdst = W('\0');

        pdst++;
    }


    _ASSERTE(*psrc == W('\0'));
    *pdstout = pdst;
    return argcount;
}


//************************************************************************
// CQuickHeap
//
// A fast non-multithread-safe heap for short term use.
// Destroying the heap frees all blocks allocated from the heap.
// Blocks cannot be freed individually.
//
// The heap uses COM+ exceptions to report errors.
//
// The heap does not use any internal synchronization so it is not
// multithreadsafe.
//************************************************************************
CQuickHeap::CQuickHeap()
{
    LIMITED_METHOD_CONTRACT;

    m_pFirstQuickBlock    = NULL;
    m_pFirstBigQuickBlock = NULL;
    m_pNextFree           = NULL;
}

CQuickHeap::~CQuickHeap()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    QuickBlock *pQuickBlock = m_pFirstQuickBlock;
    while (pQuickBlock) {
        QuickBlock *ptmp = pQuickBlock;
        pQuickBlock = pQuickBlock->m_next;
        delete [] (BYTE*)ptmp;
    }

    pQuickBlock = m_pFirstBigQuickBlock;
    while (pQuickBlock) {
        QuickBlock *ptmp = pQuickBlock;
        pQuickBlock = pQuickBlock->m_next;
        delete [] (BYTE*)ptmp;
    }
}

LPVOID CQuickHeap::Alloc(UINT sz)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    } CONTRACTL_END;

    sz = (sz+7) & ~7;

    if ( sz > kBlockSize ) {

        QuickBlock *pQuickBigBlock = (QuickBlock*) new BYTE[sz + sizeof(QuickBlock) - 1];
        pQuickBigBlock->m_next = m_pFirstBigQuickBlock;
        m_pFirstBigQuickBlock = pQuickBigBlock;

        return pQuickBigBlock->m_bytes;


    } else {
        if (m_pNextFree == NULL || sz > (UINT)( &(m_pFirstQuickBlock->m_bytes[kBlockSize]) - m_pNextFree )) {
            QuickBlock *pQuickBlock = (QuickBlock*) new BYTE[kBlockSize + sizeof(QuickBlock) - 1];
            pQuickBlock->m_next = m_pFirstQuickBlock;
            m_pFirstQuickBlock = pQuickBlock;
            m_pNextFree = pQuickBlock->m_bytes;
        }
        LPVOID pv = m_pNextFree;
        m_pNextFree += sz;
        return pv;
    }
}

//----------------------------------------------------------------------------
// Output functions that avoid the crt's.
//----------------------------------------------------------------------------

static
void NPrintToHandleA(HANDLE Handle, const char *pszString, size_t BytesToWrite)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    if (Handle == INVALID_HANDLE_VALUE || Handle == NULL)
        return;

    BOOL success;
    DWORD   dwBytesWritten;
    const size_t maxWriteFileSize = 32767; // This is somewhat arbitrary limit, but 2**16-1 doesn't work

    while (BytesToWrite > 0) {
        DWORD dwChunkToWrite = (DWORD) min(BytesToWrite, maxWriteFileSize);
        // No CharNextExA on CoreSystem, we just assume no multi-byte characters (this code path shouldn't be
        // used in the production codepath for currently supported CoreSystem based products anyway).
#ifndef FEATURE_CORESYSTEM
        if (dwChunkToWrite < BytesToWrite) {
            break;
            // must go by char to find biggest string that will fit, taking DBCS chars into account
            //dwChunkToWrite = 0;
            //const char *charNext = pszString;
            //while (dwChunkToWrite < maxWriteFileSize-2 && charNext) {
            //    charNext = CharNextExA(0, pszString+dwChunkToWrite, 0);
            //    dwChunkToWrite = (DWORD)(charNext - pszString);
            //}
            //if (dwChunkToWrite == 0)
            //    break;
        }
#endif // !FEATURE_CORESYSTEM

        // Try to write to handle.  If this is not a CUI app, then this is probably
        // not going to work unless the dev took special pains to set their own console
        // handle during CreateProcess.  So try it, but don't yell if it doesn't work in
        // that case.  Also, if we redirect stdout to a pipe then the pipe breaks (ie, we
        // write to something like the UNIX head command), don't complain.
        success = WriteFile(Handle, pszString, dwChunkToWrite, &dwBytesWritten, NULL);
        if (!success)
        {
#if defined(_DEBUG)
            // This can happen if stdout is a closed pipe.  This might not help
            // much, but we'll have half a chance of seeing this.
            OutputDebugStringA("CLR: Writing out an unhandled exception to stdout failed!\n");
            OutputDebugStringA(pszString);
#endif //_DEBUG

            break;
        }
        else {
            _ASSERTE(dwBytesWritten == dwChunkToWrite);
        }
        pszString = pszString + dwChunkToWrite;
        BytesToWrite -= dwChunkToWrite;
    }

}

static
void PrintToHandleA(HANDLE Handle, const char *pszString)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    size_t len = strlen(pszString);
    NPrintToHandleA(Handle, pszString, len);
}

void PrintToStdOutA(const char *pszString) {
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    HANDLE  Handle = GetStdHandle(STD_OUTPUT_HANDLE);
    PrintToHandleA(Handle, pszString);
}


void PrintToStdOutW(const WCHAR *pwzString)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    MAKE_MULTIBYTE_FROMWIDE_BESTFIT(pStr, pwzString, GetConsoleOutputCP());

    PrintToStdOutA(pStr);
}

void PrintToStdErrA(const char *pszString) {
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    HANDLE  Handle = GetStdHandle(STD_ERROR_HANDLE);
    PrintToHandleA(Handle, pszString);
}


void PrintToStdErrW(const WCHAR *pwzString)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    MAKE_MULTIBYTE_FROMWIDE_BESTFIT(pStr, pwzString, GetConsoleOutputCP());

    PrintToStdErrA(pStr);
}



void NPrintToStdOutA(const char *pszString, size_t nbytes) {
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    HANDLE  Handle = GetStdHandle(STD_OUTPUT_HANDLE);
    NPrintToHandleA(Handle, pszString, nbytes);
}


void NPrintToStdOutW(const WCHAR *pwzString, size_t nchars)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    LPSTR pStr;
    MAKE_MULTIBYTE_FROMWIDEN_BESTFIT(pStr, pwzString, (int)nchars, nbytes, GetConsoleOutputCP());

    NPrintToStdOutA(pStr, nbytes);
}

void NPrintToStdErrA(const char *pszString, size_t nbytes) {
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    HANDLE  Handle = GetStdHandle(STD_ERROR_HANDLE);
    NPrintToHandleA(Handle, pszString, nbytes);
}


void NPrintToStdErrW(const WCHAR *pwzString, size_t nchars)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END

    LPSTR pStr;

    MAKE_MULTIBYTE_FROMWIDEN_BESTFIT(pStr, pwzString, (int)nchars, nbytes, GetConsoleOutputCP());

    NPrintToStdErrA(pStr, nbytes);
}
//----------------------------------------------------------------------------

//*****************************************************************************
// Compare VarLoc's
//*****************************************************************************

bool operator ==(const ICorDebugInfo::VarLoc &varLoc1,
                 const ICorDebugInfo::VarLoc &varLoc2)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    if (varLoc1.vlType != varLoc2.vlType)
        return false;

    switch(varLoc1.vlType)
    {
    case ICorDebugInfo::VLT_REG:
    case ICorDebugInfo::VLT_REG_BYREF:
        return varLoc1.vlReg.vlrReg == varLoc2.vlReg.vlrReg;

    case ICorDebugInfo::VLT_STK:
    case ICorDebugInfo::VLT_STK_BYREF:
        return varLoc1.vlStk.vlsBaseReg == varLoc2.vlStk.vlsBaseReg &&
               varLoc1.vlStk.vlsOffset  == varLoc2.vlStk.vlsOffset;

    case ICorDebugInfo::VLT_REG_REG:
        return varLoc1.vlRegReg.vlrrReg1 == varLoc2.vlRegReg.vlrrReg1 &&
               varLoc1.vlRegReg.vlrrReg2 == varLoc2.vlRegReg.vlrrReg2;

    case ICorDebugInfo::VLT_REG_STK:
        return varLoc1.vlRegStk.vlrsReg == varLoc2.vlRegStk.vlrsReg &&
               varLoc1.vlRegStk.vlrsStk.vlrssBaseReg == varLoc2.vlRegStk.vlrsStk.vlrssBaseReg &&
               varLoc1.vlRegStk.vlrsStk.vlrssOffset == varLoc2.vlRegStk.vlrsStk.vlrssOffset;

    case ICorDebugInfo::VLT_STK_REG:
        return varLoc1.vlStkReg.vlsrStk.vlsrsBaseReg == varLoc2.vlStkReg.vlsrStk.vlsrsBaseReg &&
               varLoc1.vlStkReg.vlsrStk.vlsrsOffset == varLoc2.vlStkReg.vlsrStk.vlsrsBaseReg &&
               varLoc1.vlStkReg.vlsrReg == varLoc2.vlStkReg.vlsrReg;

    case ICorDebugInfo::VLT_STK2:
        return varLoc1.vlStk2.vls2BaseReg == varLoc2.vlStk2.vls2BaseReg &&
               varLoc1.vlStk2.vls2Offset == varLoc2.vlStk2.vls2Offset;

    case ICorDebugInfo::VLT_FPSTK:
        return varLoc1.vlFPstk.vlfReg == varLoc2.vlFPstk.vlfReg;

    default:
        _ASSERTE(!"Bad vlType"); return false;
    }
}

#endif // #ifndef DACCESS_COMPILE

//*****************************************************************************
// The following are used to read and write data given NativeVarInfo
// for primitive types. For ValueClasses, FALSE will be returned.
//*****************************************************************************

SIZE_T GetRegOffsInCONTEXT(ICorDebugInfo::RegNum regNum)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

#ifdef TARGET_X86
    switch(regNum)
    {
    case ICorDebugInfo::REGNUM_EAX: return offsetof(T_CONTEXT,Eax);
    case ICorDebugInfo::REGNUM_ECX: return offsetof(T_CONTEXT,Ecx);
    case ICorDebugInfo::REGNUM_EDX: return offsetof(T_CONTEXT,Edx);
    case ICorDebugInfo::REGNUM_EBX: return offsetof(T_CONTEXT,Ebx);
    // TODO: Fix AMBIENT_SP handling.
    // AMBIENT_SP It isn't necessarily the same value as ESP.  We probably shouldn't try
    // and handle REGNUM_AMBIENT_SP here, and instead update our callers (eg.
    // GetNativeVarVal) to handle this case explicitly.  This logic should also be
    // merged with the parallel (but correct in this case) logic in mscordbi.
    case ICorDebugInfo::REGNUM_ESP:
    case ICorDebugInfo::REGNUM_AMBIENT_SP:
                                    return offsetof(T_CONTEXT,Esp);
    case ICorDebugInfo::REGNUM_EBP: return offsetof(T_CONTEXT,Ebp);
    case ICorDebugInfo::REGNUM_ESI: return offsetof(T_CONTEXT,Esi);
    case ICorDebugInfo::REGNUM_EDI: return offsetof(T_CONTEXT,Edi);
    default: _ASSERTE(!"Bad regNum"); return (SIZE_T) -1;
    }
#elif defined(TARGET_AMD64)
    switch(regNum)
    {
    case ICorDebugInfo::REGNUM_RAX: return offsetof(CONTEXT, Rax);
    case ICorDebugInfo::REGNUM_RCX: return offsetof(CONTEXT, Rcx);
    case ICorDebugInfo::REGNUM_RDX: return offsetof(CONTEXT, Rdx);
    case ICorDebugInfo::REGNUM_RBX: return offsetof(CONTEXT, Rbx);
    case ICorDebugInfo::REGNUM_RSP: return offsetof(CONTEXT, Rsp);
    case ICorDebugInfo::REGNUM_RBP: return offsetof(CONTEXT, Rbp);
    case ICorDebugInfo::REGNUM_RSI: return offsetof(CONTEXT, Rsi);
    case ICorDebugInfo::REGNUM_RDI: return offsetof(CONTEXT, Rdi);
    case ICorDebugInfo::REGNUM_R8:  return offsetof(CONTEXT, R8);
    case ICorDebugInfo::REGNUM_R9:  return offsetof(CONTEXT, R9);
    case ICorDebugInfo::REGNUM_R10: return offsetof(CONTEXT, R10);
    case ICorDebugInfo::REGNUM_R11: return offsetof(CONTEXT, R11);
    case ICorDebugInfo::REGNUM_R12: return offsetof(CONTEXT, R12);
    case ICorDebugInfo::REGNUM_R13: return offsetof(CONTEXT, R13);
    case ICorDebugInfo::REGNUM_R14: return offsetof(CONTEXT, R14);
    case ICorDebugInfo::REGNUM_R15: return offsetof(CONTEXT, R15);
    default: _ASSERTE(!"Bad regNum"); return (SIZE_T)(-1);
    }
#elif defined(TARGET_ARM)

    switch(regNum)
    {
    case ICorDebugInfo::REGNUM_R0: return offsetof(T_CONTEXT, R0);
    case ICorDebugInfo::REGNUM_R1: return offsetof(T_CONTEXT, R1);
    case ICorDebugInfo::REGNUM_R2: return offsetof(T_CONTEXT, R2);
    case ICorDebugInfo::REGNUM_R3: return offsetof(T_CONTEXT, R3);
    case ICorDebugInfo::REGNUM_R4: return offsetof(T_CONTEXT, R4);
    case ICorDebugInfo::REGNUM_R5: return offsetof(T_CONTEXT, R5);
    case ICorDebugInfo::REGNUM_R6: return offsetof(T_CONTEXT, R6);
    case ICorDebugInfo::REGNUM_R7: return offsetof(T_CONTEXT, R7);
    case ICorDebugInfo::REGNUM_R8: return offsetof(T_CONTEXT, R8);
    case ICorDebugInfo::REGNUM_R9: return offsetof(T_CONTEXT, R9);
    case ICorDebugInfo::REGNUM_R10: return offsetof(T_CONTEXT, R10);
    case ICorDebugInfo::REGNUM_R11: return offsetof(T_CONTEXT, R11);
    case ICorDebugInfo::REGNUM_R12: return offsetof(T_CONTEXT, R12);
    case ICorDebugInfo::REGNUM_SP: return offsetof(T_CONTEXT, Sp);
    case ICorDebugInfo::REGNUM_PC: return offsetof(T_CONTEXT, Pc);
    case ICorDebugInfo::REGNUM_LR: return offsetof(T_CONTEXT, Lr);
    case ICorDebugInfo::REGNUM_AMBIENT_SP: return offsetof(T_CONTEXT, Sp);
    default: _ASSERTE(!"Bad regNum"); return (SIZE_T)(-1);
    }
#elif defined(TARGET_ARM64)

    switch(regNum)
    {
    case ICorDebugInfo::REGNUM_X0: return offsetof(T_CONTEXT, X0);
    case ICorDebugInfo::REGNUM_X1: return offsetof(T_CONTEXT, X1);
    case ICorDebugInfo::REGNUM_X2: return offsetof(T_CONTEXT, X2);
    case ICorDebugInfo::REGNUM_X3: return offsetof(T_CONTEXT, X3);
    case ICorDebugInfo::REGNUM_X4: return offsetof(T_CONTEXT, X4);
    case ICorDebugInfo::REGNUM_X5: return offsetof(T_CONTEXT, X5);
    case ICorDebugInfo::REGNUM_X6: return offsetof(T_CONTEXT, X6);
    case ICorDebugInfo::REGNUM_X7: return offsetof(T_CONTEXT, X7);
    case ICorDebugInfo::REGNUM_X8: return offsetof(T_CONTEXT, X8);
    case ICorDebugInfo::REGNUM_X9: return offsetof(T_CONTEXT, X9);
    case ICorDebugInfo::REGNUM_X10: return offsetof(T_CONTEXT, X10);
    case ICorDebugInfo::REGNUM_X11: return offsetof(T_CONTEXT, X11);
    case ICorDebugInfo::REGNUM_X12: return offsetof(T_CONTEXT, X12);
    case ICorDebugInfo::REGNUM_X13: return offsetof(T_CONTEXT, X13);
    case ICorDebugInfo::REGNUM_X14: return offsetof(T_CONTEXT, X14);
    case ICorDebugInfo::REGNUM_X15: return offsetof(T_CONTEXT, X15);
    case ICorDebugInfo::REGNUM_X16: return offsetof(T_CONTEXT, X16);
    case ICorDebugInfo::REGNUM_X17: return offsetof(T_CONTEXT, X17);
    case ICorDebugInfo::REGNUM_X18: return offsetof(T_CONTEXT, X18);
    case ICorDebugInfo::REGNUM_X19: return offsetof(T_CONTEXT, X19);
    case ICorDebugInfo::REGNUM_X20: return offsetof(T_CONTEXT, X20);
    case ICorDebugInfo::REGNUM_X21: return offsetof(T_CONTEXT, X21);
    case ICorDebugInfo::REGNUM_X22: return offsetof(T_CONTEXT, X22);
    case ICorDebugInfo::REGNUM_X23: return offsetof(T_CONTEXT, X23);
    case ICorDebugInfo::REGNUM_X24: return offsetof(T_CONTEXT, X24);
    case ICorDebugInfo::REGNUM_X25: return offsetof(T_CONTEXT, X25);
    case ICorDebugInfo::REGNUM_X26: return offsetof(T_CONTEXT, X26);
    case ICorDebugInfo::REGNUM_X27: return offsetof(T_CONTEXT, X27);
    case ICorDebugInfo::REGNUM_X28: return offsetof(T_CONTEXT, X28);
    case ICorDebugInfo::REGNUM_FP: return offsetof(T_CONTEXT, Fp);
    case ICorDebugInfo::REGNUM_LR: return offsetof(T_CONTEXT, Lr);
    case ICorDebugInfo::REGNUM_SP: return offsetof(T_CONTEXT, Sp);
    case ICorDebugInfo::REGNUM_PC: return offsetof(T_CONTEXT, Pc);
    case ICorDebugInfo::REGNUM_AMBIENT_SP: return offsetof(T_CONTEXT, Sp);
    default: _ASSERTE(!"Bad regNum"); return (SIZE_T)(-1);
    }
#else
    PORTABILITY_ASSERT("GetRegOffsInCONTEXT is not implemented on this platform.");
    return (SIZE_T) -1;
#endif  // TARGET_X86
}

SIZE_T DereferenceByRefVar(SIZE_T addr)
{
    STATIC_CONTRACT_WRAPPER;

    SIZE_T result = NULL;

#if defined(DACCESS_COMPILE)
    HRESULT hr = DacReadAll(addr, &result, sizeof(result), false);
    if (FAILED(hr))
    {
        result = NULL;
    }

#else  // !DACCESS_COMPILE
    EX_TRY
    {
        AVInRuntimeImplOkayHolder AVOkay;

        result = *(SIZE_T*)addr;
    }
    EX_CATCH
    {
    }
    EX_END_CATCH(SwallowAllExceptions);

#endif // !DACCESS_COMPILE

    return result;
}

// How are errors communicated to the caller?
ULONG NativeVarLocations(const ICorDebugInfo::VarLoc &   varLoc,
                         PT_CONTEXT                      pCtx,
                         ULONG                           numLocs,
                         NativeVarLocation*              locs)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    _ASSERTE(numLocs >= MAX_NATIVE_VAR_LOCS);

    bool fByRef = false;
    switch(varLoc.vlType)
    {
        SIZE_T regOffs;
        TADDR  baseReg;

    case ICorDebugInfo::VLT_REG_BYREF:
        fByRef = true;                  // fall through
        FALLTHROUGH;
    case ICorDebugInfo::VLT_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlReg.vlrReg);
        locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
        if (fByRef)
        {
            locs->addr = (ULONG64)DereferenceByRefVar((SIZE_T)locs->addr);
        }
        locs->size = sizeof(SIZE_T);
        {
            locs->contextReg = true;
        }
        return 1;

    case ICorDebugInfo::VLT_STK_BYREF:
        fByRef = true;                      // fall through
        FALLTHROUGH;
    case ICorDebugInfo::VLT_STK:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStk.vlsBaseReg);
        baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
        locs->addr = baseReg + varLoc.vlStk.vlsOffset;
        if (fByRef)
        {
            locs->addr = (ULONG64)DereferenceByRefVar((SIZE_T)locs->addr);
        }
        locs->size = sizeof(SIZE_T);
        locs->contextReg = false;
        return 1;

    case ICorDebugInfo::VLT_REG_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg1);
        locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
        locs->size = sizeof(SIZE_T);
        locs->contextReg = true;
        locs++;

        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg2);
        locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
        locs->size = sizeof(SIZE_T);
        locs->contextReg = true;
        return 2;

    case ICorDebugInfo::VLT_REG_STK:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsReg);
        locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
        locs->size = sizeof(SIZE_T);
        locs->contextReg = true;
        locs++;

        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsStk.vlrssBaseReg);
        baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
        locs->addr = baseReg + varLoc.vlRegStk.vlrsStk.vlrssOffset;
        locs->size = sizeof(SIZE_T);
        locs->contextReg = false;
        return 2;

    case ICorDebugInfo::VLT_STK_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrStk.vlsrsBaseReg);
        baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
        locs->addr = baseReg + varLoc.vlStkReg.vlsrStk.vlsrsOffset;
        locs->size = sizeof(SIZE_T);
        locs->contextReg = false;
        locs++;

        regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrReg);
        locs->addr = (ULONG64)(ULONG_PTR)pCtx + regOffs;
        locs->size = sizeof(SIZE_T);
        locs->contextReg = true;
        return 2;

    case ICorDebugInfo::VLT_STK2:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStk2.vls2BaseReg);
        baseReg = *(TADDR *)(regOffs + (BYTE*)pCtx);
        locs->addr = baseReg + varLoc.vlStk2.vls2Offset;
        locs->size = 2 * sizeof(SIZE_T);
        locs->contextReg = false;
        return 1;

    case ICorDebugInfo::VLT_FPSTK:
         _ASSERTE(!"NYI");
         return 0;

    default:
         _ASSERTE(!"Bad locType");
         return 0;
    }
}


#ifndef DACCESS_COMPILE

// Returns the location at which the variable
// begins.  Returns NULL for register vars.  For reg-stack
// split, it'll return the addr of the stack part.
// This also works for VLT_REG (a single register).
SIZE_T *NativeVarStackAddr(const ICorDebugInfo::VarLoc &   varLoc,
                           PCONTEXT                        pCtx)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    SIZE_T *dwAddr = NULL;

    bool fByRef = false;
    switch(varLoc.vlType)
    {
        SIZE_T          regOffs;
        const BYTE *    baseReg;

    case ICorDebugInfo::VLT_REG_BYREF:
        fByRef = true;                      // fall through
        FALLTHROUGH;
    case ICorDebugInfo::VLT_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlReg.vlrReg);
        dwAddr = (SIZE_T *)(regOffs + (BYTE*)pCtx);
        if (fByRef)
        {
            dwAddr = (SIZE_T*)(*dwAddr);
        }
        LOG((LF_CORDB, LL_INFO100, "NVSA: VLT_REG @ 0x%x (by ref = %d)\n", dwAddr, fByRef));
        break;

    case ICorDebugInfo::VLT_STK_BYREF:
        fByRef = true;                      // fall through
        FALLTHROUGH;
    case ICorDebugInfo::VLT_STK:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStk.vlsBaseReg);
        baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
        dwAddr  = (SIZE_T *)(baseReg + varLoc.vlStk.vlsOffset);
        if (fByRef)
        {
            dwAddr = (SIZE_T*)(*dwAddr);
        }
        LOG((LF_CORDB, LL_INFO100, "NVSA: VLT_STK @ 0x%x (by ref = %d)\n", dwAddr, fByRef));
        break;

    case ICorDebugInfo::VLT_STK2:
        // <TODO>@TODO : VLT_STK2 is overloaded to also mean VLT_STK_n.
        // return FALSE if n > 2;</TODO>

        regOffs = GetRegOffsInCONTEXT(varLoc.vlStk2.vls2BaseReg);
        baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
        dwAddr = (SIZE_T *)(baseReg + varLoc.vlStk2.vls2Offset);
        LOG((LF_CORDB, LL_INFO100, "NVSA: VLT_STK_2 @ 0x%x\n",dwAddr));
        break;

    case ICorDebugInfo::VLT_REG_STK:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsStk.vlrssBaseReg);
        baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
        dwAddr = (SIZE_T *)(baseReg + varLoc.vlRegStk.vlrsStk.vlrssOffset);
        LOG((LF_CORDB, LL_INFO100, "NVSA: REG_STK @ 0x%x\n",dwAddr));
        break;

    case ICorDebugInfo::VLT_STK_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrStk.vlsrsBaseReg);
        baseReg = (const BYTE *)*(SIZE_T *)(regOffs + (BYTE*)pCtx);
        dwAddr = (SIZE_T *)(baseReg + varLoc.vlStkReg.vlsrStk.vlsrsOffset);
        LOG((LF_CORDB, LL_INFO100, "NVSA: STK_REG @ 0x%x\n",dwAddr));
        break;

    case ICorDebugInfo::VLT_REG_REG:
    case ICorDebugInfo::VLT_FPSTK:
         _ASSERTE(!"NYI"); break;

    default:
         _ASSERTE(!"Bad locType"); break;
    }

    return dwAddr;

}


#if defined(HOST_64BIT)
void GetNativeVarValHelper(SIZE_T* dstAddrLow, SIZE_T* dstAddrHigh, SIZE_T* srcAddr, SIZE_T size)
{
    if (size == 1)
        *(BYTE*)dstAddrLow   = *(BYTE*)srcAddr;
    else if (size == 2)
        *(USHORT*)dstAddrLow = *(USHORT*)srcAddr;
    else if (size == 4)
        *(ULONG*)dstAddrLow  = *(ULONG*)srcAddr;
    else if (size == 8)
        *dstAddrLow          = *srcAddr;
    else if (size == 16)
    {
        *dstAddrLow  = *srcAddr;
        *dstAddrHigh = *(srcAddr+1);
    }
    else
    {
        _ASSERTE(!"util.cpp - unreachable code.\n");
        UNREACHABLE();
    }
}
#endif // HOST_64BIT


bool    GetNativeVarVal(const ICorDebugInfo::VarLoc &   varLoc,
                        PCONTEXT                        pCtx,
                        SIZE_T                      *   pVal1,
                        SIZE_T                      *   pVal2
                        BIT64_ARG(SIZE_T                cbSize))
{

    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    switch(varLoc.vlType)
    {
#if !defined(HOST_64BIT)
        SIZE_T          regOffs;

    case ICorDebugInfo::VLT_REG:
        *pVal1  = *NativeVarStackAddr(varLoc,pCtx);
        break;

    case ICorDebugInfo::VLT_STK:
        *pVal1  = *NativeVarStackAddr(varLoc,pCtx);
        break;

    case ICorDebugInfo::VLT_STK2:
        *pVal1  = *NativeVarStackAddr(varLoc,pCtx);
        *pVal2  = *(NativeVarStackAddr(varLoc,pCtx)+ 1);
        break;

    case ICorDebugInfo::VLT_REG_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg1);
        *pVal1 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
        LOG((LF_CORDB, LL_INFO100, "GNVV: STK_REG_REG 1 @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));

        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg2);
        *pVal2 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
        LOG((LF_CORDB, LL_INFO100, "GNVV: STK_REG_REG 2 @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));
        break;

    case ICorDebugInfo::VLT_REG_STK:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsReg);
        *pVal1 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
        LOG((LF_CORDB, LL_INFO100, "GNVV: STK_REG_STK reg @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));
        *pVal2 = *NativeVarStackAddr(varLoc,pCtx);
        break;

    case ICorDebugInfo::VLT_STK_REG:
        *pVal1 = *NativeVarStackAddr(varLoc,pCtx);
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrReg);
        *pVal2 = *(SIZE_T *)(regOffs + (BYTE*)pCtx);
        LOG((LF_CORDB, LL_INFO100, "GNVV: STK_STK_REG reg @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));
        break;

    case ICorDebugInfo::VLT_FPSTK:
         _ASSERTE(!"NYI"); break;

#else  // HOST_64BIT
    case ICorDebugInfo::VLT_REG:
    case ICorDebugInfo::VLT_REG_FP:
    case ICorDebugInfo::VLT_STK:
        GetNativeVarValHelper(pVal1, pVal2, NativeVarStackAddr(varLoc, pCtx), cbSize);
        break;

    case ICorDebugInfo::VLT_REG_BYREF:      // fall through
    case ICorDebugInfo::VLT_STK_BYREF:
        _ASSERTE(!"GNVV: This function should not be called for value types");
        break;

#endif // HOST_64BIT

    default:
         _ASSERTE(!"Bad locType"); break;
    }

    return true;
}


#if defined(HOST_64BIT)
void SetNativeVarValHelper(SIZE_T* dstAddr, SIZE_T valueLow, SIZE_T valueHigh, SIZE_T size)
{
    if (size == 1)
        *(BYTE*)dstAddr   = (BYTE)valueLow;
    else if (size == 2)
        *(USHORT*)dstAddr = (USHORT)valueLow;
    else if (size == 4)
        *(ULONG*)dstAddr  = (ULONG)valueLow;
    else if (size == 8)
        *dstAddr          = valueLow;
    else if (size == 16)
    {
        *dstAddr          = valueLow;
        *(dstAddr+1)      = valueHigh;
    }
    else
    {
        _ASSERTE(!"util.cpp - unreachable code.\n");
        UNREACHABLE();
    }
}
#endif // HOST_64BIT


bool    SetNativeVarVal(const ICorDebugInfo::VarLoc &   varLoc,
                        PCONTEXT                        pCtx,
                        SIZE_T                          val1,
                        SIZE_T                          val2
                        BIT64_ARG(SIZE_T                cbSize))
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_FORBID_FAULT;

    switch(varLoc.vlType)
    {
#if !defined(HOST_64BIT)
        SIZE_T          regOffs;

    case ICorDebugInfo::VLT_REG:
        *NativeVarStackAddr(varLoc,pCtx) = val1;
        break;

    case ICorDebugInfo::VLT_STK:
        *NativeVarStackAddr(varLoc,pCtx) = val1;
        break;

    case ICorDebugInfo::VLT_STK2:
        *NativeVarStackAddr(varLoc,pCtx) = val1;
        *(NativeVarStackAddr(varLoc,pCtx)+ 1) = val2;
        break;

    case ICorDebugInfo::VLT_REG_REG:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg1);
        *(SIZE_T *)(regOffs + (BYTE*)pCtx) = val1;
        LOG((LF_CORDB, LL_INFO100, "SNVV: STK_REG_REG 1 @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));

        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegReg.vlrrReg2);
        *(SIZE_T *)(regOffs + (BYTE*)pCtx) = val2;
        LOG((LF_CORDB, LL_INFO100, "SNVV: STK_REG_REG 2 @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));
        break;

    case ICorDebugInfo::VLT_REG_STK:
        regOffs = GetRegOffsInCONTEXT(varLoc.vlRegStk.vlrsReg);
        *(SIZE_T *)(regOffs + (BYTE*)pCtx) = val1;
        LOG((LF_CORDB, LL_INFO100, "SNVV: STK_REG_STK reg @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));
        *NativeVarStackAddr(varLoc,pCtx) = val2;
        break;

    case ICorDebugInfo::VLT_STK_REG:
        *NativeVarStackAddr(varLoc,pCtx) = val1;
        regOffs = GetRegOffsInCONTEXT(varLoc.vlStkReg.vlsrReg);
        *(SIZE_T *)(regOffs + (BYTE*)pCtx) = val2;
        LOG((LF_CORDB, LL_INFO100, "SNVV: STK_STK_REG reg @ 0x%x\n",
            (SIZE_T *)(regOffs + (BYTE*)pCtx)));
        break;

    case ICorDebugInfo::VLT_FPSTK:
         _ASSERTE(!"NYI"); break;

#else  // HOST_64BIT
    case ICorDebugInfo::VLT_REG:
    case ICorDebugInfo::VLT_REG_FP:
    case ICorDebugInfo::VLT_STK:
        SetNativeVarValHelper(NativeVarStackAddr(varLoc, pCtx), val1, val2, cbSize);
        break;

    case ICorDebugInfo::VLT_REG_BYREF:      // fall through
    case ICorDebugInfo::VLT_STK_BYREF:
        _ASSERTE(!"GNVV: This function should not be called for value types");
        break;

#endif // HOST_64BIT

    default:
         _ASSERTE(!"Bad locType"); break;
    }

    return true;
}

LPVOID
CLRMapViewOfFile(
    IN HANDLE hFileMappingObject,
    IN DWORD dwDesiredAccess,
    IN DWORD dwFileOffsetHigh,
    IN DWORD dwFileOffsetLow,
    IN SIZE_T dwNumberOfBytesToMap,
    IN LPVOID lpBaseAddress
    )
{
#ifdef _DEBUG
#ifdef TARGET_X86

    char *tmp = new (nothrow) char;
    if (!tmp)
    {
        SetLastError(ERROR_OUTOFMEMORY);
        return NULL;
    }
    delete tmp;

#endif // TARGET_X86
#endif // _DEBUG

    LPVOID pv = MapViewOfFileEx(hFileMappingObject,dwDesiredAccess,dwFileOffsetHigh,dwFileOffsetLow,dwNumberOfBytesToMap,lpBaseAddress);


    if (!pv)
    {
        if(GetLastError()==ERROR_SUCCESS)
            SetLastError(ERROR_OUTOFMEMORY);
        return NULL;
    }

#ifdef _DEBUG
#ifdef TARGET_X86
    if (pv && g_pConfig && g_pConfig->ShouldInjectFault(INJECTFAULT_MAPVIEWOFFILE))
    {
        MEMORY_BASIC_INFORMATION mbi;
        memset(&mbi, 0, sizeof(mbi));
        if (!ClrVirtualQuery(pv, &mbi, sizeof(mbi)))
        {
            if(GetLastError()==ERROR_SUCCESS)
                SetLastError(ERROR_OUTOFMEMORY);
            return NULL;
        }
        UnmapViewOfFile(pv);
        pv = ClrVirtualAlloc(lpBaseAddress, mbi.RegionSize, MEM_RESERVE, PAGE_NOACCESS);
    }
    else
#endif // TARGET_X86
#endif // _DEBUG
    {
    }

    if (!pv && GetLastError()==ERROR_SUCCESS)
        SetLastError(ERROR_OUTOFMEMORY);

    return pv;
}

BOOL
CLRUnmapViewOfFile(
    IN LPVOID lpBaseAddress
    )
{
    STATIC_CONTRACT_ENTRY_POINT;

#ifdef _DEBUG
#ifdef TARGET_X86
    if (g_pConfig && g_pConfig->ShouldInjectFault(INJECTFAULT_MAPVIEWOFFILE))
    {
        return ClrVirtualFree((LPVOID)lpBaseAddress, 0, MEM_RELEASE);
    }
    else
#endif // TARGET_X86
#endif // _DEBUG
    {
        BOOL result = UnmapViewOfFile(lpBaseAddress);
        if (result)
        {
        }
        return result;
    }
}


#ifndef CROSSGEN_COMPILE

static HMODULE CLRLoadLibraryWorker(LPCWSTR lpLibFileName, DWORD *pLastError)
{
    // Don't use dynamic contract: will override GetLastError value
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FAULT;

    HMODULE hMod;
    UINT last = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS);
    {
        INDEBUG(PEDecoder::ForceRelocForDLL(lpLibFileName));
        hMod = WszLoadLibrary(lpLibFileName);
        *pLastError = GetLastError();
    }
    SetErrorMode(last);
    return hMod;
}

HMODULE CLRLoadLibrary(LPCWSTR lpLibFileName)
{
    // Don't use dynamic contract: will override GetLastError value
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FAULT;

    DWORD dwLastError = 0;
    HMODULE hmod = 0;

    hmod = CLRLoadLibraryWorker(lpLibFileName, &dwLastError);

    SetLastError(dwLastError);
    return hmod;
}

#ifndef TARGET_UNIX

static HMODULE CLRLoadLibraryExWorker(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags, DWORD *pLastError)

{
    // Don't use dynamic contract: will override GetLastError value
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FAULT;

    HMODULE hMod;
    UINT last = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS);
    {
        INDEBUG(PEDecoder::ForceRelocForDLL(lpLibFileName));
        hMod = WszLoadLibraryEx(lpLibFileName, hFile, dwFlags);
        *pLastError = GetLastError();
    }
    SetErrorMode(last);
    return hMod;
}

HMODULE CLRLoadLibraryEx(LPCWSTR lpLibFileName, HANDLE hFile, DWORD dwFlags)
{
    // Don't use dynamic contract: will override GetLastError value

    // This will throw in the case of SO
    //STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FAULT;

    DWORD lastError = ERROR_SUCCESS;
    HMODULE hmod = NULL;

    hmod = CLRLoadLibraryExWorker(lpLibFileName, hFile, dwFlags, &lastError);

    SetLastError(lastError);
    return hmod;
}

#endif // !TARGET_UNIX

BOOL CLRFreeLibrary(HMODULE hModule)
{
    // Don't use dynamic contract: will override GetLastError value
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_TRIGGERS;
    STATIC_CONTRACT_FORBID_FAULT;

    return FreeLibrary(hModule);
}

#endif // CROSSGEN_COMPILE

#endif // #ifndef DACCESS_COMPILE

GPTR_IMPL(JITNotification, g_pNotificationTable);
GVAL_IMPL(ULONG32, g_dacNotificationFlags);

BOOL IsValidMethodCodeNotification(USHORT Notification)
{
    // If any bit is on other than that given by a valid combination of flags, no good.
    if (Notification & ~(
        CLRDATA_METHNOTIFY_NONE |
        CLRDATA_METHNOTIFY_GENERATED |
        CLRDATA_METHNOTIFY_DISCARDED))
    {
        return FALSE;
    }

    return TRUE;
}

JITNotifications::JITNotifications(JITNotification *jitTable)
{
    LIMITED_METHOD_CONTRACT;
    if (jitTable)
    {
        // Bookkeeping info is held in the first slot
        m_jitTable = jitTable + 1;
    }
    else
    {
        m_jitTable = NULL;
    }
}

BOOL JITNotifications::FindItem(TADDR clrModule, mdToken token, UINT *indexOut)
{
    LIMITED_METHOD_CONTRACT;
    if (m_jitTable == NULL)
    {
        return FALSE;
    }

    if (indexOut == NULL)
    {
        return FALSE;
    }

    UINT Length = GetLength();
    for(UINT i=0; i < Length; i++)
    {
        JITNotification *pCurrent = m_jitTable + i;
        if (!pCurrent->IsFree() &&
            pCurrent->clrModule == clrModule &&
            pCurrent->methodToken == token)
        {
            *indexOut = i;
            return TRUE;
        }
    }

    return FALSE;
}

// if clrModule is NULL, all active notifications are changed to NType
BOOL JITNotifications::SetAllNotifications(TADDR clrModule,USHORT NType,BOOL *changedOut)
{
    if (m_jitTable == NULL)
    {
        return FALSE;
    }

    if (changedOut == NULL)
    {
        return FALSE;
    }

    *changedOut = FALSE;

    UINT Length = GetLength();
    for(UINT i=0; i < Length; i++)
    {
        JITNotification *pCurrent = m_jitTable + i;
        if (!pCurrent->IsFree() &&
            ((clrModule == NULL) || (pCurrent->clrModule == clrModule))&&
            pCurrent->state != NType)
        {
            pCurrent->state = NType;
            *changedOut = TRUE;
        }
    }

    if (*changedOut && NType == CLRDATA_METHNOTIFY_NONE)
    {
        // Need to recompute length if we removed notifications
        for (UINT iCurrent=Length; iCurrent > 0; iCurrent--)
        {
            JITNotification *pCurrent = m_jitTable + (iCurrent - 1);
            if (pCurrent->IsFree())
            {
                DecrementLength();
            }
        }
    }
    return TRUE;
}

BOOL JITNotifications::SetNotification(TADDR clrModule, mdToken token, USHORT NType)
{
    UINT iIndex;

    if (!IsActive())
    {
        return FALSE;
    }

    if (clrModule == NULL)
    {
        return FALSE;
    }

    if (NType == CLRDATA_METHNOTIFY_NONE)
    {
        // Remove an item if it exists
        if (FindItem(clrModule, token, &iIndex))
        {
            JITNotification *pItem = m_jitTable + iIndex;
            pItem->SetFree();
            _ASSERTE(iIndex < GetLength());
            // Update highest?
            if (iIndex == (GetLength()-1))
            {
                DecrementLength();
            }
        }
        return TRUE;
    }

    if (FindItem(clrModule, token, &iIndex))
    {
        JITNotification *pItem = m_jitTable + iIndex;
        _ASSERTE(pItem->IsFree() == FALSE);
        pItem->state =  NType;
        return TRUE;
    }

    // Find first free item
    UINT iFirstFree = GetLength();
    for (UINT i = 0; i < iFirstFree; i++)
    {
        JITNotification *pCurrent = m_jitTable + i;
        if (pCurrent->state == CLRDATA_METHNOTIFY_NONE)
        {
            iFirstFree = i;
            break;
        }
    }

    if (iFirstFree == GetLength() &&
        iFirstFree == GetTableSize())
    {
        // No more room
        return FALSE;
    }

    JITNotification *pCurrent = m_jitTable + iFirstFree;
    pCurrent->SetState(clrModule, token, NType);
    if (iFirstFree == GetLength())
    {
        IncrementLength();
    }

    return TRUE;
}

UINT JITNotifications::GetLength()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(IsActive());

    if (!IsActive())
    {
        return 0;
    }

    return (UINT) (m_jitTable - 1)->methodToken;
}

void JITNotifications::IncrementLength()
{
    _ASSERTE(IsActive());

    if (!IsActive())
    {
        return;
    }

    UINT *pShort = (UINT *) &((m_jitTable - 1)->methodToken);
    (*pShort)++;
}

void JITNotifications::DecrementLength()
{
    _ASSERTE(IsActive());

    if (!IsActive())
    {
        return;
    }

    UINT *pShort = (UINT *) &((m_jitTable - 1)->methodToken);
    (*pShort)--;
}

UINT JITNotifications::GetTableSize()
{
    _ASSERTE(IsActive());

    if (!IsActive())
    {
        return 0;
    }

    return ((UINT) (m_jitTable - 1)->clrModule);
}

USHORT JITNotifications::Requested(TADDR clrModule, mdToken token)
{
    LIMITED_METHOD_CONTRACT;
    UINT iIndex;
    if (FindItem(clrModule, token, &iIndex))
    {
        JITNotification *pItem = m_jitTable + iIndex;
        _ASSERTE(pItem->IsFree() == FALSE);
        return pItem->state;
    }

    return CLRDATA_METHNOTIFY_NONE;
}

#ifdef DACCESS_COMPILE

JITNotification *JITNotifications::InitializeNotificationTable(UINT TableSize)
{
    // We use the first entry in the table for recordkeeping info.

    JITNotification *retTable = new (nothrow) JITNotification[TableSize+1];
    if (retTable)
    {
        // Set the length
        UINT *pUint = (UINT *) &(retTable->methodToken);
        *pUint = 0;
        // Set the table size
        pUint = (UINT *) &(retTable->clrModule);
        *pUint = TableSize;
    }
    return retTable;
}

template <class NotificationClass>
BOOL UpdateOutOfProcTable(__GlobalPtr<NotificationClass*, DPTR(NotificationClass)> pHostTable, NotificationClass* copyFrom, UINT tableSize)
{

    ClrSafeInt<ULONG32> allocSize = S_SIZE_T(sizeof(NotificationClass)) * ClrSafeInt<UINT>(tableSize);
    if (allocSize.IsOverflow())
    {
        return FALSE;
    }

    if (dac_cast<TADDR>(pHostTable) == NULL)
    {
        // The table has not been initialized in the target.  Allocate space for it and update the pointer
        // in the target so that we'll use this allocated memory from now on.  Note that we never free this
        // memory, but this isn't a big deal because it's only a single allocation.
        TADDR Location;

        if (DacAllocVirtual(0, allocSize.Value(),
                                MEM_COMMIT, PAGE_READWRITE, false,
                                &Location) != S_OK)
        {
            return FALSE;
        }

        DPTR(DPTR(NotificationClass)) ppTable = &pHostTable;
        *ppTable = DPTR(NotificationClass)(Location);
        if (DacWriteHostInstance(ppTable,false) != S_OK)
        {
            return FALSE;
        }
    }

    // We store recordkeeping info right before the m_jitTable pointer, that must be written as well.
    if (DacWriteAll(dac_cast<TADDR>(pHostTable), copyFrom,
        allocSize.Value(), false) != S_OK)
    {
        return FALSE;
    }

    return TRUE;
}

BOOL JITNotifications::UpdateOutOfProcTable()
{
    return ::UpdateOutOfProcTable<JITNotification>(g_pNotificationTable, m_jitTable - 1, GetTableSize() + 1);
}
#endif // DACCESS_COMPILE

GPTR_IMPL(GcNotification, g_pGcNotificationTable);

GcNotifications::GcNotifications(GcNotification *gcTable)
{
    LIMITED_METHOD_CONTRACT;
    if (gcTable)
    {
        // Bookkeeping info is held in the first slot
        m_gcTable = gcTable + 1;
    }
    else
    {
        m_gcTable = NULL;
    }
}

BOOL GcNotifications::FindItem(GcEvtArgs ev_, UINT *indexOut)
{
    LIMITED_METHOD_CONTRACT;
    if (m_gcTable == NULL)
    {
        return FALSE;
    }

    if (indexOut == NULL)
    {
        return FALSE;
    }

    UINT length = Length();
    for (UINT i = 0; i < length; i++)
    {
        if (m_gcTable[i].IsMatch(ev_))
        {
            *indexOut = i;
            return TRUE;
        }
    }

    return FALSE;
}


BOOL GcNotifications::SetNotification(GcEvtArgs ev)
{
    if (!IsActive())
    {
        return FALSE;
    }

    if (ev.typ < 0 || ev.typ >= GC_EVENT_TYPE_MAX)
    {
        return FALSE;
    }

    // build the "match" event
    GcEvtArgs evStar = { ev.typ };
    switch (ev.typ)
    {
        case GC_MARK_END:
            // specify mark event matching all generations
            evStar.condemnedGeneration = -1;
            break;
        default:
            break;
    }

    // look for the entry that matches the evStar argument
    UINT idx;
    if (!FindItem(evStar, &idx))
    {
        // Find first free item
        UINT iFirstFree = Length();
        for (UINT i = 0; i < iFirstFree; i++)
        {
            GcNotification *pCurrent = m_gcTable + i;
            if (pCurrent->IsFree())
            {
                iFirstFree = i;
                break;
            }
        }

        if (iFirstFree == Length() &&
            iFirstFree == GetTableSize())
    {
            // No more room
        return FALSE;
    }

        // guarantee the free cell is zeroed out
        m_gcTable[iFirstFree].SetFree();
        idx = iFirstFree;
    }

    // Now update the state
    m_gcTable[idx].ev.typ = ev.typ;
    switch (ev.typ)
    {
        case GC_MARK_END:
            if (ev.condemnedGeneration == 0)
            {
                m_gcTable[idx].SetFree();
            }
            else
            {
                m_gcTable[idx].ev.condemnedGeneration |= ev.condemnedGeneration;
            }
            break;
        default:
            break;
    }

    // and if needed, update the array's length
    if (idx == Length())
    {
        IncrementLength();
    }

    return TRUE;
}

GARY_IMPL(size_t, g_clrNotificationArguments, MAX_CLR_NOTIFICATION_ARGS);

#ifdef DACCESS_COMPILE

GcNotification *GcNotifications::InitializeNotificationTable(UINT TableSize)
{
    // We use the first entry in the table for recordkeeping info.

    GcNotification *retTable = new (nothrow) GcNotification[TableSize+1];
    if (retTable)
    {
        // Set the length
        UINT *pUint = (UINT *) &(retTable[0].ev.typ);
        *pUint = 0;
        // Set the table size
        ++pUint;
        *pUint = TableSize;
    }
    return retTable;
}

BOOL GcNotifications::UpdateOutOfProcTable()
{
    return ::UpdateOutOfProcTable<GcNotification>(g_pGcNotificationTable, m_gcTable - 1, GetTableSize() + 1);
}

#else // DACCESS_COMPILE

static CrstStatic g_clrNotificationCrst;

void DACRaiseException(TADDR *args, UINT argCount)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

    struct Param
    {
        TADDR *args;
        UINT argCount;
    } param;
    param.args = args;
    param.argCount = argCount;

    PAL_TRY(Param *, pParam, &param)
    {
        RaiseException(CLRDATA_NOTIFY_EXCEPTION, 0, pParam->argCount, (ULONG_PTR *)pParam->args);
    }
    PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
    {
    }
    PAL_ENDTRY
}

void DACNotifyExceptionHelper(TADDR *args, UINT argCount)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    _ASSERTE(argCount <= MAX_CLR_NOTIFICATION_ARGS);

    if (IsDebuggerPresent() && !CORDebuggerAttached())
    {
        CrstHolder lh(&g_clrNotificationCrst);

        for (UINT i = 0; i < argCount; i++)
        {
            g_clrNotificationArguments[i] = args[i];
        }

        DACRaiseException(args, argCount);

        g_clrNotificationArguments[0] = NULL;
    }
}

void InitializeClrNotifications()
{
    g_clrNotificationCrst.Init(CrstClrNotification, CRST_UNSAFE_ANYMODE);
    g_clrNotificationArguments[0] = NULL;
}

// <TODO> FIX IN BETA 2
//
// g_dacNotificationFlags is only modified by the DAC and therefore the
// optmizer can assume that it will always be its default value and has
// been seen to eliminate the code in DoModuleLoadNotification,
// etc... such that DAC notifications are no longer sent.
//
// TODO: fix this in Beta 2
// the RIGHT fix is to make g_dacNotificationFlags volatile, but currently
// we don't have DAC macros to do that. Additionally, there are a number
// of other places we should look at DAC definitions to determine if they
// should be also declared volatile.
//
// for now we just turn off optimization for these guys
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4748)
#pragma optimize("", off)
#endif  // _MSC_VER

#if defined(FEATURE_GDBJIT)
#include "gdbjit.h"
#endif // FEATURE_GDBJIT

// called from the runtime
void DACNotify::DoJITNotification(MethodDesc *MethodDescPtr, TADDR NativeCodeLocation)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    TADDR Args[3] = { JIT_NOTIFICATION2, (TADDR) MethodDescPtr, NativeCodeLocation };
    DACNotifyExceptionHelper(Args, 3);
}

void DACNotify::DoJITPitchingNotification(MethodDesc *MethodDescPtr)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

#if defined(FEATURE_GDBJIT) && defined(TARGET_UNIX) && !defined(CROSSGEN_COMPILE)
    NotifyGdb::MethodPitched(MethodDescPtr);
#endif
    TADDR Args[2] = { JIT_PITCHING_NOTIFICATION, (TADDR) MethodDescPtr };
    DACNotifyExceptionHelper(Args, 2);
}

void DACNotify::DoModuleLoadNotification(Module *ModulePtr)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_MODULE_LOAD) != 0)
    {
        TADDR Args[2] = { MODULE_LOAD_NOTIFICATION, (TADDR) ModulePtr};
        DACNotifyExceptionHelper(Args, 2);
    }
}

void DACNotify::DoModuleUnloadNotification(Module *ModulePtr)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_MODULE_UNLOAD) != 0)
    {
        TADDR Args[2] = { MODULE_UNLOAD_NOTIFICATION, (TADDR) ModulePtr};
        DACNotifyExceptionHelper(Args, 2);
    }
}

void DACNotify::DoExceptionNotification(Thread* ThreadPtr)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_PREEMPTIVE;
    }
    CONTRACTL_END;

    if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_EXCEPTION) != 0)
    {
        TADDR Args[2] = { EXCEPTION_NOTIFICATION, (TADDR) ThreadPtr};
        DACNotifyExceptionHelper(Args, 2);
    }
}

void DACNotify::DoGCNotification(const GcEvtArgs& args)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    if (args.typ == GC_MARK_END)
    {
        TADDR Args[3] = { GC_NOTIFICATION, (TADDR) args.typ, (TADDR) args.condemnedGeneration };
        DACNotifyExceptionHelper(Args, 3);
    }
}

void DACNotify::DoExceptionCatcherEnterNotification(MethodDesc *MethodDescPtr, DWORD nativeOffset)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    if ((g_dacNotificationFlags & CLRDATA_NOTIFY_ON_EXCEPTION_CATCH_ENTER) != 0)
    {
        TADDR Args[3] = { CATCH_ENTER_NOTIFICATION, (TADDR) MethodDescPtr, (TADDR)nativeOffset };
        DACNotifyExceptionHelper(Args, 3);
    }
}

#ifdef _MSC_VER
#pragma optimize("", on)
#pragma warning(pop)
#endif  // _MSC_VER
// </TODO>

#endif // DACCESS_COMPILE

// called from the DAC
int DACNotify::GetType(TADDR Args[])
{
    // Type is an enum, and will thus fit into an int.
    return static_cast<int>(Args[0]);
}

BOOL DACNotify::ParseJITNotification(TADDR Args[], TADDR& MethodDescPtr, TADDR& NativeCodeLocation)
{
    _ASSERTE(Args[0] == JIT_NOTIFICATION2);
    if (Args[0] != JIT_NOTIFICATION2)
    {
        return FALSE;
    }

    MethodDescPtr = Args[1];
    NativeCodeLocation = Args[2];

    return TRUE;
}

BOOL DACNotify::ParseJITPitchingNotification(TADDR Args[], TADDR& MethodDescPtr)
{
    _ASSERTE(Args[0] == JIT_PITCHING_NOTIFICATION);
    if (Args[0] != JIT_PITCHING_NOTIFICATION)
    {
        return FALSE;
    }

    MethodDescPtr = Args[1];

    return TRUE;
}

BOOL DACNotify::ParseModuleLoadNotification(TADDR Args[], TADDR& Module)
{
    _ASSERTE(Args[0] == MODULE_LOAD_NOTIFICATION);
    if (Args[0] != MODULE_LOAD_NOTIFICATION)
    {
        return FALSE;
    }

    Module = Args[1];

    return TRUE;
}

BOOL DACNotify::ParseModuleUnloadNotification(TADDR Args[], TADDR& Module)
{
    _ASSERTE(Args[0] == MODULE_UNLOAD_NOTIFICATION);
    if (Args[0] != MODULE_UNLOAD_NOTIFICATION)
    {
        return FALSE;
    }

    Module = Args[1];

    return TRUE;
}

BOOL DACNotify::ParseExceptionNotification(TADDR Args[], TADDR& ThreadPtr)
{
    _ASSERTE(Args[0] == EXCEPTION_NOTIFICATION);
    if (Args[0] != EXCEPTION_NOTIFICATION)
    {
        return FALSE;
    }

    ThreadPtr = Args[1];

    return TRUE;
}


BOOL DACNotify::ParseGCNotification(TADDR Args[], GcEvtArgs& args)
{
    _ASSERTE(Args[0] == GC_NOTIFICATION);
    if (Args[0] != GC_NOTIFICATION)
    {
        return FALSE;
    }

    BOOL bRet = FALSE;

    args.typ = (GcEvt_t) Args[1];
    switch (args.typ)
    {
        case GC_MARK_END:
        {
            // The condemnedGeneration is an int.
            args.condemnedGeneration = static_cast<int>(Args[2]);
            bRet = TRUE;
            break;
        }
        default:
            bRet = FALSE;
            break;
    }

    return bRet;
}

BOOL DACNotify::ParseExceptionCatcherEnterNotification(TADDR Args[], TADDR& MethodDescPtr, DWORD& nativeOffset)
{
    _ASSERTE(Args[0] == CATCH_ENTER_NOTIFICATION);
    if (Args[0] != CATCH_ENTER_NOTIFICATION)
    {
        return FALSE;
    }

    MethodDescPtr = Args[1];
    nativeOffset = (DWORD) Args[2];
    return TRUE;
}

static BOOL TrustMeIAmSafe(void *pLock)
{
    LIMITED_METHOD_CONTRACT;
    return TRUE;
}

LockOwner g_lockTrustMeIAmThreadSafe = { NULL, TrustMeIAmSafe };

static DangerousNonHostedSpinLock g_randomLock;
static CLRRandom g_random;

int GetRandomInt(int maxVal)
{
#ifndef CROSSGEN_COMPILE
    // Use the thread-local Random instance if possible
    Thread* pThread = GetThreadNULLOk();
    if (pThread)
        return pThread->GetRandom()->Next(maxVal);
#endif

    // No Thread object - need to fall back to the global generator.
    // In DAC builds we don't need the lock (DAC is single-threaded) and can't get it anyway (DNHSL isn't supported)
#ifndef DACCESS_COMPILE
    DangerousNonHostedSpinLockHolder lh(&g_randomLock);
#endif
    if (!g_random.IsInitialized())
        g_random.Init();
    return g_random.Next(maxVal);
}

// These wrap the SString:L:CompareCaseInsenstive function in a way that makes it
// easy to fix code that uses _stricmp. _stricmp should be avoided as it uses the current
// C-runtime locale rather than the invariance culture.
//
// Note that unlike the real _stricmp, these functions unavoidably have a throws/gc_triggers/inject_fault
// contract. So if need a case-insensitive comparison in a place where you can't tolerate this contract,
// you've got a problem.
int __cdecl stricmpUTF8(const char* szStr1, const char* szStr2)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END

    SString sStr1 (SString::Utf8, szStr1);
    SString sStr2 (SString::Utf8, szStr2);
    return sStr1.CompareCaseInsensitive(sStr2);

}

#ifndef DACCESS_COMPILE
//
//
// COMCharacter and Helper functions
//
//

#ifndef TARGET_UNIX
/*============================GetCharacterInfoHelper============================
**Determines character type info (digit, whitespace, etc) for the given char.
**Args:   c is the character on which to operate.
**        CharInfoType is one of CT_CTYPE1, CT_CTYPE2, CT_CTYPE3 and specifies the type
**        of information being requested.
**Returns: The bitmask returned by GetStringTypeEx.  The caller needs to know
**         how to interpret this.
**Exceptions: ArgumentException if GetStringTypeEx fails.
==============================================================================*/
INT32 GetCharacterInfoHelper(WCHAR c, INT32 CharInfoType)
{
    WRAPPER_NO_CONTRACT;

    unsigned short result=0;
    if (!GetStringTypeEx(LOCALE_USER_DEFAULT, CharInfoType, &(c), 1, &result)) {
        _ASSERTE(!"This should not happen, verify the arguments passed to GetStringTypeEx()");
    }
    return(INT32)result;
}
#endif // !TARGET_UNIX

/*==============================nativeIsWhiteSpace==============================
**The locally available version of IsWhiteSpace.  Designed to be called by other
**native methods.  The work is mostly done by GetCharacterInfoHelper
**Args:  c -- the character to check.
**Returns: true if c is whitespace, false otherwise.
**Exceptions:  Only those thrown by GetCharacterInfoHelper.
==============================================================================*/
BOOL COMCharacter::nativeIsWhiteSpace(WCHAR c)
{
    WRAPPER_NO_CONTRACT;

#ifndef TARGET_UNIX
    if (c <= (WCHAR) 0x7F) // common case
    {
        BOOL result = (c == ' ') || (c == '\r') || (c == '\n') || (c == '\t') || (c == '\f') || (c == (WCHAR) 0x0B);

        ASSERT(result == ((GetCharacterInfoHelper(c, CT_CTYPE1) & C1_SPACE)!=0));

        return result;
    }

    // GetCharacterInfoHelper costs around 160 instructions
    return((GetCharacterInfoHelper(c, CT_CTYPE1) & C1_SPACE)!=0);
#else // !TARGET_UNIX
    return iswspace(c);
#endif // !TARGET_UNIX
}

/*================================nativeIsDigit=================================
**The locally available version of IsDigit.  Designed to be called by other
**native methods.  The work is mostly done by GetCharacterInfoHelper
**Args:  c -- the character to check.
**Returns: true if c is whitespace, false otherwise.
**Exceptions:  Only those thrown by GetCharacterInfoHelper.
==============================================================================*/
BOOL COMCharacter::nativeIsDigit(WCHAR c)
{
    WRAPPER_NO_CONTRACT;
#ifndef TARGET_UNIX
    return((GetCharacterInfoHelper(c, CT_CTYPE1) & C1_DIGIT)!=0);
#else // !TARGET_UNIX
    return iswdigit(c);
#endif // !TARGET_UNIX
}

BOOL RuntimeFileNotFound(HRESULT hr)
{
    LIMITED_METHOD_CONTRACT;
    return Assembly::FileNotFound(hr);
}

#ifndef TARGET_UNIX
HRESULT GetFileVersion(                     // S_OK or error
    LPCWSTR wszFilePath,                    // Path to the executable.
    ULARGE_INTEGER* pFileVersion)           // Put file version here.
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    //
    // Note that this code is equivalent to FusionGetFileVersionInfo, found in fusion\asmcache\asmcache.cpp
    //

    // Avoid confusion.
    pFileVersion->QuadPart = 0;

    DWORD ret;

    DWORD dwHandle = 0;
    DWORD bufSize = GetFileVersionInfoSizeW(wszFilePath, &dwHandle);
    if (!bufSize)
    {
        return HRESULT_FROM_GetLastErrorNA();
    }

    // Allocate the buffer for the version info structure
    // _alloca() can't return NULL -- raises STATUS_STACK_OVERFLOW.
    BYTE* pVersionInfoBuffer = reinterpret_cast< BYTE* >(_alloca(bufSize));

    ret = GetFileVersionInfoW(wszFilePath, dwHandle, bufSize, pVersionInfoBuffer);
    if (!ret)
    {
        return HRESULT_FROM_GetLastErrorNA();
    }

    // Extract the actual File Version number that we care about.
    UINT versionInfoSize = 0;
    VS_FIXEDFILEINFO* pVSFileInfo;
    ret = VerQueryValueW(pVersionInfoBuffer, W("\\"),
                            reinterpret_cast< void **>(&pVSFileInfo), &versionInfoSize);
    if (!ret || versionInfoSize == 0)
    {
        return HRESULT_FROM_GetLastErrorNA();
    }

    pFileVersion->HighPart = pVSFileInfo->dwFileVersionMS;
    pFileVersion->LowPart = pVSFileInfo->dwFileVersionLS;

    return S_OK;
}
#endif // !TARGET_UNIX

#endif // !DACCESS_COMPILE