summaryrefslogtreecommitdiff
path: root/src/vm/clrex.cpp
blob: 299b0723518825dcf254f8dcbaf5ab558b6b8982 (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
// 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.
//

//
// ---------------------------------------------------------------------------
// Clrex.cpp
// ---------------------------------------------------------------------------


#include "common.h"
#include "clrex.h"
#include "field.h"
#include "eetoprofinterfacewrapper.inl"
#include "typestring.h"
#include "sigformat.h"
#include "eeconfig.h"
#include "frameworkexceptionloader.h"

#ifdef WIN64EXCEPTIONS
#include "exceptionhandling.h"
#endif // WIN64EXCEPTIONS

#ifdef FEATURE_COMINTEROP
#include "interoputil.inl"
#endif // FEATURE_COMINTEROP

// ---------------------------------------------------------------------------
// CLRException methods
// ---------------------------------------------------------------------------

CLRException::~CLRException()
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_ANY;
        if (GetThrowableHandle() == NULL)
        {
            CANNOT_TAKE_LOCK;
        }
        else
        {
            CAN_TAKE_LOCK;         // because of DestroyHandle
        }
    }
    CONTRACTL_END;
    
#ifndef CROSSGEN_COMPILE
    OBJECTHANDLE throwableHandle = GetThrowableHandle();
    if (throwableHandle != NULL)
    {
        STRESS_LOG1(LF_EH, LL_INFO100, "CLRException::~CLRException destroying throwable: obj = %x\n", GetThrowableHandle());
        // clear the handle first, so if we SO on destroying it, we don't have a dangling reference
        SetThrowableHandle(NULL);
        DestroyHandle(throwableHandle);
    }
#endif
}

OBJECTREF CLRException::GetThrowable()
{
    CONTRACTL
    {
        GC_TRIGGERS;
        NOTHROW;
        MODE_COOPERATIVE;
        FORBID_FAULT;
    }
    CONTRACTL_END;

#ifdef CROSSGEN_COMPILE
    _ASSERTE(false);
    return NULL;
#else
    OBJECTREF throwable = NULL;

    if (NingenEnabled())
    {
        return NULL;
    }

    Thread *pThread = GetThread();

    if (pThread->IsRudeAbortInitiated()) {
        return GetPreallocatedRudeThreadAbortException();
    }

    if ((IsType(CLRLastThrownObjectException::GetType()) && 
         pThread->LastThrownObject() == GetPreallocatedStackOverflowException()))
    {
        return GetPreallocatedStackOverflowException();
    }

    OBJECTHANDLE oh = GetThrowableHandle();
    if (oh != NULL)
    {
        return ObjectFromHandle(oh);
    }
   
    Exception *pLastException = pThread->m_pCreatingThrowableForException;
    if (pLastException != NULL)
    {
        if (IsSameInstanceType(pLastException))
        {
#if defined(_DEBUG)
            static int BreakOnExceptionInGetThrowable = -1;
            if (BreakOnExceptionInGetThrowable == -1)
            {
                BreakOnExceptionInGetThrowable = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_BreakOnExceptionInGetThrowable);
            }
            if (BreakOnExceptionInGetThrowable)
            {
                _ASSERTE(!"BreakOnExceptionInGetThrowable");
            }
            LOG((LF_EH, LL_INFO100, "GetThrowable: Exception in GetThrowable, translating to a preallocated exception.\n"));
#endif // _DEBUG
            // Look at the type of GET_EXCEPTION() and see if it is OOM or SO.
            if (IsPreallocatedOOMException())
            {
                throwable = GetPreallocatedOutOfMemoryException();
            }
            else if (GetInstanceType() == EEException::GetType() && GetHR() == COR_E_THREADABORTED)
            {
                // If creating a normal ThreadAbortException fails, due to OOM or StackOverflow,
                // use a pre-created one.
                // We do not won't to change a ThreadAbortException into OOM or StackOverflow, because
                // it will cause recursive call when escalation policy is on: 
                // Creating ThreadAbortException fails, we throw OOM.  Escalation leads to ThreadAbort.
                // The cycle repeats.
                throwable = GetPreallocatedThreadAbortException();
            }
            else
            {
                // I am not convinced if this case is actually a fatal error in the runtime.
                // There have been two bugs in early 2006 (VSW 575647 and 575650) that came in here,
                // both because of OOM and resulted in the ThreadAbort clause above being added since
                // we were creating a ThreadAbort throwable that, due to OOM, got us on a path
                // which came here. Both were valid execution paths and scenarios and not a fatal condition.
                // 
                // I am tempted to return preallocated OOM from here but my concern is that it *may*
                // result in fake OOM exceptions being thrown that could break valid scenarios.
                //
                // Hence, we return preallocated System.Exception instance. Lossy information is better
                // than wrong or no information (or even FailFast).
                _ASSERTE (!"Recursion in CLRException::GetThrowable");
                
                // We didn't recognize it, so use the preallocated System.Exception instance.
                STRESS_LOG0(LF_EH, LL_INFO100, "CLRException::GetThrowable: Recursion! Translating to preallocated System.Exception.\n");
                throwable = GetPreallocatedBaseException();
            }
        }
    }

    GCPROTECT_BEGIN(throwable);

    if (throwable == NULL)
    {
        class RestoreLastException
        {
            Thread *m_pThread;
            Exception *m_pLastException;
        public:
            RestoreLastException(Thread *pThread, Exception *pException)
            {
                m_pThread = pThread;
                m_pLastException = m_pThread->m_pCreatingThrowableForException;
                m_pThread->m_pCreatingThrowableForException = pException;
            }
            ~RestoreLastException()
            {
                m_pThread->m_pCreatingThrowableForException = m_pLastException;
            }
        };
        
        RestoreLastException restore(pThread, this);

        EX_TRY
        {
            FAULT_NOT_FATAL();
            throwable = CreateThrowable();
        }
        EX_CATCH
        {
            // This code used to be this line:
            //      throwable = GET_THROWABLE();
            // GET_THROWABLE() expands to CLRException::GetThrowable(GET_EXCEPTION()),
            //  (where GET_EXCEPTION() refers to the exception that was thrown from
            //  CreateThrowable() and is being caught in this EX_TRY/EX_CATCH.)
            //  If that exception is the same as the one for which this GetThrowable() 
            //  was called, we're in a recursive situation.
            // Since the CreateThrowable() call should return a type from mscorlib,
            //  there really shouldn't be much opportunity for error.  We could be
            //  out of memory, we could overflow the stack, or the runtime could
            //  be in a weird state(the thread could be aborted as well).
            // Because we've seen a number of recursive death bugs here, just look
            //  explicitly for OOM and SO, and otherwise use ExecutionEngineException.

            // Check whether the exception from CreateThrowable() is the same as the current
            //  exception.  If not, call GetThrowable(), otherwise, settle for a
            //  preallocated exception.
            Exception *pException = GET_EXCEPTION();

            if (GetHR() == COR_E_THREADABORTED)
            {
                // If creating a normal ThreadAbortException fails, due to OOM or StackOverflow,
                // use a pre-created one.
                // We do not won't to change a ThreadAbortException into OOM or StackOverflow, because
                // it will cause recursive call when escalation policy is on: 
                // Creating ThreadAbortException fails, we throw OOM.  Escalation leads to ThreadAbort.
                // The cycle repeats.
                throwable = GetPreallocatedThreadAbortException();
            }
            else
            {
                throwable = CLRException::GetThrowableFromException(pException);
            }
        }
        EX_END_CATCH(SwallowAllExceptions)
        
    }
    
    {
        if (throwable == NULL)
        {
            STRESS_LOG0(LF_EH, LL_INFO100, "CLRException::GetThrowable: We have failed to track exceptions accurately through the system.\n");

            // There's no reason to believe that it is an OOM.  A better choice is ExecutionEngineException.
            // We have failed to track exceptions accurately through the system.  However, it's arguably
            // better to give the wrong exception object than it is to rip the process.  So let's leave
            // it as an Assert for now and convert it to ExecutionEngineException in the next release.

            // SQL Stress is hitting the assert.  We want to remove it, so that we can see if there are further errors
            //  masked by the assert.
            // _ASSERTE(FALSE);

            throwable = GetPreallocatedOutOfMemoryException();
        }

        EX_TRY
        {
            SetThrowableHandle(GetAppDomain()->CreateHandle(throwable));
            if (m_innerException != NULL && !CLRException::IsPreallocatedExceptionObject(throwable))
            {
                // Only set inner exception if the exception is not preallocated.
                FAULT_NOT_FATAL();

                // If inner exception is not empty, then set the managed exception's 
                // _innerException field properly
                OBJECTREF throwableValue = CLRException::GetThrowableFromException(m_innerException);
                ((EXCEPTIONREF)throwable)->SetInnerException(throwableValue);
            }

        }
        EX_CATCH
        {
            // No matter... we just don't get to cache the throwable.
        }
        EX_END_CATCH(SwallowAllExceptions)
    }

    GCPROTECT_END();

    return throwable;
#endif
}

HRESULT CLRException::GetHR()
{
    CONTRACTL
    {
        DISABLED(NOTHROW);
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    GCX_COOP();
    return GetExceptionHResult(GetThrowable());
}

#ifdef FEATURE_COMINTEROP
HRESULT CLRException::SetErrorInfo()
{
   CONTRACTL
    {
        GC_TRIGGERS;
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;

    HRESULT hr = S_OK;

    IErrorInfo *pErrorInfo = NULL;

    // Try to get IErrorInfo
    EX_TRY
    {
        pErrorInfo = GetErrorInfo();
    }
    EX_CATCH
    {
        // Since there was an exception getting IErrorInfo get the exception's HR so 
        // that we return it back to the caller as the new exception.
        hr = GET_EXCEPTION()->GetHR();
        pErrorInfo = NULL;
        LOG((LF_EH, LL_INFO100, "CLRException::SetErrorInfo: caught exception (hr = %08X) while trying to get IErrorInfo\n", hr));
    }
    EX_END_CATCH(SwallowAllExceptions)

    if (!pErrorInfo)
    {
        // Return the HR to the caller if we dont get IErrorInfo - if the HR is E_NOINTERFACE, then 
        // there was no IErrorInfo available. If its anything else, it implies we failed to get the 
        // interface and have the HR corresponding to the exception we took while trying to get IErrorInfo.
        return hr;
    }
    else
    {
        GCX_PREEMP();

        EX_TRY
        {
            ::SetErrorInfo(0, pErrorInfo);
            pErrorInfo->Release();

            // Success in setting the ErrorInfo on the thread
            hr = S_OK;
        }
        EX_CATCH
        {
            hr = GET_EXCEPTION()->GetHR();
            // Log the failure
            LOG((LF_EH, LL_INFO100, "CLRException::SetErrorInfo: caught exception (hr = %08X) while trying to set IErrorInfo\n", hr));
        }
        EX_END_CATCH(SwallowAllExceptions)
    }

    return hr;
}

IErrorInfo *CLRException::GetErrorInfo()
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    IErrorInfo *pErrorInfo = NULL;

#ifndef CROSSGEN_COMPILE
    // Attempt to get IErrorInfo only if COM is initialized.
    // Not all codepaths expect to have it initialized (e.g. hosting APIs).
    if (g_fComStarted)
    {
        // Get errorinfo only when our SO probe succeeds
        {
            // Switch to coop mode since GetComIPFromObjectRef requires that
            // and we could be here in any mode...
            GCX_COOP();

            OBJECTREF e = NULL;
            GCPROTECT_BEGIN(e);

            e = GetThrowable();
        
            if (e != NULL)
            {
                pErrorInfo = (IErrorInfo *)GetComIPFromObjectRef(&e, IID_IErrorInfo);
            }

            GCPROTECT_END();
        }
    }
    else
    {
        // Write to the log incase COM isnt initialized.
        LOG((LF_EH, LL_INFO100, "CLRException::GetErrorInfo: exiting since COM is not initialized.\n"));
    }
#endif //CROSSGEN_COMPILE

    // return the IErrorInfo we got...
    return pErrorInfo;
}
#else   // FEATURE_COMINTEROP
IErrorInfo *CLRException::GetErrorInfo()
{
    LIMITED_METHOD_CONTRACT;
    return NULL;
}
HRESULT CLRException::SetErrorInfo()
{
    LIMITED_METHOD_CONTRACT;

    return S_OK;
 }
#endif  // FEATURE_COMINTEROP

void CLRException::GetMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
#ifndef CROSSGEN_COMPILE
    GCX_COOP();

    OBJECTREF e = GetThrowable();
    if (e != NULL)
    {
        _ASSERTE(IsException(e->GetMethodTable()));

        GCPROTECT_BEGIN (e);

        STRINGREF message = ((EXCEPTIONREF)e)->GetMessage();

        if (!message)
            result.Clear();
        else
            message->GetSString(result);

        GCPROTECT_END ();
    }
#endif
}

#ifndef CROSSGEN_COMPILE
OBJECTREF CLRException::GetPreallocatedBaseException()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(g_pPreallocatedBaseException != NULL);
    return ObjectFromHandle(g_pPreallocatedBaseException);
}

OBJECTREF CLRException::GetPreallocatedOutOfMemoryException()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(g_pPreallocatedOutOfMemoryException != NULL);
    return ObjectFromHandle(g_pPreallocatedOutOfMemoryException);
}

OBJECTREF CLRException::GetPreallocatedStackOverflowException()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(g_pPreallocatedStackOverflowException != NULL);
    return ObjectFromHandle(g_pPreallocatedStackOverflowException);
}

OBJECTREF CLRException::GetPreallocatedExecutionEngineException()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(g_pPreallocatedExecutionEngineException != NULL);
    return ObjectFromHandle(g_pPreallocatedExecutionEngineException);
}

OBJECTREF CLRException::GetPreallocatedRudeThreadAbortException()
{
    WRAPPER_NO_CONTRACT;
    // When we are hosted, we pre-create this exception.
    // This function should be called only if the exception has been created.
    _ASSERTE(g_pPreallocatedRudeThreadAbortException);
    return ObjectFromHandle(g_pPreallocatedRudeThreadAbortException);
}

OBJECTREF CLRException::GetPreallocatedThreadAbortException()
{
    WRAPPER_NO_CONTRACT;
    _ASSERTE(g_pPreallocatedThreadAbortException);
    return ObjectFromHandle(g_pPreallocatedThreadAbortException);
}

OBJECTHANDLE CLRException::GetPreallocatedOutOfMemoryExceptionHandle()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(g_pPreallocatedOutOfMemoryException != NULL);
    return g_pPreallocatedOutOfMemoryException;
}

OBJECTHANDLE CLRException::GetPreallocatedThreadAbortExceptionHandle()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(g_pPreallocatedThreadAbortException != NULL);
    return g_pPreallocatedThreadAbortException;
}

OBJECTHANDLE CLRException::GetPreallocatedRudeThreadAbortExceptionHandle()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(g_pPreallocatedRudeThreadAbortException != NULL);
    return g_pPreallocatedRudeThreadAbortException;
}

OBJECTHANDLE CLRException::GetPreallocatedStackOverflowExceptionHandle()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(g_pPreallocatedStackOverflowException != NULL);
    return g_pPreallocatedStackOverflowException;
}

OBJECTHANDLE CLRException::GetPreallocatedExecutionEngineExceptionHandle()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(g_pPreallocatedExecutionEngineException != NULL);
    return g_pPreallocatedExecutionEngineException;
}

//
// Returns TRUE if the given object ref is one of the preallocated exception objects.
//
BOOL CLRException::IsPreallocatedExceptionObject(OBJECTREF o)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    if ((o == ObjectFromHandle(g_pPreallocatedBaseException)) ||
        (o == ObjectFromHandle(g_pPreallocatedOutOfMemoryException)) ||
        (o == ObjectFromHandle(g_pPreallocatedStackOverflowException)) ||
        (o == ObjectFromHandle(g_pPreallocatedExecutionEngineException)))
    {
        return TRUE;
    }

    // The preallocated rude thread abort exception is not always preallocated.
    if ((g_pPreallocatedRudeThreadAbortException != NULL) &&
        (o == ObjectFromHandle(g_pPreallocatedRudeThreadAbortException)))
    {
        return TRUE;
    }

    // The preallocated rude thread abort exception is not always preallocated.
    if ((g_pPreallocatedThreadAbortException != NULL) &&
        (o == ObjectFromHandle(g_pPreallocatedThreadAbortException)))
    {
        return TRUE;
    }

    return FALSE;
}

//
// Returns TRUE if the given object ref is one of the preallocated exception handles
//
BOOL CLRException::IsPreallocatedExceptionHandle(OBJECTHANDLE h)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        FORBID_FAULT;
    }
    CONTRACTL_END;

    if ((h == g_pPreallocatedBaseException) ||
        (h == g_pPreallocatedOutOfMemoryException) ||
        (h == g_pPreallocatedStackOverflowException) ||
        (h == g_pPreallocatedExecutionEngineException) ||
        (h == g_pPreallocatedThreadAbortException))
    {
        return TRUE;
    }

    // The preallocated rude thread abort exception is not always preallocated.
    if ((g_pPreallocatedRudeThreadAbortException != NULL) &&
        (h == g_pPreallocatedRudeThreadAbortException))
    {
        return TRUE;
    }

    return FALSE;
}

//
// Returns a preallocated handle to match a preallocated exception object, or NULL if the object isn't one of the
// preallocated exception objects.
//
OBJECTHANDLE CLRException::GetPreallocatedHandleForObject(OBJECTREF o)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
        FORBID_FAULT;
    }
    CONTRACTL_END;
    
    if (o == ObjectFromHandle(g_pPreallocatedBaseException))
    {
        return g_pPreallocatedBaseException;    		
    }
    else if (o == ObjectFromHandle(g_pPreallocatedOutOfMemoryException))
    {
        return g_pPreallocatedOutOfMemoryException;
    }
    else if (o == ObjectFromHandle(g_pPreallocatedStackOverflowException))
    {
        return g_pPreallocatedStackOverflowException;
    }
    else if (o == ObjectFromHandle(g_pPreallocatedExecutionEngineException))
    {
        return g_pPreallocatedExecutionEngineException;
    }
    else if (o == ObjectFromHandle(g_pPreallocatedThreadAbortException))
    {
        return g_pPreallocatedThreadAbortException;
    }

    // The preallocated rude thread abort exception is not always preallocated.
    if ((g_pPreallocatedRudeThreadAbortException != NULL) &&
        (o == ObjectFromHandle(g_pPreallocatedRudeThreadAbortException)))
    {
        return g_pPreallocatedRudeThreadAbortException;
    }

    return NULL;
}

// Prefer a new OOM exception if we can make one.  If we cannot, then give back the pre-allocated one.
OBJECTREF CLRException::GetBestOutOfMemoryException()
{
    CONTRACTL
    {
        NOTHROW;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    OBJECTREF retVal = NULL;

    EX_TRY
    {
        FAULT_NOT_FATAL();

        EXCEPTIONREF pOutOfMemory = (EXCEPTIONREF)AllocateObject(g_pOutOfMemoryExceptionClass);
        pOutOfMemory->SetHResult(COR_E_OUTOFMEMORY);
        pOutOfMemory->SetXCode(EXCEPTION_COMPLUS);

        retVal = pOutOfMemory;
    }
    EX_CATCH
    {
        retVal = GetPreallocatedOutOfMemoryException();
    }
    EX_END_CATCH(SwallowAllExceptions)

    _ASSERTE(retVal != NULL);

    return retVal;
}


// Works on non-CLRExceptions as well
// static function
OBJECTREF CLRException::GetThrowableFromException(Exception *pException)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        NOTHROW;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    Thread* pThread = GetThread();

    // Can't have a throwable without a Thread.
    _ASSERTE(pThread != NULL);

    if (NULL == pException)
    {
        return pThread->LastThrownObject();
    }

    if (pException->IsType(CLRException::GetType()))
        return ((CLRException*)pException)->GetThrowable();

    if (pException->IsType(EEException::GetType()))
        return ((EEException*)pException)->GetThrowable();

    // Note: we are creating a throwable on the fly in this case - so 
    // multiple calls will return different objects.  If we really need identity,
    // we could store a throwable handle at the catch site, or store it
    // on the thread object.

    if (pException->IsType(SEHException::GetType()))
    {
        SEHException *pSEHException = (SEHException*)pException;

        switch (pSEHException->m_exception.ExceptionCode)
        {
        case EXCEPTION_COMPLUS:
            // Note: even though the switch compared the exception code,
            // we have to call the official IsComPlusException() routine
            // for side-by-side correctness. If that check fails, treat
            // as an unrelated unmanaged exception.
            if (IsComPlusException(&(pSEHException->m_exception)))
            {
                return pThread->LastThrownObject();
            }
            else
            {
                break;
            }

        case STATUS_NO_MEMORY:
            return GetBestOutOfMemoryException();

        case STATUS_STACK_OVERFLOW:
            return GetPreallocatedStackOverflowException();
        }

        DWORD exceptionCode = 
          MapWin32FaultToCOMPlusException(&pSEHException->m_exception);

        EEException e((RuntimeExceptionKind)exceptionCode);

        OBJECTREF throwable = e.GetThrowable();
        GCPROTECT_BEGIN (throwable);
        EX_TRY
        {
            SCAN_IGNORE_FAULT;
            if (throwable != NULL  && !CLRException::IsPreallocatedExceptionObject(throwable))
            {
                _ASSERTE(IsException(throwable->GetMethodTable()));

                // set the exception code
                ((EXCEPTIONREF)throwable)->SetXCode(pSEHException->m_exception.ExceptionCode);
            }
        }
        EX_CATCH
        {
        }
        EX_END_CATCH(SwallowAllExceptions)
        GCPROTECT_END ();
            
        return throwable;
    }
    else
    {
        // We can enter here for HRException, COMException, DelegatingException
        // just to name a few.
        OBJECTREF oRetVal = NULL;
        GCPROTECT_BEGIN(oRetVal);
        {
            EX_TRY
            {
                HRESULT hr = pException->GetHR();

                if (hr == E_OUTOFMEMORY || hr == HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY))
                {
                    oRetVal = GetBestOutOfMemoryException();
                }
                else if (hr == COR_E_STACKOVERFLOW)
                {
                    oRetVal = GetPreallocatedStackOverflowException();
                }
                else
                {
                    SafeComHolder<IErrorInfo> pErrInfo(pException->GetErrorInfo());

                    if (pErrInfo != NULL)
                    {
                        GetExceptionForHR(hr, pErrInfo, &oRetVal);
                    }
                    else
                    {
                        SString message;
                        pException->GetMessage(message);

                        EEMessageException e(hr, IDS_EE_GENERIC, message);

                        oRetVal = e.CreateThrowable();
                    }
                }
            }
            EX_CATCH
            {
                // We have caught an exception trying to get a Throwable for the pException we
                //  were given.  It is tempting to want to get the Throwable for the new
                //  exception, but that is dangerous, due to infinitely cascading 
                //  exceptions, leading to a stack overflow.

                // If we can see that the exception was OOM, return the preallocated OOM,
                //  if we can see that it is SO, return the preallocated SO, 
                //  if we can see that it is some other managed exception, return that
                //  exception, otherwise return the preallocated System.Exception.
                Exception *pNewException = GET_EXCEPTION();

                if (pNewException->IsPreallocatedOOMException())
                {   // It definitely was an OOM
                    STRESS_LOG0(LF_EH, LL_INFO100, "CLRException::GetThrowableFromException: OOM creating throwable; getting pre-alloc'd OOM.\n");
                    if (oRetVal == NULL)
                        oRetVal = GetPreallocatedOutOfMemoryException();
                }
                else
                if (pNewException->IsType(CLRLastThrownObjectException::GetType()) &&
                    (pThread->LastThrownObject() != NULL))           
                {
                    STRESS_LOG0(LF_EH, LL_INFO100, "CLRException::GetThrowableFromException: LTO Exception creating throwable; getting LastThrownObject.\n");
                    if (oRetVal == NULL)
                        oRetVal = pThread->LastThrownObject();
                }
                else
                {   
                    // We *could* come here if one of the calls in the EX_TRY above throws an exception (e.g. MissingMethodException if we attempt
                    // to invoke CreateThrowable for a type that does not have a default constructor) that is neither preallocated OOM nor a 
                    // CLRLastThrownObject type.
                    //
                    // Like the comment says above, we cannot afford to get the throwable lest we hit SO. In such a case, runtime is not in a bad shape
                    // but we dont know what to return as well. A reasonable answer is to return something less appropriate than ripping down process
                    // or returning an incorrect exception (e.g. OOM) that could break execution paths.
                    //
                    // Hence, we return preallocated System.Exception instance.
                    if (oRetVal == NULL)
                    {
                        oRetVal = GetPreallocatedBaseException();
                        STRESS_LOG0(LF_EH, LL_INFO100, "CLRException::GetThrowableFromException: Unknown Exception creating throwable; getting preallocated System.Exception.\n");
                    }
                }

            }
            EX_END_CATCH(SwallowAllExceptions)
        }
        GCPROTECT_END();

        return oRetVal;
    }
} // OBJECTREF CLRException::GetThrowableFromException()

OBJECTREF CLRException::GetThrowableFromExceptionRecord(EXCEPTION_RECORD *pExceptionRecord)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (IsComPlusException(pExceptionRecord))
    {
        return GetThread()->LastThrownObject();
    }

    return NULL;
}

void CLRException::HandlerState::CleanupTry()
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;

    if (m_pThread != NULL)
    {
        BEGIN_GETTHREAD_ALLOWED;
        // If there is no frame to unwind, UnwindFrameChain call is just an expensive NOP
        // due to setting up and tear down of EH records. So we avoid it if we can.
        if (m_pThread->GetFrame() < m_pFrame)
            UnwindFrameChain(m_pThread, m_pFrame);

        if (m_fPreemptiveGCDisabled != m_pThread->PreemptiveGCDisabled())
        {
            if (m_fPreemptiveGCDisabled)
                m_pThread->DisablePreemptiveGC();
            else
                m_pThread->EnablePreemptiveGC();
        }
        END_GETTHREAD_ALLOWED;
    }

    // Make sure to call the base class's CleanupTry so it can do whatever it wants to do.
    Exception::HandlerState::CleanupTry();
}

void CLRException::HandlerState::SetupCatch(INDEBUG_COMMA(__in_z const char * szFile) int lineNum)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_CANNOT_TAKE_LOCK;

    Exception::HandlerState::SetupCatch(INDEBUG_COMMA(szFile) lineNum);

    Thread *pThread = NULL;
    DWORD exceptionCode = 0;

    if (g_fEEStarted)
    {
        pThread = GetThread();
        exceptionCode = GetCurrentExceptionCode();
    }
    
    if (!DidCatchCxx())
    {
        if (exceptionCode == STATUS_STACK_OVERFLOW)
        {
            // Handle SO exception
            // 
            // We should ensure that a valid Thread object exists before trying to set SO as the LTO.
            if (pThread != NULL)
            {
                // We have a nasty issue with our EX_TRY/EX_CATCH.  If EX_CATCH catches SEH exception,
                // GET_THROWABLE uses CLRLastThrownObjectException instead, because we don't know
                // what exception to use.  But for SO, we can use preallocated SO exception.
                GCX_COOP();
                pThread->SetSOForLastThrownObject();
            }

            if (exceptionCode == STATUS_STACK_OVERFLOW)
            {
                // We have called HandleStackOverflow for soft SO through our vectored exception handler.
                EEPolicy::HandleStackOverflow(SOD_UnmanagedFrameHandler, FRAME_TOP);                
            }
        }
    }

#ifdef WIN64EXCEPTIONS
    if (!DidCatchCxx())
    {
        // this must be done after the second pass has run, it does not 
        // reference anything on the stack, so it is safe to run in an 
        // SEH __except clause as well as a C++ catch clause.
        ExceptionTracker::PopTrackers(this);
    }
#endif // WIN64EXCEPTIONS
}

#ifdef LOGGING
void CLRException::HandlerState::SucceedCatch()
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_MODE_ANY;
    STATIC_CONTRACT_CANNOT_TAKE_LOCK;

    LOG((LF_EH, LL_INFO100, "EX_CATCH catch succeeded (CLRException::HandlerState)\n"));

    //
    // At this point, we don't believe we need to do any unwinding of the ExInfo chain after an EX_CATCH. The chain
    // is unwound by CPFH_UnwindFrames1() when it detects that the exception is being caught by an unmanaged
    // catcher. EX_CATCH looks just like an unmanaged catcher now, so the unwind is already done by the time we get
    // into the catch. That's different than before the big switch to the new exeption system, and it effects
    // rethrows. Fixing rethrows is a work item for a little later. For now, we're simplying removing the unwind
    // from here to avoid the extra unwind, which is harmless in many cases, but is very harmful when a managed
    // filter throws an exception.
    //
    //

    Exception::HandlerState::SucceedCatch();
}
#endif

#endif // CROSSGEN_COMPILE

// ---------------------------------------------------------------------------
// EEException methods
// ---------------------------------------------------------------------------

//------------------------------------------------------------------------
// Array that is used to retrieve the right exception for a given HRESULT.
//------------------------------------------------------------------------

#ifdef FEATURE_COMINTEROP

struct WinRtHR_to_ExceptionKind_Map
{
    RuntimeExceptionKind reKind;
    int cHRs;
    const HRESULT *aHRs;
};

enum WinRtOnly_ExceptionKind {
#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) kWinRtEx##reKind,
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...)
#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...)
#include "rexcep.h"
kWinRtExLastException
};

#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) static const HRESULT s_##reKind##WinRtOnlyHRs[] = { __VA_ARGS__ };
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...)
#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...)
#include "rexcep.h"

static const
WinRtHR_to_ExceptionKind_Map gWinRtHR_to_ExceptionKind_Maps[] = {
#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...) { k##reKind, sizeof(s_##reKind##WinRtOnlyHRs) / sizeof(HRESULT), s_##reKind##WinRtOnlyHRs },
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...)
#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...)
#include "rexcep.h"
};

#endif  // FEATURE_COMINTEROP

struct ExceptionHRInfo
{
    int cHRs;
    const HRESULT *aHRs;
};

#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) static const HRESULT s_##reKind##HRs[] = { __VA_ARGS__ };
#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...)
#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__)
#include "rexcep.h"

static const
ExceptionHRInfo gExceptionHRInfos[] = {
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) {sizeof(s_##reKind##HRs) / sizeof(HRESULT), s_##reKind##HRs},
#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...)
#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__)
#include "rexcep.h"
};


static const
bool gShouldDisplayHR[] =
{   
#define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...) bHRformessage,
#define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...)
#define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__)
#include "rexcep.h"
};


/*static*/
HRESULT EEException::GetHRFromKind(RuntimeExceptionKind reKind)
{
    LIMITED_METHOD_CONTRACT;
    return gExceptionHRInfos[reKind].aHRs[0];
}

HRESULT EEException::GetHR() 
{ 
    LIMITED_METHOD_CONTRACT;

    return EEException::GetHRFromKind(m_kind);
}
    
IErrorInfo *EEException::GetErrorInfo()
{
    LIMITED_METHOD_CONTRACT;
    
    return NULL;
}

BOOL EEException::GetThrowableMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Return a meaningful HR message, if there is one.

    HRESULT hr = GetHR();

    // If the hr is more interesting than the kind, use that
    // for a message.

    if (hr != S_OK 
        && hr != E_FAIL
        && (gShouldDisplayHR[m_kind]
            || gExceptionHRInfos[m_kind].aHRs[0] !=  hr))
    {
        // If it has only one HR, the original message should be good enough
        _ASSERTE(gExceptionHRInfos[m_kind].cHRs > 1 ||
                 gExceptionHRInfos[m_kind].aHRs[0] !=  hr);
        
        GenerateTopLevelHRExceptionMessage(hr, result);
        return TRUE;
    }

    // No interesting hr - just keep the class default message.

    return FALSE;
}

void EEException::GetMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // First look for a specialized message
    if (GetThrowableMessage(result))
        return;
    
    // Otherwise, report the class's generic message
    LPCUTF8 pszExceptionName = NULL;
    if (m_kind <= kLastExceptionInMscorlib)
    {
        pszExceptionName = MscorlibBinder::GetExceptionName(m_kind);
        result.SetUTF8(pszExceptionName);
    }
#ifndef CROSSGEN_COMPILE
    else
    {
        FrameworkExceptionLoader::GetExceptionName(m_kind, result);
    }
#endif // CROSSGEN_COMPILE
}

OBJECTREF EEException::CreateThrowable()
{
#ifdef CROSSGEN_COMPILE
    _ASSERTE(false);
    return NULL;
#else
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    _ASSERTE(g_pPreallocatedOutOfMemoryException != NULL);
    static int allocCount = 0;

    MethodTable *pMT = NULL;
    if (m_kind <= kLastExceptionInMscorlib)
        pMT = MscorlibBinder::GetException(m_kind);
    else
    {
        pMT = FrameworkExceptionLoader::GetException(m_kind);
    }

    ThreadPreventAsyncHolder preventAsyncHolder(m_kind == kThreadAbortException);

    OBJECTREF throwable = AllocateObject(pMT);
    allocCount++;
    GCPROTECT_BEGIN(throwable);

    {
        ThreadPreventAsyncHolder preventAbort(m_kind == kThreadAbortException ||
                                              m_kind == kThreadInterruptedException);
        CallDefaultConstructor(throwable);
    }

    HRESULT hr = GetHR();
    ((EXCEPTIONREF)throwable)->SetHResult(hr);

    SString message;
    if (GetThrowableMessage(message))
    {
        // Set the message field. It is not safe doing this through the constructor
        // since the string constructor for some exceptions add a prefix to the message 
        // which we don't want.
        //
        // We only want to replace whatever the default constructor put there, if we
        // have something meaningful to add.
        
        STRINGREF s = StringObject::NewString(message);
        ((EXCEPTIONREF)throwable)->SetMessage(s);
    }

    GCPROTECT_END();

    return throwable;
#endif
}

RuntimeExceptionKind EEException::GetKindFromHR(HRESULT hr, bool fIsWinRtMode /*= false*/)
{
    LIMITED_METHOD_CONTRACT;

    #ifdef FEATURE_COMINTEROP    
    // If we are in WinRT mode, try to get a WinRT specific mapping first:
    if (fIsWinRtMode)
    {
        for (int i = 0; i < kWinRtExLastException; i++)
        {
            for (int j = 0; j < gWinRtHR_to_ExceptionKind_Maps[i].cHRs; j++)
            {
                if (gWinRtHR_to_ExceptionKind_Maps[i].aHRs[j] == hr)
                {
                    return gWinRtHR_to_ExceptionKind_Maps[i].reKind;                    
                }
            }
        }
    }    
    #endif  // FEATURE_COMINTEROP
    
    // Is not in WinRT mode OR did not find a WinRT specific mapping. Check normal mappings:
    
    for (int i = 0; i < kLastException; i++)
    {
        for (int j = 0; j < gExceptionHRInfos[i].cHRs; j++)
        {
            if (gExceptionHRInfos[i].aHRs[j] == hr)
                return (RuntimeExceptionKind) i;
        }
    }

    return (fIsWinRtMode ? kException : kCOMException);
    
} // RuntimeExceptionKind EEException::GetKindFromHR()

BOOL EEException::GetResourceMessage(UINT iResourceID, SString &result, 
                                     const SString &arg1, const SString &arg2,
                                     const SString &arg3, const SString &arg4,
                                     const SString &arg5, const SString &arg6)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    BOOL ok;

    StackSString temp;
    ok = temp.LoadResource(CCompRC::Error, iResourceID);

    if (ok)
        result.FormatMessage(FORMAT_MESSAGE_FROM_STRING,
         (LPCWSTR)temp, 0, 0, arg1, arg2, arg3, arg4, arg5, arg6);

    return ok;
}

// ---------------------------------------------------------------------------
// EEMessageException methods
// ---------------------------------------------------------------------------

HRESULT EEMessageException::GetHR()
{
    WRAPPER_NO_CONTRACT;
    
    return m_hr;
}

BOOL EEMessageException::GetThrowableMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_resID != 0 && GetResourceMessage(m_resID, result))
        return TRUE;

    return EEException::GetThrowableMessage(result);
}

BOOL EEMessageException::GetResourceMessage(UINT iResourceID, SString &result)
{
    WRAPPER_NO_CONTRACT;

    return EEException::GetResourceMessage(
        iResourceID, result, m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6);
}

// ---------------------------------------------------------------------------
// EEResourceException methods
// ---------------------------------------------------------------------------

void EEResourceException::GetMessage(SString &result)
{
    WRAPPER_NO_CONTRACT; 
    // 
    // Return a simplified message, 
    // since we don't want to call managed code here.
    //

    result.Printf("%s (message resource %s)", 
                  MscorlibBinder::GetExceptionName(m_kind), m_resourceName.GetUnicode());
}

BOOL EEResourceException::GetThrowableMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

#ifndef CROSSGEN_COMPILE
    STRINGREF message = NULL;
    ResMgrGetString(m_resourceName, &message);

    if (message != NULL) 
    {
        message->GetSString(result);
        return TRUE;
    }
#endif // CROSSGEN_COMPILE

    return EEException::GetThrowableMessage(result);
}

// ---------------------------------------------------------------------------
// EEFieldException is an EE exception subclass composed of a field
// ---------------------------------------------------------------------------

    
BOOL EEFieldException::GetThrowableMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_messageID == 0)
    {
        LPUTF8 szFullName;
        LPCUTF8 szClassName, szMember;
        szMember = m_pFD->GetName();
        DefineFullyQualifiedNameForClass();
        szClassName = GetFullyQualifiedNameForClass(m_pFD->GetApproxEnclosingMethodTable());
        MAKE_FULLY_QUALIFIED_MEMBER_NAME(szFullName, NULL, szClassName, szMember, "");
        result.SetUTF8(szFullName);

        return TRUE;
    }
    else
    {
        _ASSERTE(m_pAccessingMD != NULL);

        const TypeString::FormatFlags formatFlags = static_cast<TypeString::FormatFlags>(
            TypeString::FormatNamespace |
            TypeString::FormatAngleBrackets |
            TypeString::FormatSignature);

        StackSString caller;
        TypeString::AppendMethod(caller,
                                 m_pAccessingMD,
                                 m_pAccessingMD->GetClassInstantiation(),
                                 formatFlags);

        StackSString field;
        TypeString::AppendField(field,
                                m_pFD,
                                m_pFD->GetApproxEnclosingMethodTable()->GetInstantiation(),
                                formatFlags);

        return GetResourceMessage(m_messageID, result, caller, field, m_additionalContext);
    }
}

// ---------------------------------------------------------------------------
// EEMethodException is an EE exception subclass composed of a field
// ---------------------------------------------------------------------------

BOOL EEMethodException::GetThrowableMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (m_messageID == 0)
    {
        LPUTF8 szFullName;
        LPCUTF8 szClassName, szMember;
        szMember = m_pMD->GetName();
        DefineFullyQualifiedNameForClass();
        szClassName = GetFullyQualifiedNameForClass(m_pMD->GetMethodTable());
        //@todo GENERICS: exact instantiations?
        MetaSig tmp(m_pMD);
        SigFormat sigFormatter(tmp, szMember);
        const char * sigStr = sigFormatter.GetCStringParmsOnly();
        MAKE_FULLY_QUALIFIED_MEMBER_NAME(szFullName, NULL, szClassName, szMember, sigStr);
        result.SetUTF8(szFullName);

        return TRUE;
    }
    else
    {
        _ASSERTE(m_pAccessingMD != NULL);

        const TypeString::FormatFlags formatFlags = static_cast<TypeString::FormatFlags>(
            TypeString::FormatNamespace |
            TypeString::FormatAngleBrackets |
            TypeString::FormatSignature);

        StackSString caller;
        TypeString::AppendMethod(caller,
                                 m_pAccessingMD,
                                 m_pAccessingMD->GetClassInstantiation(),
                                 formatFlags);

        StackSString callee;
        TypeString::AppendMethod(callee,
                                 m_pMD,
                                 m_pMD->GetClassInstantiation(),
                                 formatFlags);

        return GetResourceMessage(m_messageID, result, caller, callee, m_additionalContext);
    }
}

BOOL EETypeAccessException::GetThrowableMessage(SString &result)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    const TypeString::FormatFlags formatFlags = static_cast<TypeString::FormatFlags>(
            TypeString::FormatNamespace |
            TypeString::FormatAngleBrackets |
            TypeString::FormatSignature);
    StackSString type;
    TypeString::AppendType(type, TypeHandle(m_pMT), formatFlags);

    if (m_messageID == 0)
    {
        result.Set(type);
        return TRUE;
    }
    else
    {
        _ASSERTE(m_pAccessingMD != NULL);

        StackSString caller;
        TypeString::AppendMethod(caller,
                                 m_pAccessingMD,
                                 m_pAccessingMD->GetClassInstantiation(),
                                 formatFlags);

        return GetResourceMessage(m_messageID, result, caller, type, m_additionalContext);
    }
}

// ---------------------------------------------------------------------------
// EEArgumentException is an EE exception subclass representing a bad argument
// ---------------------------------------------------------------------------

typedef struct {
    OBJECTREF pThrowable;
    STRINGREF s1;
    OBJECTREF pTmpThrowable;
} ProtectArgsStruct;

OBJECTREF EEArgumentException::CreateThrowable()
{
#ifdef CROSSGEN_COMPILE
    _ASSERTE(false);
    return NULL;
#else

    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    _ASSERTE(GetThread() != NULL);

    ProtectArgsStruct prot;
    memset(&prot, 0, sizeof(ProtectArgsStruct));
    ResMgrGetString(m_resourceName, &prot.s1);
    GCPROTECT_BEGIN(prot);

    MethodTable *pMT = MscorlibBinder::GetException(m_kind);
    prot.pThrowable = AllocateObject(pMT);

    MethodDesc* pMD = MemberLoader::FindMethod(prot.pThrowable->GetMethodTable(),
                            COR_CTOR_METHOD_NAME, &gsig_IM_Str_Str_RetVoid);

    if (!pMD)
    {
        MAKE_WIDEPTR_FROMUTF8(wzMethodName, COR_CTOR_METHOD_NAME);
        COMPlusThrowNonLocalized(kMissingMethodException, wzMethodName);
    }

    MethodDescCallSite exceptionCtor(pMD);

    STRINGREF argName = StringObject::NewString(m_argumentName);

    // Note that ArgumentException takes arguments to its constructor in a different order,
    // for usability reasons.  However it is inconsistent with our other exceptions.
    if (m_kind == kArgumentException)
    {
        ARG_SLOT args1[] = { 
            ObjToArgSlot(prot.pThrowable),
            ObjToArgSlot(prot.s1),
            ObjToArgSlot(argName),
        };
        exceptionCtor.Call(args1);
    }
    else
    {
        ARG_SLOT args1[] = { 
            ObjToArgSlot(prot.pThrowable),
            ObjToArgSlot(argName),
            ObjToArgSlot(prot.s1),
        };
        exceptionCtor.Call(args1);
    }

    GCPROTECT_END(); //Prot

    return prot.pThrowable;
#endif
}


// ---------------------------------------------------------------------------
// EETypeLoadException is an EE exception subclass representing a type loading
// error
// ---------------------------------------------------------------------------

EETypeLoadException::EETypeLoadException(LPCUTF8 pszNameSpace, LPCUTF8 pTypeName, 
                    LPCWSTR pAssemblyName, LPCUTF8 pMessageArg, UINT resIDWhy)
  : EEException(kTypeLoadException),
    m_pAssemblyName(pAssemblyName),
    m_pMessageArg(SString::Utf8, pMessageArg),
    m_resIDWhy(resIDWhy)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    if(pszNameSpace)
    {
        SString sNameSpace(SString::Utf8, pszNameSpace);
        SString sTypeName(SString::Utf8, pTypeName);
        m_fullName.MakeFullNamespacePath(sNameSpace, sTypeName);
    }
    else if (pTypeName)
        m_fullName.SetUTF8(pTypeName);
    else {
        WCHAR wszTemplate[30];
        if (FAILED(UtilLoadStringRC(IDS_EE_NAME_UNKNOWN,
                                    wszTemplate,
                                    sizeof(wszTemplate)/sizeof(wszTemplate[0]),
                                    FALSE)))
            wszTemplate[0] = W('\0');
        MAKE_UTF8PTR_FROMWIDE(name, wszTemplate);
        m_fullName.SetUTF8(name);
    }
}

EETypeLoadException::EETypeLoadException(LPCWSTR pFullName,
                                         LPCWSTR pAssemblyName, 
                                         LPCUTF8 pMessageArg, 
                                         UINT resIDWhy)
  : EEException(kTypeLoadException),
    m_pAssemblyName(pAssemblyName),
    m_pMessageArg(SString::Utf8, pMessageArg),
    m_resIDWhy(resIDWhy)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    MAKE_UTF8PTR_FROMWIDE(name, pFullName);
    m_fullName.SetUTF8(name);
}

void EETypeLoadException::GetMessage(SString &result)
{
    WRAPPER_NO_CONTRACT;
    GetResourceMessage(IDS_CLASSLOAD_GENERAL, result,
                       m_fullName, m_pAssemblyName, m_pMessageArg); 
}

OBJECTREF EETypeLoadException::CreateThrowable()
{
#ifdef CROSSGEN_COMPILE
    _ASSERTE(false);
    return NULL;
#else

    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    MethodTable *pMT = MscorlibBinder::GetException(kTypeLoadException);

    struct _gc {
        OBJECTREF pNewException;
        STRINGREF pNewAssemblyString;
        STRINGREF pNewClassString;
        STRINGREF pNewMessageArgString;
    } gc;
    ZeroMemory(&gc, sizeof(gc));
    GCPROTECT_BEGIN(gc);

    gc.pNewClassString = StringObject::NewString(m_fullName);

    if (!m_pMessageArg.IsEmpty())
        gc.pNewMessageArgString = StringObject::NewString(m_pMessageArg);

    if (!m_pAssemblyName.IsEmpty())
        gc.pNewAssemblyString = StringObject::NewString(m_pAssemblyName);

    gc.pNewException = AllocateObject(pMT);

    MethodDesc* pMD = MemberLoader::FindMethod(gc.pNewException->GetMethodTable(),
                            COR_CTOR_METHOD_NAME, &gsig_IM_Str_Str_Str_Int_RetVoid);

    if (!pMD)
    {
        MAKE_WIDEPTR_FROMUTF8(wzMethodName, COR_CTOR_METHOD_NAME);
        COMPlusThrowNonLocalized(kMissingMethodException, wzMethodName);
    }

    MethodDescCallSite exceptionCtor(pMD);

    ARG_SLOT args[] = {
        ObjToArgSlot(gc.pNewException),
        ObjToArgSlot(gc.pNewClassString),
        ObjToArgSlot(gc.pNewAssemblyString),
        ObjToArgSlot(gc.pNewMessageArgString),
        (ARG_SLOT)m_resIDWhy,
    };
    
    exceptionCtor.Call(args);

    GCPROTECT_END();
        
    return gc.pNewException;
#endif
}

// ---------------------------------------------------------------------------
// EEFileLoadException is an EE exception subclass representing a file loading
// error
// ---------------------------------------------------------------------------
EEFileLoadException::EEFileLoadException(const SString &name, HRESULT hr, void *pFusionLog, Exception *pInnerException/* = NULL*/)
  : EEException(GetFileLoadKind(hr)),
    m_name(name),
    m_pFusionLog(pFusionLog),
    m_hr(hr)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // We don't want to wrap IsTransient() exceptions. The caller should really have checked this
    // before invoking the ctor. 
    _ASSERTE(pInnerException == NULL || !(pInnerException->IsTransient()));
    m_innerException = pInnerException ? pInnerException->DomainBoundClone() : NULL;

    if (m_name.IsEmpty())
    {
        WCHAR wszTemplate[30];
        if (FAILED(UtilLoadStringRC(IDS_EE_NAME_UNKNOWN,
                                    wszTemplate,
                                    sizeof(wszTemplate)/sizeof(wszTemplate[0]),
                                    FALSE)))
        {
            wszTemplate[0] = W('\0');
        }

        m_name.Set(wszTemplate);
    }
}


EEFileLoadException::~EEFileLoadException()
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;

}



void EEFileLoadException::SetFileName(const SString &fileName, BOOL removePath)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    //<TODO>@TODO: security: It would be nice for debugging purposes if the
    // user could have the full path, if the user has the right permission.</TODO>
    if (removePath)
    {
        SString::CIterator i = fileName.End();
        
        if (fileName.FindBack(i, W('\\')))
            i++;

        if (fileName.FindBack(i, W('/')))
            i++;

        m_name.Set(fileName, i, fileName.End());
    }
    else
        m_name.Set(fileName);
}

void EEFileLoadException::GetMessage(SString &result)
{
    WRAPPER_NO_CONTRACT;

    SString sHR;
    GetHRMsg(m_hr, sHR);
    GetResourceMessage(GetResourceIDForFileLoadExceptionHR(m_hr), result, m_name, sHR);
}

void EEFileLoadException::GetName(SString &result)
{
    WRAPPER_NO_CONTRACT;

    result.Set(m_name);
}

/* static */
RuntimeExceptionKind EEFileLoadException::GetFileLoadKind(HRESULT hr)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    if (Assembly::FileNotFound(hr))
        return kFileNotFoundException;
    else
    {
        // Make sure this matches the list in rexcep.h
        if ((hr == COR_E_BADIMAGEFORMAT) ||
            (hr == CLDB_E_FILE_OLDVER)   ||
            (hr == CLDB_E_INDEX_NOTFOUND)   ||
            (hr == CLDB_E_FILE_CORRUPT)   ||
            (hr == COR_E_NEWER_RUNTIME)   ||
            (hr == COR_E_ASSEMBLYEXPECTED)   ||
            (hr == HRESULT_FROM_WIN32(ERROR_BAD_EXE_FORMAT)) ||
            (hr == HRESULT_FROM_WIN32(ERROR_EXE_MARKED_INVALID)) ||
            (hr == CORSEC_E_INVALID_IMAGE_FORMAT) ||
            (hr == HRESULT_FROM_WIN32(ERROR_NOACCESS)) ||
            (hr == HRESULT_FROM_WIN32(ERROR_INVALID_ORDINAL))   ||
            (hr == HRESULT_FROM_WIN32(ERROR_INVALID_DLL)) || 
            (hr == HRESULT_FROM_WIN32(ERROR_FILE_CORRUPT)) ||
            (hr == (HRESULT) IDS_CLASSLOAD_32BITCLRLOADING64BITASSEMBLY) ||
            (hr == COR_E_LOADING_REFERENCE_ASSEMBLY) ||
            (hr == META_E_BAD_SIGNATURE) || 
            (hr == COR_E_LOADING_WINMD_REFERENCE_ASSEMBLY))
            return kBadImageFormatException;
        else 
        {
            if ((hr == E_OUTOFMEMORY) || (hr == NTE_NO_MEMORY))
                return kOutOfMemoryException;
            else
                return kFileLoadException;
        }
    }
}

OBJECTREF EEFileLoadException::CreateThrowable()
{
#ifdef CROSSGEN_COMPILE
    _ASSERTE(false);
    return NULL;
#else

    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // Fetch any log info from the fusion log
    SString logText;
    struct _gc {
        OBJECTREF pNewException;
        STRINGREF pNewFileString;
        STRINGREF pFusLogString;
    } gc;
    ZeroMemory(&gc, sizeof(gc));
    GCPROTECT_BEGIN(gc);

    gc.pNewFileString = StringObject::NewString(m_name);
    gc.pFusLogString = StringObject::NewString(logText);
    gc.pNewException = AllocateObject(MscorlibBinder::GetException(m_kind));

    MethodDesc* pMD = MemberLoader::FindMethod(gc.pNewException->GetMethodTable(),
                            COR_CTOR_METHOD_NAME, &gsig_IM_Str_Str_Int_RetVoid);

    if (!pMD)
    {
        MAKE_WIDEPTR_FROMUTF8(wzMethodName, COR_CTOR_METHOD_NAME);
        COMPlusThrowNonLocalized(kMissingMethodException, wzMethodName);
    }

    MethodDescCallSite  exceptionCtor(pMD);

    ARG_SLOT args[] = {
        ObjToArgSlot(gc.pNewException),
        ObjToArgSlot(gc.pNewFileString),
        ObjToArgSlot(gc.pFusLogString),
        (ARG_SLOT) m_hr
    };

    exceptionCtor.Call(args);

    GCPROTECT_END();

    return gc.pNewException;
#endif
}


/* static */
BOOL EEFileLoadException::CheckType(Exception* ex)
{
    LIMITED_METHOD_CONTRACT;

    // used as typeof(EEFileLoadException)
    RuntimeExceptionKind kind = kException;
    if (ex->IsType(EEException::GetType()))
        kind=((EEException*)ex)->m_kind;
 
    
    switch(kind)
    {
        case kFileLoadException:
        case kFileNotFoundException:
        case kBadImageFormatException:
            return TRUE;
        default:
            return FALSE;
    }
};


// <TODO>@todo: ideally we would use inner exceptions with these routines</TODO>

/* static */

/* static */
void DECLSPEC_NORETURN EEFileLoadException::Throw(AssemblySpec  *pSpec, HRESULT hr, Exception *pInnerException/* = NULL*/)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    if (hr == COR_E_THREADABORTED)
        COMPlusThrow(kThreadAbortException);
    if (hr == E_OUTOFMEMORY)
        COMPlusThrowOM();
#ifdef FEATURE_COMINTEROP
    if ((hr == RO_E_METADATA_NAME_NOT_FOUND) || (hr == CLR_E_BIND_TYPE_NOT_FOUND))
    {   // These error codes behave like FileNotFound, but are exposed as TypeLoadException
        EX_THROW_WITH_INNER(EETypeLoadException, (pSpec->GetWinRtTypeNamespace(), pSpec->GetWinRtTypeClassName(), nullptr, nullptr, IDS_EE_WINRT_LOADFAILURE), pInnerException);
    }
#endif //FEATURE_COMINTEROP
    
    StackSString name;
    pSpec->GetFileOrDisplayName(0, name);
    EX_THROW_WITH_INNER(EEFileLoadException, (name, hr), pInnerException);
}

/* static */
void DECLSPEC_NORETURN EEFileLoadException::Throw(PEFile *pFile, HRESULT hr, Exception *pInnerException /* = NULL*/)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    if (hr == COR_E_THREADABORTED)
        COMPlusThrow(kThreadAbortException);
    if (hr == E_OUTOFMEMORY)
        COMPlusThrowOM();

    StackSString name;

    if (pFile->IsAssembly())
        ((PEAssembly*)pFile)->GetDisplayName(name);
    else
        name = StackSString(SString::Utf8, pFile->GetSimpleName());
    EX_THROW_WITH_INNER(EEFileLoadException, (name, hr), pInnerException);

}

/* static */
void DECLSPEC_NORETURN EEFileLoadException::Throw(LPCWSTR path, HRESULT hr, Exception *pInnerException/* = NULL*/)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    if (hr == COR_E_THREADABORTED)
        COMPlusThrow(kThreadAbortException);
    if (hr == E_OUTOFMEMORY)
        COMPlusThrowOM();

    EX_THROW_WITH_INNER(EEFileLoadException, (StackSString(path), hr), pInnerException);
}

/* static */
/* static */
void DECLSPEC_NORETURN EEFileLoadException::Throw(PEAssembly *parent, 
                                                  const void *memory, COUNT_T size, HRESULT hr, Exception *pInnerException/* = NULL*/)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;
    
    if (hr == COR_E_THREADABORTED)
        COMPlusThrow(kThreadAbortException);
    if (hr == E_OUTOFMEMORY)
        COMPlusThrowOM();

    StackSString name;
    name.Printf("%d bytes loaded from ", size);

    StackSString parentName;
    parent->GetDisplayName(parentName);

    name.Append(parentName);
    EX_THROW_WITH_INNER(EEFileLoadException, (name, hr), pInnerException);
}

#ifndef CROSSGEN_COMPILE
// ---------------------------------------------------------------------------
// EEComException methods
// ---------------------------------------------------------------------------

static HRESULT Undefer(EXCEPINFO *pExcepInfo)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (pExcepInfo->pfnDeferredFillIn)
    {
        EXCEPINFO FilledInExcepInfo; 

        HRESULT hr = pExcepInfo->pfnDeferredFillIn(&FilledInExcepInfo);
        if (SUCCEEDED(hr))
        {
            // Free the strings in the original EXCEPINFO.
            if (pExcepInfo->bstrDescription)
            {
                SysFreeString(pExcepInfo->bstrDescription);
                pExcepInfo->bstrDescription = NULL;
            }
            if (pExcepInfo->bstrSource)
            {
                SysFreeString(pExcepInfo->bstrSource);
                pExcepInfo->bstrSource = NULL;
            }
            if (pExcepInfo->bstrHelpFile)
            {
                SysFreeString(pExcepInfo->bstrHelpFile);
                pExcepInfo->bstrHelpFile = NULL;
            }

            // Fill in the new data
            *pExcepInfo = FilledInExcepInfo;
        }
    }

    if (pExcepInfo->scode != 0)
        return pExcepInfo->scode;
    else
        return (HRESULT)pExcepInfo->wCode;
}

EECOMException::EECOMException(EXCEPINFO *pExcepInfo)
  : EEException(GetKindFromHR(Undefer(pExcepInfo)))
{
    WRAPPER_NO_CONTRACT;

    if (pExcepInfo->scode != 0)
        m_ED.hr = pExcepInfo->scode;
    else
        m_ED.hr = (HRESULT)pExcepInfo->wCode;
    
    m_ED.bstrDescription = pExcepInfo->bstrDescription;
    m_ED.bstrSource = pExcepInfo->bstrSource;
    m_ED.bstrHelpFile = pExcepInfo->bstrHelpFile;
    m_ED.dwHelpContext = pExcepInfo->dwHelpContext;
    m_ED.guid = GUID_NULL;

#ifdef FEATURE_COMINTEROP    
    m_ED.bstrReference = NULL;
    m_ED.bstrRestrictedError = NULL;
    m_ED.bstrCapabilitySid = NULL;
    m_ED.pRestrictedErrorInfo = NULL;
    m_ED.bHasLanguageRestrictedErrorInfo = FALSE;
#endif

    // Zero the EXCEPINFO.
    memset(pExcepInfo, NULL, sizeof(EXCEPINFO));
}

EECOMException::EECOMException(ExceptionData *pData)
  : EEException(GetKindFromHR(pData->hr))
{
    LIMITED_METHOD_CONTRACT;
    
    m_ED = *pData;

    // Zero the data.
    ZeroMemory(pData, sizeof(ExceptionData));
}    

EECOMException::EECOMException(
    HRESULT hr,
    IErrorInfo *pErrInfo,
    bool fUseCOMException,  // use System.Runtime.InteropServices.COMException as the default exception type (means as much as !IsWinRT)
    IRestrictedErrorInfo* pRestrictedErrInfo,
    BOOL bHasLanguageRestrictedErrInfo
    COMMA_INDEBUG(BOOL bCheckInProcCCWTearOff))
  : EEException(GetKindFromHR(hr, !fUseCOMException))
{
    WRAPPER_NO_CONTRACT;
    
#ifdef FEATURE_COMINTEROP
    // Must use another path for managed IErrorInfos...
    //  note that this doesn't cover out-of-proc managed IErrorInfos.
    _ASSERTE(!bCheckInProcCCWTearOff || !IsInProcCCWTearOff(pErrInfo));
    _ASSERTE(pRestrictedErrInfo == NULL || !bCheckInProcCCWTearOff || !IsInProcCCWTearOff(pRestrictedErrInfo));
#endif  // FEATURE_COMINTEROP

    m_ED.hr = hr;
    m_ED.bstrDescription = NULL;
    m_ED.bstrSource = NULL;
    m_ED.bstrHelpFile = NULL;
    m_ED.dwHelpContext = NULL;
    m_ED.guid = GUID_NULL;

#ifdef FEATURE_COMINTEROP
    m_ED.bstrReference = NULL;
    m_ED.bstrRestrictedError = NULL;
    m_ED.bstrCapabilitySid = NULL;
    m_ED.pRestrictedErrorInfo = NULL;
    m_ED.bHasLanguageRestrictedErrorInfo = bHasLanguageRestrictedErrInfo;
#endif

    FillExceptionData(&m_ED, pErrInfo, pRestrictedErrInfo);
}

BOOL EECOMException::GetThrowableMessage(SString &result)
{
     CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

#ifdef FEATURE_COMINTEROP
    if (m_ED.bstrDescription != NULL || m_ED.bstrRestrictedError != NULL)
    {
        // For cross language WinRT exceptions, general information will be available in the bstrDescription,
        // which is populated from IErrorInfo::GetDescription and more specific information will be available
        // in the bstrRestrictedError which comes from the IRestrictedErrorInfo.  If both are available, we
        // need to concatinate them to produce the final exception message.

        result.Clear();

        // If we have a restricted description, start our message with that
        if (m_ED.bstrDescription != NULL)
        {
            SString generalInformation(m_ED.bstrDescription, SysStringLen(m_ED.bstrDescription));
            result.Append(generalInformation);

            // If we're also going to have a specific error message, append a newline to separate the two
            if (m_ED.bstrRestrictedError != NULL)
            {
                result.Append(W("\r\n"));
            }
        }

        // If we have additional error information, attach it to the end of the string
        if (m_ED.bstrRestrictedError != NULL)
        {
            SString restrictedDescription(m_ED.bstrRestrictedError, SysStringLen(m_ED.bstrRestrictedError));
            result.Append(restrictedDescription);
        }
    }
#else // !FEATURE_COMINTEROP
    if (m_ED.bstrDescription != NULL)
    {
        result.Set(m_ED.bstrDescription, SysStringLen(m_ED.bstrDescription));
    }
#endif // FEATURE_COMINTEROP
    else
    {
        GenerateTopLevelHRExceptionMessage(GetHR(), result);
    }

    return TRUE;
}

EECOMException::~EECOMException()
{
    WRAPPER_NO_CONTRACT;
    
    FreeExceptionData(&m_ED);
}

HRESULT EECOMException::GetHR()
{
    LIMITED_METHOD_CONTRACT;
    
    return m_ED.hr;
}

OBJECTREF EECOMException::CreateThrowable()
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    OBJECTREF throwable = NULL;
    GCPROTECT_BEGIN(throwable);

    // Note that this will pick up the message from GetThrowableMessage
    throwable = EEException::CreateThrowable();

    // Set the _helpURL field in the exception.
    if (m_ED.bstrHelpFile) 
    {
        // Create the help link from the help file and the help context.
        STRINGREF helpStr = NULL;
        if (m_ED.dwHelpContext != 0)
        {
            // We have a non 0 help context so use it to form the help link.
            SString strMessage;
            strMessage.Printf(W("%s#%d"), m_ED.bstrHelpFile, m_ED.dwHelpContext);
            helpStr = StringObject::NewString(strMessage);
        }
        else
        {
            // The help context is 0 so we simply use the help file to from the help link.
            helpStr = StringObject::NewString(m_ED.bstrHelpFile, SysStringLen(m_ED.bstrHelpFile));
        }

        ((EXCEPTIONREF)throwable)->SetHelpURL(helpStr);
    } 
        
    // Set the Source field in the exception.
    STRINGREF sourceStr = NULL;
    if (m_ED.bstrSource) 
    {
        sourceStr = StringObject::NewString(m_ED.bstrSource, SysStringLen(m_ED.bstrSource));
    }
    else
    {
        // for now set a null source
        sourceStr = StringObject::GetEmptyString();
    }
    ((EXCEPTIONREF)throwable)->SetSource(sourceStr);

#ifdef FEATURE_COMINTEROP
    //
    // Support for WinRT interface IRestrictedErrorInfo
    //
    if (m_ED.pRestrictedErrorInfo)
    {

        struct _gc {
            STRINGREF RestrictedErrorRef;
            STRINGREF ReferenceRef;
            STRINGREF RestrictedCapabilitySidRef;
            OBJECTREF RestrictedErrorInfoObjRef;
        } gc;
        ZeroMemory(&gc, sizeof(gc));
    
        GCPROTECT_BEGIN(gc);
        
        EX_TRY
        {            
            gc.RestrictedErrorRef = StringObject::NewString(
                m_ED.bstrRestrictedError, 
                SysStringLen(m_ED.bstrRestrictedError)
                );
            gc.ReferenceRef = StringObject::NewString(
                m_ED.bstrReference, 
                SysStringLen(m_ED.bstrReference)
                );

            gc.RestrictedCapabilitySidRef = StringObject::NewString(
                m_ED.bstrCapabilitySid,
                SysStringLen(m_ED.bstrCapabilitySid)
                );

            // Convert IRestrictedErrorInfo into a managed object - don't care whether it is a RCW/CCW
            GetObjectRefFromComIP(
                &gc.RestrictedErrorInfoObjRef,
                m_ED.pRestrictedErrorInfo,      // IUnknown *
                NULL,                           // ClassMT
                NULL,                           // ItfMT 
                ObjFromComIP::CLASS_IS_HINT | ObjFromComIP::IGNORE_WINRT_AND_SKIP_UNBOXING
                );

            //
            // Call Exception.AddExceptionDataForRestrictedErrorInfo and put error information 
            // from IRestrictedErrorInfo on Exception.Data
            //        
            MethodDescCallSite addExceptionDataForRestrictedErrorInfo(
                METHOD__EXCEPTION__ADD_EXCEPTION_DATA_FOR_RESTRICTED_ERROR_INFO,
                &throwable
                );

            ARG_SLOT Args[] =
            { 
                ObjToArgSlot(throwable),
                ObjToArgSlot(gc.RestrictedErrorRef),
                ObjToArgSlot(gc.ReferenceRef),
                ObjToArgSlot(gc.RestrictedCapabilitySidRef),
                ObjToArgSlot(gc.RestrictedErrorInfoObjRef),
                BoolToArgSlot(m_ED.bHasLanguageRestrictedErrorInfo)
            };

            addExceptionDataForRestrictedErrorInfo.Call(Args);

        }
        EX_CATCH
        {
            // IDictionary.Add may throw. Ignore all non terminal exceptions    
        }
        EX_END_CATCH(RethrowTerminalExceptions)

        GCPROTECT_END();
    }
#endif // FEATURE_COMINTEROP

    GCPROTECT_END();


    return throwable;
}

// ---------------------------------------------------------------------------
// ObjrefException methods
// ---------------------------------------------------------------------------

ObjrefException::ObjrefException()
{
    LIMITED_METHOD_CONTRACT;
}

ObjrefException::ObjrefException(OBJECTREF throwable)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    SetThrowableHandle(GetAppDomain()->CreateHandle(throwable));
}

// --------------------------------------------------------------------------------------------------------------------------------------
// ObjrefException and CLRLastThrownObjectException are never set as inner exception for an internal CLR exception.
// As a result, if we invoke DomainBoundClone against an exception, it will never reach these implementations.
// If someone does set them as inner, it will trigger contract violation - which is valid and should be fixed by whoever
// set them as inner since Exception::DomainBoundClone is implemented in utilcode that has to work outside the context of CLR and thus,
// should never trigger GC. This is also why GC_TRIGGERS is not supported in utilcode (refer to its definition in contracts.h).
// --------------------------------------------------------------------------------------------------------------------------------------
Exception *ObjrefException::DomainBoundCloneHelper()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;
    GCX_COOP();
    return new ObjrefException(GetThrowable());
}

// ---------------------------------------------------------------------------
// CLRLastThrownException methods
// ---------------------------------------------------------------------------

CLRLastThrownObjectException::CLRLastThrownObjectException()
{
    LIMITED_METHOD_CONTRACT;
}

Exception *CLRLastThrownObjectException::CloneHelper()
 {
    WRAPPER_NO_CONTRACT;
    GCX_COOP();
    return new ObjrefException(GetThrowable());
}
  
// ---------------------------------------------------------------------------
// See ObjrefException::DomainBoundCloneHelper comments.
// ---------------------------------------------------------------------------
Exception *CLRLastThrownObjectException::DomainBoundCloneHelper()
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;
    GCX_COOP();
    return new ObjrefException(GetThrowable());
}

OBJECTREF CLRLastThrownObjectException::CreateThrowable()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    DEBUG_STMT(Validate());

    return GetThread()->LastThrownObject();
} // OBJECTREF CLRLastThrownObjectException::CreateThrowable()

#if defined(_DEBUG)
CLRLastThrownObjectException* CLRLastThrownObjectException::Validate()
{
    CONTRACTL {
        NOTHROW;
        GC_NOTRIGGER;
        DEBUG_ONLY;
    }
    CONTRACTL_END;
    
    // Have to be in coop for GCPROTECT_BEGIN.
    GCX_COOP();

    OBJECTREF throwable = NULL;

    GCPROTECT_BEGIN(throwable);

    Thread * pThread = GetThread();
    throwable = pThread->LastThrownObject();

    DWORD dwCurrentExceptionCode = GetCurrentExceptionCode();

    if (dwCurrentExceptionCode == BOOTUP_EXCEPTION_COMPLUS)
    {
        // BOOTUP_EXCEPTION_COMPLUS can be thrown when a thread setup is failed due to reasons like
        // runtime is being shutdown or managed code is no longer allowed to be executed.
        //
        // If this exception is caught in EX_CATCH, there may not be any LTO setup since:
        //
        // 1) It is setup against the thread that may not exist (due to thread setup failure)
        // 2) This exception is raised using RaiseException (and not the managed raise implementation in RaiseTheExceptionInternalOnly) 
        //    since managed code may not be allowed to be executed. 
        //
        // However, code inside EX_CATCH is abstracted of this specificity of EH and thus, will attempt to fetch the throwble
        // using GET_THROWABLE that will, in turn, use the GET_EXCEPTION macro to fetch the C++ exception type corresponding to the caught exception.
        // Since BOOTUP_EXCEPTION_COMPLUS is a SEH exception, this (C++ exception) type will be CLRLastThrownObjectException.
        //
        // GET_EXCEPTION will call this method to validate the presence of LTO for a SEH exception caught by EX_CATCH. This is based upon the assumption
        // that by the time a SEH exception is caught in EX_CATCH, the LTO is setup:
        //
        // A) For a managed exception thrown, this is done by RaiseTheExceptionInternalOnly.
        // B) For a SEH exception that enters managed code from a PInvoke call, this is done by calling SafeSetThrowables after the corresponding throwable is created
        //    using CreateCOMPlusExceptionObject. 
        
        // Clearly, BOOTUP_EXCEPTION_COMPLUS can also be caught in EX_CATCH. However:
        //
        // (A) above is not applicable since the exception is raised using RaiseException.
        //
        // (B) scenario is interesting. On x86, CPFH_FirstPassHandler also invokes CLRVectoredExceptionHandler (for legacy purposes) that, in Phase3, will return EXCEPTION_CONTINUE_SEARCH for 
        //     BOOTUP_EXCEPTION_COMPLUS. This will result in CPFH_FirstPassHandler to simply return from the x86 personality routine without invoking CreateCOMPlusExceptionObject even if managed
        //     frames were present on the stack (as happens in PInvoke). Thus, there is no LTO setup for X86.
        //
        //     On X64, the personality routine does not invoke VEH but simply creates the exception tracker and will also create throwable and setup LTO if managed frames are present on the stack.
        //     But if there are no managed frames on the stack, then the managed personality routine may or may not get invoked (depending upon if any VM native function is present on the stack whose
        //     personality routine is the managed personality routine). Thus, we may have a case of LTO not being present on X64 as well, for this exception.
        //
        // Thus, when we see BOOTUP_EXCEPTION_COMPLUS, we will return back successfully (without doing anything) to imply a successful LTO validation. Eventually, a valid
        // throwable will be returned to the user of GET_THROWABLE (for details, trace the call to CLRException::GetThrowableFromException for CLRLastThrownObjectException type).
        //
        // This also ensures that the handling of BOOTUP_EXCEPTION_COMPLUS is now insync between the chk and fre builds in terms of the throwable returned.
    }
    else if (throwable == NULL)
    {   // If there isn't a LastThrownObject at all, that's a problem for GetLastThrownObject
        // We've lost track of the exception's type.  Raise an assert.  (This is configurable to allow
        //  stress labs to turn off the assert.)

        static int iSuppress = -1;
        if (iSuppress == -1) 
            iSuppress = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SuppressLostExceptionTypeAssert);
        if (!iSuppress)
        {   
            // Raising an assert message can  cause a mode violation.
            CONTRACT_VIOLATION(ModeViolation);

            // Use DbgAssertDialog to get the formatting right.
            DbgAssertDialog(__FILE__, __LINE__, 
                "The 'LastThrownObject' should not be, but is, NULL.\n"
                "The runtime may have lost track of the type of an exception in flight.\n"
                "Please get a good stack trace, find the caller of Validate, and file a bug against the owner.\n\n"
                "To suppress this assert 'set COMPlus_SuppressLostExceptionTypeAssert=1'");
        }
    }

    GCPROTECT_END();

    return this;
} // CLRLastThrownObjectException* CLRLastThrownObjectException::Validate()
#endif // _DEBUG

// ---------------------------------------------------------------------------
// Helper function to get an exception from outside the exception.  
//  Create and return a LastThrownObjectException.  Its virtual destructor
//  will clean up properly.
void GetLastThrownObjectExceptionFromThread_Internal(Exception **ppException)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    // If the Thread has been set up, then the LastThrownObject may make sense...
    if (GetThread())
    {
        // give back an object that knows about Threads and their exceptions.
        *ppException = new CLRLastThrownObjectException();
    }
    else
    {   
        // but if no Thread, don't pretend to know about LastThrownObject.
        *ppException = NULL;
    }

} // void GetLastThrownObjectExceptionFromThread_Internal()

#endif // CROSSGEN_COMPILE

//@TODO: Make available generally?
// Wrapper class to encapsulate both array pointer and element count.
template <typename T>
class ArrayReference
{
public:
    typedef T value_type;
    typedef const typename std::remove_const<T>::type const_value_type;

    typedef ArrayDPTR(value_type) array_type;
    typedef ArrayDPTR(const_value_type) const_array_type;

    // Constructor taking array pointer and size.
    ArrayReference(array_type array, size_t size)
        : _array(dac_cast<array_type>(array))
        , _size(size)
    { LIMITED_METHOD_CONTRACT; }

    // Constructor taking a statically sized array by reference.
    template <size_t N>
    ArrayReference(T (&array)[N])
        : _array(dac_cast<array_type>(&array[0]))
        , _size(N)
    { LIMITED_METHOD_CONTRACT; }

    // Copy constructor.
    ArrayReference(ArrayReference const & other)
        : _array(other._array)
        , _size(other._size)
    { LIMITED_METHOD_CONTRACT; }

    // Indexer
    template <typename IdxT>
    T & operator[](IdxT idx)
    { LIMITED_METHOD_CONTRACT; _ASSERTE(idx < _size); return _array[idx]; }

    // Implicit conversion operators.
    operator array_type()
    { LIMITED_METHOD_CONTRACT; return _array; }

    operator const_array_type() const
    { LIMITED_METHOD_CONTRACT; return dac_cast<const_array_type>(_array); }

    // Returns the array element count.
    size_t size() const
    { LIMITED_METHOD_CONTRACT; return _size; }

    // Iteration methods and types.
    typedef array_type iterator;

    iterator begin()
    { LIMITED_METHOD_CONTRACT; return _array; }

    iterator end()
    { LIMITED_METHOD_CONTRACT; return _array + _size; }

    typedef const_array_type const_iterator;

    const_iterator begin() const
    { LIMITED_METHOD_CONTRACT; return dac_cast<const_array_type>(_array); }

    const_iterator end() const
    { LIMITED_METHOD_CONTRACT; return dac_cast<const_array_type>(_array) + _size; }

private:
    array_type   _array;
    size_t       _size;
};

ArrayReference<const HRESULT> GetHRESULTsForExceptionKind(RuntimeExceptionKind kind)
{
    LIMITED_METHOD_CONTRACT;

    switch (kind)
    {
        #define DEFINE_EXCEPTION(ns, reKind, bHRformessage, ...)    \
            case k##reKind:                                         \
                return ArrayReference<const HRESULT>(s_##reKind##HRs);    \
                break;
        #define DEFINE_EXCEPTION_HR_WINRT_ONLY(ns, reKind, ...)
        #define DEFINE_EXCEPTION_IN_OTHER_FX_ASSEMBLY(ns, reKind, assemblySimpleName, publicKeyToken, bHRformessage, ...) DEFINE_EXCEPTION(ns, reKind, bHRformessage, __VA_ARGS__)
        #include "rexcep.h"

        default:
            _ASSERTE(!"Unknown exception kind!");
            break;
            
    }

    return ArrayReference<const HRESULT>(nullptr, 0);
}

bool IsHRESULTForExceptionKind(HRESULT hr, RuntimeExceptionKind kind)
{
    LIMITED_METHOD_CONTRACT;

    ArrayReference<const HRESULT> rgHR = GetHRESULTsForExceptionKind(kind);
    for (ArrayReference<const HRESULT>::iterator i = rgHR.begin(); i != rgHR.end(); ++i)
    {
        if (*i == hr)
        {
            return true;
        }
    }

    return false;
}