summaryrefslogtreecommitdiff
path: root/src/vm/object.h
blob: 5808e6c0eb6c28d852798e826715cd42987a657e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// OBJECT.H
//
// Definitions of a Com+ Object
// 

// See code:EEStartup#TableOfContents for overview


#ifndef _OBJECT_H_
#define _OBJECT_H_

#include "util.hpp"
#include "syncblk.h"
#include "gcdesc.h"
#include "specialstatics.h"
#include "sstring.h"
#include "daccess.h"
#include "fcall.h"

extern "C" void __fastcall ZeroMemoryInGCHeap(void*, size_t);

void ErectWriteBarrierForMT(MethodTable **dst, MethodTable *ref);

/*
 #ObjectModel 
 * COM+ Internal Object Model
 *
 *
 * Object              - This is the common base part to all COM+ objects
 *  |                        it contains the MethodTable pointer and the
 *  |                        sync block index, which is at a negative offset
 *  |
 *  +-- code:StringObject       - String objects are specialized objects for string
 *  |                        storage/retrieval for higher performance
 *  |
 *  +-- code:StringBufferObject - StringBuffer instance layout.  
 *  |
 *  +-- BaseObjectWithCachedData - Object Plus one object field for caching.
 *  |       |
 *  |            +-  ReflectClassBaseObject    - The base object for the RuntimeType class
 *  |            +-  ReflectMethodObject       - The base object for the RuntimeMethodInfo class
 *  |            +-  ReflectFieldObject        - The base object for the RtFieldInfo class
 *  |
 *  +-- code:ArrayBase          - Base portion of all arrays
 *  |       |
 *  |       +-  I1Array    - Base type arrays
 *  |       |   I2Array
 *  |       |   ...
 *  |       |
 *  |       +-  PtrArray   - Array of OBJECTREFs, different than base arrays because of pObjectClass
 *  |              
 *  +-- code:AppDomainBaseObject - The base object for the class AppDomain
 *  |              
 *  +-- code:AssemblyBaseObject - The base object for the class Assembly
 *  |
 *  +-- code:ContextBaseObject   - base object for class Context
 *
 *
 * PLEASE NOTE THE FOLLOWING WHEN ADDING A NEW OBJECT TYPE:
 *
 *    The size of the object in the heap must be able to be computed
 *    very, very quickly for GC purposes.   Restrictions on the layout
 *    of the object guarantee this is possible.
 *
 *    Any object that inherits from Object must be able to
 *    compute its complete size by using the first 4 bytes of
 *    the object following the Object part and constants
 *    reachable from the MethodTable...
 *
 *    The formula used for this calculation is:
 *        MT->GetBaseSize() + ((OBJECTTYPEREF->GetSizeField() * MT->GetComponentSize())
 *
 *    So for Object, since this is of fixed size, the ComponentSize is 0, which makes the right side
 *    of the equation above equal to 0 no matter what the value of GetSizeField(), so the size is just the base size.
 *
 */

// <TODO>
// @TODO:  #define COW         0x04     
// @TODO: MOO, MOO - no, not bovine, really Copy On Write bit for StringBuffer, requires 8 byte align MT
// @TODL: which we don't have yet</TODO>

class MethodTable;
class Thread;
class BaseDomain;
class Assembly;
class Context;
class CtxStaticData;
class DomainAssembly;
class AssemblyNative;
class WaitHandleNative;
class ArgDestination;

struct RCW;

#if CHECK_APP_DOMAIN_LEAKS

class Object;

class SetAppDomainAgilePendingTable
{
public:

    SetAppDomainAgilePendingTable ();
    ~SetAppDomainAgilePendingTable ();

    void PushReference (Object *pObject)
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_NOTRIGGER;

        PendingEntry entry;
        entry.pObject = pObject;

        m_Stack.Push(entry);
    }

    void PushParent (Object *pObject)
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_NOTRIGGER;

        PendingEntry entry;
        entry.pObject = (Object*)((size_t)pObject | 1);

        m_Stack.Push(entry);
    }

    Object *GetPendingObject (bool *pfReturnedToParent)
    {
        STATIC_CONTRACT_THROWS;
        STATIC_CONTRACT_GC_NOTRIGGER;

        if (!m_Stack.Count())
            return NULL;

        PendingEntry *pPending = m_Stack.Pop();

        *pfReturnedToParent = pPending->fMarked != 0;
        return (Object*)((size_t)pPending->pObject & ~1);
    }

private:

    union PendingEntry
    {
        Object *pObject;

        // Indicates whether the current thread set BIT_SBLK_AGILE_IN_PROGRESS
        // on the object.  Entries without this flag set are unexplored
        // objects.
        size_t fMarked:1;
    };

    CStackArray<PendingEntry> m_Stack;
};

#endif //CHECK_APP_DOMAIN_LEAKS


//
// The generational GC requires that every object be at least 12 bytes
// in size.   

#define MIN_OBJECT_SIZE     (2*sizeof(BYTE*) + sizeof(ObjHeader))

#define PTRALIGNCONST (DATA_ALIGNMENT-1)

#ifndef PtrAlign
#define PtrAlign(size) \
    ((size + PTRALIGNCONST) & (~PTRALIGNCONST))
#endif //!PtrAlign

// code:Object is the respesentation of an managed object on the GC heap.
//   
// See  code:#ObjectModel for some important subclasses of code:Object 
// 
// The only fields mandated by all objects are
// 
//     * a pointer to the code:MethodTable at offset 0
//     * a poiner to a code:ObjHeader at a negative offset. This is often zero.  It holds information that
//         any addition information that we might need to attach to arbitrary objects. 
// 
class Object
{
  protected:
    PTR_MethodTable m_pMethTab;

  protected:
    Object() { LIMITED_METHOD_CONTRACT; };
   ~Object() { LIMITED_METHOD_CONTRACT; };
   
  public:
    MethodTable *RawGetMethodTable() const
    {
        return m_pMethTab;
    }

#ifndef DACCESS_COMPILE
    void RawSetMethodTable(MethodTable *pMT)
    {
        LIMITED_METHOD_CONTRACT;
        m_pMethTab = pMT;
    }

    VOID SetMethodTable(MethodTable *pMT)
    { 
        LIMITED_METHOD_CONTRACT;
        m_pMethTab = pMT; 
    }

    VOID SetMethodTableForLargeObject(MethodTable *pMT)
    {
        // This function must be used if the allocation occurs on the large object heap, and the method table might be a collectible type
        WRAPPER_NO_CONTRACT;
        ErectWriteBarrierForMT(&m_pMethTab, pMT);
    }
 
#endif //!DACCESS_COMPILE

    // An object might be a proxy of some sort, with a thunking VTable.  If so, we can
    // advance to the true method table or class.
    BOOL            IsTransparentProxy()                        
    { 
#ifdef FEATURE_REMOTING
        WRAPPER_NO_CONTRACT;
        return( GetMethodTable()->IsTransparentProxy() );
#else
        LIMITED_METHOD_CONTRACT;
        return FALSE;
#endif
    }

#define MARKED_BIT 0x1

    PTR_MethodTable GetMethodTable() const              
    { 
        LIMITED_METHOD_DAC_CONTRACT;

#ifndef DACCESS_COMPILE
        // We should always use GetGCSafeMethodTable() if we're running during a GC. 
        // If the mark bit is set then we're running during a GC     
        _ASSERTE((dac_cast<TADDR>(m_pMethTab) & MARKED_BIT) == 0);

        return m_pMethTab;
#else //DACCESS_COMPILE

        //@dbgtodo dharvey Make this a type which supports bitwise and operations
        //when available
        return PTR_MethodTable((dac_cast<TADDR>(m_pMethTab)) & (~MARKED_BIT));
#endif //DACCESS_COMPILE
    }

    DPTR(PTR_MethodTable) GetMethodTablePtr() const
    {
        LIMITED_METHOD_CONTRACT;
        return dac_cast<DPTR(PTR_MethodTable)>(PTR_HOST_MEMBER_TADDR(Object, this, m_pMethTab));
    }

    MethodTable    *GetTrueMethodTable();
    
    TypeHandle      GetTypeHandle();
    TypeHandle      GetTrueTypeHandle();

        // Methods used to determine if an object supports a given interface.
    static BOOL     SupportsInterface(OBJECTREF pObj, MethodTable *pInterfaceMT);

    inline DWORD    GetNumComponents();
    inline SIZE_T   GetSize();

    CGCDesc*        GetSlotMap()                        
    { 
        WRAPPER_NO_CONTRACT;
        return( CGCDesc::GetCGCDescFromMT(GetMethodTable())); 
    }

    // Sync Block & Synchronization services

    // Access the ObjHeader which is at a negative offset on the object (because of
    // cache lines)
    PTR_ObjHeader   GetHeader()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<PTR_ObjHeader>(this) - 1;
    }

    // Get the current address of the object (works for debug refs, too.)
    PTR_BYTE      GetAddress()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return dac_cast<PTR_BYTE>(this);
    }

#ifdef _DEBUG
    // TRUE if the header has a real SyncBlockIndex (i.e. it has an entry in the
    // SyncTable, though it doesn't necessarily have an entry in the SyncBlockCache)
    BOOL HasEmptySyncBlockInfo()
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->HasEmptySyncBlockInfo();
    }
#endif

    // retrieve or allocate a sync block for this object
    SyncBlock *GetSyncBlock()
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->GetSyncBlock();
    }

    DWORD GetSyncBlockIndex()
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->GetSyncBlockIndex();
    }

#ifndef BINDER
    ADIndex GetAppDomainIndex();

    // Get app domain of object, or NULL if it is agile
    AppDomain *GetAppDomain();

#ifndef DACCESS_COMPILE
    // Set app domain of object to current domain.
    void SetAppDomain() { WRAPPER_NO_CONTRACT; SetAppDomain(::GetAppDomain()); }
#endif

    // Set app domain of object to given domain - it can only be set once
    void SetAppDomain(AppDomain *pDomain);
#endif // BINDER

#ifdef _DEBUG
#ifndef DACCESS_COMPILE
    // For SO-tolerance contract violation purposes, define these DEBUG_ versions to identify
    // the codepaths to SetAppDomain that are called only from DEBUG code.
    void DEBUG_SetAppDomain()
    {
        WRAPPER_NO_CONTRACT;

#ifndef BINDER
        DEBUG_SetAppDomain(::GetAppDomain());
#endif
    }
#endif //!DACCESS_COMPILE

    void DEBUG_SetAppDomain(AppDomain *pDomain);
#endif //_DEBUG
    
#if CHECK_APP_DOMAIN_LEAKS

    // Mark object as app domain agile
    BOOL SetAppDomainAgile(BOOL raiseAssert=TRUE, SetAppDomainAgilePendingTable *pTable = NULL);
    BOOL TrySetAppDomainAgile(BOOL raiseAssert=TRUE);

    // Mark sync block as app domain agile
    void SetSyncBlockAppDomainAgile();

    // Check if object is app domain agile
    BOOL IsAppDomainAgile();

    // Check if object is app domain agile
    BOOL IsAppDomainAgileRaw()
    {
        WRAPPER_NO_CONTRACT;

        SyncBlock *psb = PassiveGetSyncBlock();

        return (psb && psb->IsAppDomainAgile());
    }

    BOOL IsCheckedForAppDomainAgile()
    {
        WRAPPER_NO_CONTRACT;

        SyncBlock *psb = PassiveGetSyncBlock();
        return (psb && psb->IsCheckedForAppDomainAgile());
    }

    void SetIsCheckedForAppDomainAgile()
    {
        WRAPPER_NO_CONTRACT;

        SyncBlock *psb = PassiveGetSyncBlock();
        if (psb)
            psb->SetIsCheckedForAppDomainAgile();
    }

    // Check object to see if it is usable in the current domain 
    BOOL CheckAppDomain() { WRAPPER_NO_CONTRACT; return CheckAppDomain(::GetAppDomain()); }

    //Check object to see if it is usable in the given domain 
    BOOL CheckAppDomain(AppDomain *pDomain);

    // Check if the object's type is app domain agile
    BOOL IsTypeAppDomainAgile();

    // Check if the object's type is conditionally app domain agile
    BOOL IsTypeCheckAppDomainAgile();

    // Check if the object's type is naturally app domain agile
    BOOL IsTypeTypesafeAppDomainAgile();

    // Check if the object's type is possibly app domain agile
    BOOL IsTypeNeverAppDomainAgile();

    // Validate object & fields to see that it's usable from the current app domain
    BOOL ValidateAppDomain() { WRAPPER_NO_CONTRACT; return ValidateAppDomain(::GetAppDomain()); }

    // Validate object & fields to see that it's usable from any app domain
    BOOL ValidateAppDomainAgile() { WRAPPER_NO_CONTRACT; return ValidateAppDomain(NULL); }

    // Validate object & fields to see that it's usable from the given app domain (or null for agile)
    BOOL ValidateAppDomain(AppDomain *pAppDomain);

    // Validate fields to see that they are usable from the object's app domain 
    // (or from any domain if the object is agile)
    BOOL ValidateAppDomainFields() { WRAPPER_NO_CONTRACT; return ValidateAppDomainFields(GetAppDomain()); }

    // Validate fields to see that they are usable from the given app domain (or null for agile)
    BOOL ValidateAppDomainFields(AppDomain *pAppDomain);

    // Validate a value type's fields to see that it's usable from the current app domain
    static BOOL ValidateValueTypeAppDomain(MethodTable *pMT, void *base, BOOL raiseAssert = TRUE) 
      { WRAPPER_NO_CONTRACT; return ValidateValueTypeAppDomain(pMT, base, ::GetAppDomain(), raiseAssert); }

    // Validate a value type's fields to see that it's usable from any app domain
    static BOOL ValidateValueTypeAppDomainAgile(MethodTable *pMT, void *base, BOOL raiseAssert = TRUE) 
      { WRAPPER_NO_CONTRACT; return ValidateValueTypeAppDomain(pMT, base, NULL, raiseAssert); }

    // Validate a value type's fields to see that it's usable from the given app domain (or null for agile)
    static BOOL ValidateValueTypeAppDomain(MethodTable *pMT, void *base, AppDomain *pAppDomain, BOOL raiseAssert = TRUE);

    // Call when we are assigning this object to a dangerous field 
    // in an object in a given app domain (or agile if null)
    BOOL AssignAppDomain(AppDomain *pAppDomain, BOOL raiseAssert = TRUE);
    BOOL TryAssignAppDomain(AppDomain *pAppDomain, BOOL raiseAssert = TRUE);

    // Call when we are assigning to a dangerous value type field 
    // in an object in a given app domain (or agile if null)
    static BOOL AssignValueTypeAppDomain(MethodTable *pMT, void *base, AppDomain *pAppDomain, BOOL raiseAssert = TRUE);

#endif // CHECK_APP_DOMAIN_LEAKS

    // DO NOT ADD ANY ASSERTS TO THIS METHOD.
    // DO NOT USE THIS METHOD.
    // Yes folks, for better or worse the debugger pokes supposed object addresses 
    // to try to see if objects are valid, possibly firing an AccessViolation or worse,
    // and then catches the AV and reports a failure to the debug client.  This makes
    // the debugger slightly more robust should any corrupted object references appear
    // in a session. Thus it is "correct" behaviour for this to AV when used with 
    // an invalid object pointer, and incorrect behaviour for it to
    // assert.  
    BOOL ValidateObjectWithPossibleAV();

    // Validate an object ref out of the Promote routine in the GC
    void ValidatePromote(ScanContext *sc, DWORD flags);

    // Validate an object ref out of the VerifyHeap routine in the GC
    void ValidateHeap(Object *from, BOOL bDeep=TRUE);

    PTR_SyncBlock PassiveGetSyncBlock()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return GetHeader()->PassiveGetSyncBlock();
    }

    static DWORD ComputeHashCode();

#ifndef DACCESS_COMPILE    
    INT32 GetHashCodeEx();
#endif // #ifndef DACCESS_COMPILE
    
    // Synchronization
#ifndef DACCESS_COMPILE

    void EnterObjMonitor()
    {
        WRAPPER_NO_CONTRACT;
        GetHeader()->EnterObjMonitor();
    }

    BOOL TryEnterObjMonitor(INT32 timeOut = 0)
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->TryEnterObjMonitor(timeOut);
    }

    FORCEINLINE AwareLock::EnterHelperResult EnterObjMonitorHelper(Thread* pCurThread)
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->EnterObjMonitorHelper(pCurThread);
    }

    FORCEINLINE AwareLock::EnterHelperResult EnterObjMonitorHelperSpin(Thread* pCurThread)
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->EnterObjMonitorHelperSpin(pCurThread);
    }

    BOOL LeaveObjMonitor()
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->LeaveObjMonitor();
    }
    
    // should be called only from unwind code; used in the
    // case where EnterObjMonitor failed to allocate the
    // sync-object.
    BOOL LeaveObjMonitorAtException()
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->LeaveObjMonitorAtException();
    }

    FORCEINLINE AwareLock::LeaveHelperAction LeaveObjMonitorHelper(Thread* pCurThread)
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->LeaveObjMonitorHelper(pCurThread);
    }

    // Returns TRUE if the lock is owned and FALSE otherwise
    // threadId is set to the ID (Thread::GetThreadId()) of the thread which owns the lock
    // acquisitionCount is set to the number of times the lock needs to be released before
    // it is unowned
    BOOL GetThreadOwningMonitorLock(DWORD *pThreadId, DWORD *pAcquisitionCount)
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        return GetHeader()->GetThreadOwningMonitorLock(pThreadId, pAcquisitionCount);
    }

#endif // #ifndef DACCESS_COMPILE

    BOOL Wait(INT32 timeOut, BOOL exitContext)
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->Wait(timeOut, exitContext);
    }

    void Pulse()
    {
        WRAPPER_NO_CONTRACT;
        GetHeader()->Pulse();
    }

    void PulseAll()
    {
        WRAPPER_NO_CONTRACT;
        GetHeader()->PulseAll();
    }

   PTR_VOID UnBox();      // if it is a value class, get the pointer to the first field
  
    PTR_BYTE   GetData(void)
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;
        return dac_cast<PTR_BYTE>(this) + sizeof(Object);
    }

    static UINT GetOffsetOfFirstField()
    {
        LIMITED_METHOD_CONTRACT;
        return sizeof(Object);
    }

    DWORD   GetOffset32(DWORD dwOffset)
    { 
        WRAPPER_NO_CONTRACT;
        return * PTR_DWORD(GetData() + dwOffset);
    }

    USHORT  GetOffset16(DWORD dwOffset)
    { 
        WRAPPER_NO_CONTRACT;
        return * PTR_USHORT(GetData() + dwOffset);
    }

    BYTE    GetOffset8(DWORD dwOffset)
    { 
        WRAPPER_NO_CONTRACT;
        return * PTR_BYTE(GetData() + dwOffset);
    }

    __int64 GetOffset64(DWORD dwOffset)
    { 
        WRAPPER_NO_CONTRACT;
        return (__int64) * PTR_ULONG64(GetData() + dwOffset);
    }

    void *GetPtrOffset(DWORD dwOffset)
    {
        WRAPPER_NO_CONTRACT;
        return (void *)(TADDR)*PTR_TADDR(GetData() + dwOffset);
    }

#ifndef DACCESS_COMPILE
    
    void SetOffsetObjectRef(DWORD dwOffset, size_t dwValue);

    void SetOffsetPtr(DWORD dwOffset, LPVOID value)
    {
        WRAPPER_NO_CONTRACT;
        *(LPVOID *) &GetData()[dwOffset] = value;
    }
        
    void SetOffset32(DWORD dwOffset, DWORD dwValue)
    { 
        WRAPPER_NO_CONTRACT;
        *(DWORD *) &GetData()[dwOffset] = dwValue;
    }

    void SetOffset16(DWORD dwOffset, DWORD dwValue)
    { 
        WRAPPER_NO_CONTRACT;
        *(USHORT *) &GetData()[dwOffset] = (USHORT) dwValue;
    }

    void SetOffset8(DWORD dwOffset, DWORD dwValue)
    { 
        WRAPPER_NO_CONTRACT;
        *(BYTE *) &GetData()[dwOffset] = (BYTE) dwValue;
    }

    void SetOffset64(DWORD dwOffset, __int64 qwValue)
    { 
        WRAPPER_NO_CONTRACT;
        *(__int64 *) &GetData()[dwOffset] = qwValue;
    }

#endif // #ifndef DACCESS_COMPILE

    VOID            Validate(BOOL bDeep = TRUE, BOOL bVerifyNextHeader = TRUE, BOOL bVerifySyncBlock = TRUE);

    PTR_MethodTable GetGCSafeMethodTable() const
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;

        // lose GC marking bit and the pinning bit
        // A method table pointer should always be aligned.  During GC we set the least 
        // significant bit for marked objects and we set the second to least significant
        // bit for pinned objects.  So if we want the actual MT pointer during a GC
        // we must zero out the lowest 2 bits.
        return dac_cast<PTR_MethodTable>((dac_cast<TADDR>(m_pMethTab)) & ~((UINT_PTR)3));
    }

    // There are some cases where it is unsafe to get the type handle during a GC.
    // This occurs when the type has already been unloaded as part of an in-progress appdomain shutdown.
    TypeHandle GetGCSafeTypeHandleIfPossible() const;
    
    inline TypeHandle GetGCSafeTypeHandle() const;

#ifdef DACCESS_COMPILE
    void EnumMemoryRegions(void);
#endif
    
 private:
    VOID ValidateInner(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock);

#if CHECK_APP_DOMAIN_LEAKS
    friend class ObjHeader;
    BOOL SetFieldsAgile(BOOL raiseAssert = TRUE, SetAppDomainAgilePendingTable *pTable = NULL);
    static BOOL SetClassFieldsAgile(MethodTable *pMT, void *base, BOOL baseIsVT, BOOL raiseAssert = TRUE, SetAppDomainAgilePendingTable *pTable = NULL); 
    static BOOL ValidateClassFields(MethodTable *pMT, void *base, BOOL baseIsVT, AppDomain *pAppDomain, BOOL raiseAssert = TRUE);
    BOOL SetAppDomainAgileWorker(BOOL raiseAssert, SetAppDomainAgilePendingTable *pTable);
    BOOL ShouldCheckAppDomainAgile(BOOL raiseAssert, BOOL *pfResult);
#endif

};

/*
 * Object ref setting routines.  You must use these to do 
 * proper write barrier support, as well as app domain 
 * leak checking.
 *
 * Note that the AppDomain parameter is the app domain affinity
 * of the object containing the field or value class.  It should
 * be NULL if the containing object is app domain agile. Note that
 * you typically get this value by calling obj->GetAppDomain() on 
 * the containing object.
 */

// SetObjectReference sets an OBJECTREF field

void SetObjectReferenceUnchecked(OBJECTREF *dst,OBJECTREF ref);

#ifdef _DEBUG
void EnableStressHeapHelper();
#endif

//Used to clear the object reference
inline void ClearObjectReference(OBJECTREF* dst) 
{ 
    LIMITED_METHOD_CONTRACT;
    *(void**)(dst) = NULL; 
}

// CopyValueClass sets a value class field

void STDCALL CopyValueClassUnchecked(void* dest, void* src, MethodTable *pMT);
void STDCALL CopyValueClassArgUnchecked(ArgDestination *argDest, void* src, MethodTable *pMT, int destOffset);

inline void InitValueClass(void *dest, MethodTable *pMT)
{ 
    WRAPPER_NO_CONTRACT;
    ZeroMemoryInGCHeap(dest, pMT->GetNumInstanceFieldBytes());
}

// Initialize value class argument
void InitValueClassArg(ArgDestination *argDest, MethodTable *pMT);

#if CHECK_APP_DOMAIN_LEAKS

void SetObjectReferenceChecked(OBJECTREF *dst,OBJECTREF ref, AppDomain *pAppDomain);
void CopyValueClassChecked(void* dest, void* src, MethodTable *pMT, AppDomain *pAppDomain);
void CopyValueClassArgChecked(ArgDestination *argDest, void* src, MethodTable *pMT, AppDomain *pAppDomain, int destOffset);

#define SetObjectReference(_d,_r,_a)        SetObjectReferenceChecked(_d, _r, _a)
#define CopyValueClass(_d,_s,_m,_a)         CopyValueClassChecked(_d,_s,_m,_a)      
#define CopyValueClassArg(_d,_s,_m,_a,_o)   CopyValueClassArgChecked(_d,_s,_m,_a,_o)      

#else

#define SetObjectReference(_d,_r,_a)        SetObjectReferenceUnchecked(_d, _r)
#define CopyValueClass(_d,_s,_m,_a)         CopyValueClassUnchecked(_d,_s,_m)       
#define CopyValueClassArg(_d,_s,_m,_a,_o)   CopyValueClassArgUnchecked(_d,_s,_m,_o)       

#endif

#include <pshpack4.h>


// There are two basic kinds of array layouts in COM+
//      ELEMENT_TYPE_ARRAY  - a multidimensional array with lower bounds on the dims
//      ELMENNT_TYPE_SZARRAY - A zero based single dimensional array
//
// In addition the layout of an array in memory is also affected by
// whether the method table is shared (eg in the case of arrays of object refs)
// or not.  In the shared case, the array has to hold the type handle of
// the element type.  
//
// ArrayBase encapuslates all of these details.  In theory you should never
// have to peek inside this abstraction
//
class ArrayBase : public Object
{
    friend class GCHeap;
    friend class CObjectHeader;
    friend class Object;
    friend OBJECTREF AllocateArrayEx(TypeHandle arrayClass, INT32 *pArgs, DWORD dwNumArgs, BOOL bAllocateInLargeHeap DEBUG_ARG(BOOL bDontSetAppDomain)); 
    friend OBJECTREF FastAllocatePrimitiveArray(MethodTable* arrayType, DWORD cElements, BOOL bAllocateInLargeHeap);
    friend FCDECL2(Object*, JIT_NewArr1VC_MP_FastPortable, CORINFO_CLASS_HANDLE typeHnd_, INT_PTR size);
    friend FCDECL2(Object*, JIT_NewArr1OBJ_MP_FastPortable, CORINFO_CLASS_HANDLE typeHnd_, INT_PTR size);
    friend class JIT_TrialAlloc;
    friend class CheckAsmOffsets;
    friend struct _DacGlobals;

private:
    // This MUST be the first field, so that it directly follows Object.  This is because
    // Object::GetSize() looks at m_NumComponents even though it may not be an array (the
    // values is shifted out if not an array, so it's ok). 
    DWORD       m_NumComponents;
#ifdef _WIN64
    DWORD       pad;
#endif // _WIN64

    SVAL_DECL(INT32, s_arrayBoundsZero); // = 0

    // What comes after this conceputally is:
    // TypeHandle elementType;        Only present if the method table is shared among many types (arrays of pointers)
    // INT32      bounds[rank];       The bounds are only present for Multidimensional arrays   
    // INT32      lowerBounds[rank];  Valid indexes are lowerBounds[i] <= index[i] < lowerBounds[i] + bounds[i]

public:
    // Gets the unique type handle for this array object.
    // This will call the loader in don't-load mode - the allocator
    // always makes sure that the particular ArrayTypeDesc for this array
    // type is available before allocating any instances of this array type.
    inline TypeHandle GetTypeHandle() const;

    inline static TypeHandle GetTypeHandle(MethodTable * pMT);

    // Get the element type for the array, this works whether the the element
    // type is stored in the array or not
    inline TypeHandle GetArrayElementTypeHandle() const;

        // Get the CorElementType for the elements in the array.  Avoids creating a TypeHandle
    inline CorElementType GetArrayElementType() const;

    inline unsigned GetRank() const;

        // Total element count for the array
    inline DWORD GetNumComponents() const;

        // Get pointer to elements, handles any number of dimensions
    PTR_BYTE GetDataPtr(BOOL inGC = FALSE) const {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;
#ifdef _DEBUG
#ifndef DACCESS_COMPILE
        EnableStressHeapHelper();
#endif
#endif
        return dac_cast<PTR_BYTE>(this) +
                        GetDataPtrOffset(inGC ? GetGCSafeMethodTable() : GetMethodTable());
    }

    // The component size is actually 16-bit WORD, but this method is returning SIZE_T to ensure
    // that SIZE_T is used everywhere for object size computation. It is necessary to support
    // objects bigger than 2GB.
    SIZE_T GetComponentSize() const {
        WRAPPER_NO_CONTRACT;
        MethodTable * pMT;
#if CHECK_APP_DOMAIN_LEAKS
        pMT = GetGCSafeMethodTable();
#else
        pMT = GetMethodTable();
#endif //CHECK_APP_DOMAIN_LEAKS
        _ASSERTE(pMT->HasComponentSize());
        return pMT->RawGetComponentSize();
    }

        // Note that this can be a multidimensional array of rank 1 
        // (for example if we had a 1-D array with lower bounds
    BOOL IsMultiDimArray() const {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        return(GetMethodTable()->IsMultiDimArray());
    }

        // Get pointer to the begining of the bounds (counts for each dim)
        // Works for any array type 
    PTR_INT32 GetBoundsPtr() const {
        WRAPPER_NO_CONTRACT;
        MethodTable * pMT = GetMethodTable();
        if (pMT->IsMultiDimArray()) 
        {
            return dac_cast<PTR_INT32>(
                dac_cast<TADDR>(this) + sizeof(*this));
        }
        else
        {
            return dac_cast<PTR_INT32>(PTR_HOST_MEMBER_TADDR(ArrayBase, this,
                                                   m_NumComponents));
        }
    }

        // Works for any array type 
    PTR_INT32 GetLowerBoundsPtr() const {
        WRAPPER_NO_CONTRACT;
        if (IsMultiDimArray())
        {
            // Lower bounds info is after total bounds info
            // and total bounds info has rank elements
            return GetBoundsPtr() + GetRank();
        }
        else
            return dac_cast<PTR_INT32>(GVAL_ADDR(s_arrayBoundsZero));
    }

    static unsigned GetOffsetOfNumComponents() {
        LIMITED_METHOD_CONTRACT;
        return offsetof(ArrayBase, m_NumComponents);
    }

    inline static unsigned GetDataPtrOffset(MethodTable* pMT);

    inline static unsigned GetBoundsOffset(MethodTable* pMT);
    inline static unsigned GetLowerBoundsOffset(MethodTable* pMT);
};

//
// Template used to build all the non-object
// arrays of a single dimension
//

template < class KIND >
class Array : public ArrayBase
{
  public:
      
    typedef DPTR(KIND) PTR_KIND;
    typedef DPTR(const KIND) PTR_CKIND;

    KIND          m_Array[1];

    PTR_KIND        GetDirectPointerToNonObjectElements()
    { 
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        // return m_Array; 
        return PTR_KIND(GetDataPtr()); // This also handles arrays of dim 1 with lower bounds present

    }

    PTR_CKIND  GetDirectConstPointerToNonObjectElements() const
    { 
        WRAPPER_NO_CONTRACT;
        // return m_Array; 
        return PTR_CKIND(GetDataPtr()); // This also handles arrays of dim 1 with lower bounds present
    }
};


// Warning: Use PtrArray only for single dimensional arrays, not multidim arrays.
class PtrArray : public ArrayBase
{
    friend class GCHeap;
    friend class ClrDataAccess;
    friend OBJECTREF AllocateArrayEx(TypeHandle arrayClass, INT32 *pArgs, DWORD dwNumArgs, BOOL bAllocateInLargeHeap); 
    friend class JIT_TrialAlloc;
    friend class CheckAsmOffsets;

public:
    TypeHandle GetArrayElementTypeHandle()
    {
        LIMITED_METHOD_CONTRACT;
        return GetMethodTable()->GetApproxArrayElementTypeHandle();
    }

    static SIZE_T GetDataOffset()
    {
        LIMITED_METHOD_CONTRACT;
        return offsetof(PtrArray, m_Array);
    }

    void SetAt(SIZE_T i, OBJECTREF ref)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        _ASSERTE(i < GetNumComponents());
        SetObjectReference(m_Array + i, ref, GetAppDomain());
    }

    void ClearAt(SIZE_T i)
    {
        WRAPPER_NO_CONTRACT;
        _ASSERTE(i < GetNumComponents());
        ClearObjectReference(m_Array + i);
    }

    OBJECTREF GetAt(SIZE_T i)
    {
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;
        _ASSERTE(i < GetNumComponents());

// DAC doesn't know the true size of this array
// the compiler thinks it is size 1, but really it is size N hanging off the structure
#ifndef DACCESS_COMPILE
        return m_Array[i];
#else
        TADDR arrayTargetAddress = dac_cast<TADDR>(this) + offsetof(PtrArray, m_Array);
        __ArrayDPtr<OBJECTREF> targetArray = dac_cast< __ArrayDPtr<OBJECTREF> >(arrayTargetAddress);
        return targetArray[i];
#endif
    }

    friend class StubLinkerCPU;
#ifdef FEATURE_ARRAYSTUB_AS_IL
    friend class ArrayOpLinker;
#endif
public:
    OBJECTREF    m_Array[1];
};

/* a TypedByRef is a structure that is used to implement VB's BYREF variants.  
   it is basically a tuple of an address of some data along with a TypeHandle
   that indicates the type of the address */
class TypedByRef 
{
public:

    PTR_VOID data;
    TypeHandle type;  
};

typedef DPTR(TypedByRef) PTR_TypedByRef;

typedef Array<I1>   I1Array;
typedef Array<I2>   I2Array;
typedef Array<I4>   I4Array;
typedef Array<I8>   I8Array;
typedef Array<R4>   R4Array;
typedef Array<R8>   R8Array;
typedef Array<U1>   U1Array;
typedef Array<U1>   BOOLArray;
typedef Array<U2>   U2Array;
typedef Array<WCHAR>   CHARArray;
typedef Array<U4>   U4Array;
typedef Array<U8>   U8Array;
typedef PtrArray    PTRArray;  

typedef DPTR(I1Array)   PTR_I1Array;
typedef DPTR(I2Array)   PTR_I2Array;
typedef DPTR(I4Array)   PTR_I4Array;
typedef DPTR(I8Array)   PTR_I8Array;
typedef DPTR(R4Array)   PTR_R4Array;
typedef DPTR(R8Array)   PTR_R8Array;
typedef DPTR(U1Array)   PTR_U1Array;
typedef DPTR(BOOLArray) PTR_BOOLArray;
typedef DPTR(U2Array)   PTR_U2Array;
typedef DPTR(CHARArray) PTR_CHARArray;
typedef DPTR(U4Array)   PTR_U4Array;
typedef DPTR(U8Array)   PTR_U8Array;
typedef DPTR(PTRArray)  PTR_PTRArray;

class StringObject;

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ArrayBase>  BASEARRAYREF;
typedef REF<I1Array>    I1ARRAYREF;
typedef REF<I2Array>    I2ARRAYREF;
typedef REF<I4Array>    I4ARRAYREF;
typedef REF<I8Array>    I8ARRAYREF;
typedef REF<R4Array>    R4ARRAYREF;
typedef REF<R8Array>    R8ARRAYREF;
typedef REF<U1Array>    U1ARRAYREF;
typedef REF<BOOLArray>  BOOLARRAYREF;
typedef REF<U2Array>    U2ARRAYREF;
typedef REF<U4Array>    U4ARRAYREF;
typedef REF<U8Array>    U8ARRAYREF;
typedef REF<CHARArray>  CHARARRAYREF;
typedef REF<PTRArray>   PTRARRAYREF;  // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays.
typedef REF<StringObject> STRINGREF;

#else   // USE_CHECKED_OBJECTREFS

typedef PTR_ArrayBase   BASEARRAYREF;
typedef PTR_I1Array     I1ARRAYREF;
typedef PTR_I2Array     I2ARRAYREF;
typedef PTR_I4Array     I4ARRAYREF;
typedef PTR_I8Array     I8ARRAYREF;
typedef PTR_R4Array     R4ARRAYREF;
typedef PTR_R8Array     R8ARRAYREF;
typedef PTR_U1Array     U1ARRAYREF;
typedef PTR_BOOLArray   BOOLARRAYREF;
typedef PTR_U2Array     U2ARRAYREF;
typedef PTR_U4Array     U4ARRAYREF;
typedef PTR_U8Array     U8ARRAYREF;
typedef PTR_CHARArray   CHARARRAYREF;
typedef PTR_PTRArray    PTRARRAYREF;  // Warning: Use PtrArray only for single dimensional arrays, not multidim arrays.
typedef PTR_StringObject STRINGREF;

#endif // USE_CHECKED_OBJECTREFS


#include <poppack.h>


/*
 * StringObject
 *
 * Special String implementation for performance.   
 *
 *   m_ArrayLength  - Length of buffer (m_Characters) in number of WCHARs
 *   m_StringLength - Length of string in number of WCHARs, may be smaller
 *                    than the m_ArrayLength implying that there is extra
 *                    space at the end. The high two bits of this field are used
 *                    to indicate if the String has characters higher than 0x7F
 *   m_Characters   - The string buffer
 *
 */


/**
 *  The high bit state can be one of three value: 
 * STRING_STATE_HIGH_CHARS: We've examined the string and determined that it definitely has values greater than 0x80
 * STRING_STATE_FAST_OPS: We've examined the string and determined that it definitely has no chars greater than 0x80
 * STRING_STATE_UNDETERMINED: We've never examined this string.
 * We've also reserved another bit for future use.
 */

#define STRING_STATE_UNDETERMINED     0x00000000
#define STRING_STATE_HIGH_CHARS       0x40000000
#define STRING_STATE_FAST_OPS         0x80000000
#define STRING_STATE_SPECIAL_SORT     0xC0000000

#ifdef _MSC_VER
#pragma warning(disable : 4200)     // disable zero-sized array warning
#endif
class StringObject : public Object
{
#ifdef DACCESS_COMPILE
    friend class ClrDataAccess;
#endif
    friend class GCHeap;
    friend class JIT_TrialAlloc;
    friend class CheckAsmOffsets;
    friend class COMString;

  private:
    DWORD   m_StringLength;
    WCHAR   m_Characters[0];
    // GC will see a StringObject like this:
    //   DWORD m_StringLength
    //   WCHAR m_Characters[0]
    //   DWORD m_OptionalPadding (this is an optional field and will appear based on need)

  public:
    VOID    SetStringLength(DWORD len)                   { LIMITED_METHOD_CONTRACT; _ASSERTE(len >= 0); m_StringLength = len; }

  protected:
    StringObject() {LIMITED_METHOD_CONTRACT; }
   ~StringObject() {LIMITED_METHOD_CONTRACT; }
   
  public:
    static SIZE_T GetSize(DWORD stringLength);

    DWORD   GetStringLength()                           { LIMITED_METHOD_DAC_CONTRACT; return( m_StringLength );}
    WCHAR*  GetBuffer()                                 { LIMITED_METHOD_CONTRACT; _ASSERTE(this != nullptr); return (WCHAR*)( dac_cast<TADDR>(this) + offsetof(StringObject, m_Characters) );  }
    WCHAR*  GetBuffer(DWORD *pdwSize)                   { LIMITED_METHOD_CONTRACT; _ASSERTE((this != nullptr) && pdwSize); *pdwSize = GetStringLength(); return GetBuffer();  }
    WCHAR*  GetBufferNullable()                         { LIMITED_METHOD_CONTRACT; return( (this == nullptr) ? nullptr : (WCHAR*)( dac_cast<TADDR>(this) + offsetof(StringObject, m_Characters) ) );  }

    DWORD GetHighCharState() {
        WRAPPER_NO_CONTRACT;
        DWORD ret = GetHeader()->GetBits() & (BIT_SBLK_STRING_HIGH_CHAR_MASK);
        return ret;
    }

    VOID SetHighCharState(DWORD value) {
        WRAPPER_NO_CONTRACT;
        _ASSERTE(value==STRING_STATE_HIGH_CHARS || value==STRING_STATE_FAST_OPS 
                 || value==STRING_STATE_UNDETERMINED || value==STRING_STATE_SPECIAL_SORT);

        // you need to clear the present state before going to a new state, but we'll allow multiple threads to set it to the same thing.
        _ASSERTE((GetHighCharState() == STRING_STATE_UNDETERMINED) || (GetHighCharState()==value));    

        static_assert_no_msg(BIT_SBLK_STRING_HAS_NO_HIGH_CHARS == STRING_STATE_FAST_OPS && 
                 STRING_STATE_HIGH_CHARS == BIT_SBLK_STRING_HIGH_CHARS_KNOWN &&
                 STRING_STATE_SPECIAL_SORT == BIT_SBLK_STRING_HAS_SPECIAL_SORT);

        GetHeader()->SetBit(value);
    }

    static UINT GetBufferOffset()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return (UINT)(offsetof(StringObject, m_Characters));
    }
    static UINT GetStringLengthOffset()
    {
        LIMITED_METHOD_CONTRACT;
        return (UINT)(offsetof(StringObject, m_StringLength));
    }
    VOID    GetSString(SString &result)
    {
        WRAPPER_NO_CONTRACT;
        result.Set(GetBuffer(), GetStringLength());
    }
    //========================================================================
    // Creates a System.String object. All the functions that take a length
    // or a count of bytes will add the null terminator after length
    // characters. So this means that if you have a string that has 5
    // characters and the null terminator you should pass in 5 and NOT 6.
    //========================================================================
    static STRINGREF NewString(int length);
    static STRINGREF NewString(int length, BOOL bHasTrailByte);
    static STRINGREF NewString(const WCHAR *pwsz);
    static STRINGREF NewString(const WCHAR *pwsz, int length);
    static STRINGREF NewString(LPCUTF8 psz);
    static STRINGREF NewString(LPCUTF8 psz, int cBytes);

    static STRINGREF GetEmptyString();
    static STRINGREF* GetEmptyStringRefPtr();

    static STRINGREF* InitEmptyStringRefPtr();

    static STRINGREF __stdcall StringInitCharHelper(LPCSTR pszSource, int length);
    DWORD InternalCheckHighChars();

    BOOL HasTrailByte();
    BOOL GetTrailByte(BYTE *bTrailByte);
    BOOL SetTrailByte(BYTE bTrailByte);
    static BOOL CaseInsensitiveCompHelper(__in_ecount(aLength) WCHAR * strA, __in_z INT8 * strB, int aLength, int bLength, int *result);

#ifdef VERIFY_HEAP
    //has to use raw object to avoid recursive validation
    BOOL ValidateHighChars ();
#endif //VERIFY_HEAP

    /*=================RefInterpretGetStringValuesDangerousForGC======================
    **N.B.: This perfoms no range checking and relies on the caller to have done this.
    **Args: (IN)ref -- the String to be interpretted.
    **      (OUT)chars -- a pointer to the characters in the buffer.
    **      (OUT)length -- a pointer to the length of the buffer.
    **Returns: void.
    **Exceptions: None.
    ==============================================================================*/
    // !!!! If you use this function, you have to be careful because chars is a pointer
    // !!!! to the data buffer of ref.  If GC happens after this call, you need to make
    // !!!! sure that you have a pin handle on ref, or use GCPROTECT_BEGINPINNING on ref.
    void RefInterpretGetStringValuesDangerousForGC(__deref_out_ecount(*length + 1) WCHAR **chars, int *length) {
        WRAPPER_NO_CONTRACT;
    
        _ASSERTE(GetGCSafeMethodTable() == g_pStringClass);
        *length = GetStringLength();
        *chars  = GetBuffer();
#ifdef _DEBUG
        EnableStressHeapHelper();
#endif
    }


private:
    static INT32 FastCompareStringHelper(DWORD* strAChars, INT32 countA, DWORD* strBChars, INT32 countB);

    static STRINGREF* EmptyStringRefPtr;
};

//The first two macros are essentially the same.  I just define both because
//having both can make the code more readable.
#define IS_FAST_SORT(state) (((state) == STRING_STATE_FAST_OPS))
#define IS_SLOW_SORT(state) (((state) != STRING_STATE_FAST_OPS))

//This macro should be used to determine things like indexing, casing, and encoding.
#define IS_FAST_OPS_EXCEPT_SORT(state) (((state)==STRING_STATE_SPECIAL_SORT) || ((state)==STRING_STATE_FAST_OPS))
#define IS_ASCII(state) (((state)==STRING_STATE_SPECIAL_SORT) || ((state)==STRING_STATE_FAST_OPS))
#define IS_FAST_CASING(state) IS_ASCII(state)
#define IS_FAST_INDEX(state)  IS_ASCII(state)
#define IS_STRING_STATE_UNDETERMINED(state) ((state)==STRING_STATE_UNDETERMINED)
#define HAS_HIGH_CHARS(state) ((state)==STRING_STATE_HIGH_CHARS)

/*================================GetEmptyString================================
**Get a reference to the empty string.  If we haven't already gotten one, we
**query the String class for a pointer to the empty string that we know was
**created at startup.
**
**Args: None
**Returns: A STRINGREF to the EmptyString
**Exceptions: None
==============================================================================*/
inline STRINGREF StringObject::GetEmptyString() {

    CONTRACTL {
        THROWS;
        MODE_COOPERATIVE;
        GC_TRIGGERS;
    } CONTRACTL_END;
    STRINGREF* refptr = EmptyStringRefPtr;

    //If we've never gotten a reference to the EmptyString, we need to go get one.
    if (refptr==NULL) {
        refptr = InitEmptyStringRefPtr();
    }
    //We've already have a reference to the EmptyString, so we can just return it.
    return *refptr;
}

inline STRINGREF* StringObject::GetEmptyStringRefPtr() {

    CONTRACTL {
        THROWS;
        MODE_ANY;
        GC_TRIGGERS;
    } CONTRACTL_END;
    STRINGREF* refptr = EmptyStringRefPtr;

    //If we've never gotten a reference to the EmptyString, we need to go get one.
    if (refptr==NULL) {
        refptr = InitEmptyStringRefPtr();
    }
    //We've already have a reference to the EmptyString, so we can just return it.
    return refptr;
}

// This is used to account for the remoting cache on RuntimeType, 
// RuntimeMethodInfo, and RtFieldInfo.
class BaseObjectWithCachedData : public Object
{
#ifdef FEATURE_REMOTING
    protected:
        OBJECTREF  m_CachedData;
#endif //FEATURE_REMOTING
};

#ifndef BINDER
// This is the Class version of the Reflection object.
//  A Class has adddition information.
//  For a ReflectClassBaseObject the m_pData is a pointer to a FieldDesc array that
//      contains all of the final static primitives if its defined.
//  m_cnt = the number of elements defined in the m_pData FieldDesc array.  -1 means
//      this hasn't yet been defined.
class ReflectClassBaseObject : public BaseObjectWithCachedData
{
    friend class MscorlibBinder;

protected:
    OBJECTREF           m_keepalive;
    OBJECTREF           m_cache;
    TypeHandle          m_typeHandle;
#ifdef FEATURE_APPX
    UINT32              m_invocationFlags;
#endif

#ifdef _DEBUG
    void TypeCheck()
    {
        CONTRACTL
        {
            NOTHROW;
            MODE_COOPERATIVE;
            GC_NOTRIGGER;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        MethodTable *pMT = GetMethodTable();
        while (pMT != g_pRuntimeTypeClass && pMT != NULL)
        {
            pMT = pMT->GetParentMethodTable();
        }
        _ASSERTE(pMT == g_pRuntimeTypeClass);
    }
#endif // _DEBUG

public:
    void SetType(TypeHandle type) {
        CONTRACTL
        {
            NOTHROW;
            MODE_COOPERATIVE;
            GC_NOTRIGGER;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        INDEBUG(TypeCheck());
        m_typeHandle = type;
    }

    void SetKeepAlive(OBJECTREF keepalive)
    {
        CONTRACTL
        {
            NOTHROW;
            MODE_COOPERATIVE;
            GC_NOTRIGGER;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        INDEBUG(TypeCheck());
        SetObjectReference(&m_keepalive, keepalive, GetAppDomain());
    }

    TypeHandle GetType() {
        CONTRACTL
        {
            NOTHROW;
            MODE_COOPERATIVE;
            GC_NOTRIGGER;
            SO_TOLERANT;
        }
        CONTRACTL_END;

        INDEBUG(TypeCheck());
        return m_typeHandle;
    }

};
#endif // BINDER

// This is the Method version of the Reflection object.
//  A Method has adddition information.
//   m_pMD - A pointer to the actual MethodDesc of the method.
//   m_object - a field that has a reference type in it. Used only for RuntimeMethodInfoStub to keep the real type alive.
// This structure matches the structure up to the m_pMD for several different managed types. 
// (RuntimeConstructorInfo, RuntimeMethodInfo, and RuntimeMethodInfoStub). These types are unrelated in the type
// system except that they all implement a particular interface. It is important that that interface is not attached to any
// type that does not sufficiently match this data structure.
class ReflectMethodObject : public BaseObjectWithCachedData
{
    friend class MscorlibBinder;

protected:
    OBJECTREF           m_object;
    OBJECTREF           m_empty1;
    OBJECTREF           m_empty2;
    OBJECTREF           m_empty3;
    OBJECTREF           m_empty4;
    OBJECTREF           m_empty5;
    OBJECTREF           m_empty6;
    OBJECTREF           m_empty7;
    MethodDesc *        m_pMD;

public:
    void SetMethod(MethodDesc *pMethod) {
        LIMITED_METHOD_CONTRACT;
        m_pMD = pMethod;
    }

    // This must only be called on instances of ReflectMethodObject that are actually RuntimeMethodInfoStub
    void SetKeepAlive(OBJECTREF keepalive)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference(&m_object, keepalive, GetAppDomain());
    }

    MethodDesc *GetMethod() {
        LIMITED_METHOD_CONTRACT;
        return m_pMD;
    }

};

// This is the Field version of the Reflection object.
//  A Method has adddition information.
//   m_pFD - A pointer to the actual MethodDesc of the method.
//   m_object - a field that has a reference type in it. Used only for RuntimeFieldInfoStub to keep the real type alive.
// This structure matches the structure up to the m_pFD for several different managed types. 
// (RtFieldInfo and RuntimeFieldInfoStub). These types are unrelated in the type
// system except that they all implement a particular interface. It is important that that interface is not attached to any
// type that does not sufficiently match this data structure.
class ReflectFieldObject : public BaseObjectWithCachedData
{
    friend class MscorlibBinder;

protected:
    OBJECTREF           m_object;
    OBJECTREF           m_empty1;
    INT32               m_empty2;
    OBJECTREF           m_empty3;
    OBJECTREF           m_empty4;
    FieldDesc *         m_pFD;

public:
    void SetField(FieldDesc *pField) {
        LIMITED_METHOD_CONTRACT;
        m_pFD = pField;
    }

    // This must only be called on instances of ReflectFieldObject that are actually RuntimeFieldInfoStub
    void SetKeepAlive(OBJECTREF keepalive)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference(&m_object, keepalive, GetAppDomain());
    }

    FieldDesc *GetField() {
        LIMITED_METHOD_CONTRACT;
        return m_pFD;
    }
};

// ReflectModuleBaseObject 
// This class is the base class for managed Module.
//  This class will connect the Object back to the underlying VM representation
//  m_ReflectClass -- This is the real Class that was used for reflection
//      This class was used to get at this object
//  m_pData -- this is a generic pointer which usually points CorModule
//  
class ReflectModuleBaseObject : public Object
{
    friend class MscorlibBinder;

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.
    OBJECTREF          m_runtimeType;    
    OBJECTREF          m_runtimeAssembly;
    void*              m_ReflectClass;  // Pointer to the ReflectClass structure
    Module*            m_pData;         // Pointer to the Module
    void*              m_pGlobals;      // Global values....
    void*              m_pGlobalsFlds;  // Global Fields....

  protected:
    ReflectModuleBaseObject() {LIMITED_METHOD_CONTRACT;}
   ~ReflectModuleBaseObject() {LIMITED_METHOD_CONTRACT;}
   
  public:
    void SetModule(Module* p) {
        LIMITED_METHOD_CONTRACT;
        m_pData = p;
    }
    Module* GetModule() {
        LIMITED_METHOD_CONTRACT;
        return m_pData;
    }
    void SetAssembly(OBJECTREF assembly)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference(&m_runtimeAssembly, assembly, GetAppDomain());
    }
};

NOINLINE ReflectModuleBaseObject* GetRuntimeModuleHelper(LPVOID __me, Module *pModule, OBJECTREF keepAlive);
#define FC_RETURN_MODULE_OBJECT(pModule, refKeepAlive) FC_INNER_RETURN(ReflectModuleBaseObject*, GetRuntimeModuleHelper(__me, pModule, refKeepAlive))

class SafeHandle;

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<SafeHandle> SAFEHANDLE;
typedef REF<SafeHandle> SAFEHANDLEREF;
#else // USE_CHECKED_OBJECTREFS
typedef SafeHandle * SAFEHANDLE;
typedef SafeHandle * SAFEHANDLEREF;
#endif // USE_CHECKED_OBJECTREFS

class PermissionListSetObject: public Object
{
    friend class MscorlibBinder;

private:
    OBJECTREF _firstPermSetTriple;
    OBJECTREF _permSetTriples;
#ifdef FEATURE_COMPRESSEDSTACK
    OBJECTREF _zoneList;
    OBJECTREF _originList;
#endif // FEATURE_COMPRESSEDSTACK

public:
    BOOL IsEmpty() 
    {
        LIMITED_METHOD_CONTRACT;
        return (_firstPermSetTriple == NULL &&
                _permSetTriples == NULL
#ifdef FEATURE_COMPRESSEDSTACK
                && _zoneList == NULL &&
                _originList == NULL
#endif // FEATURE_COMPRESSEDSTACK
                );
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<PermissionListSetObject> PERMISSIONLISTSETREF;
#else
typedef PermissionListSetObject*     PERMISSIONLISTSETREF;
#endif
#ifdef FEATURE_COMPRESSEDSTACK
class CompressedStackObject: public Object
{
    friend class MscorlibBinder;

private:
    // These field are also defined in the managed representation.  (CompressedStack.cs)If you
    // add or change these field you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size. 
    PERMISSIONLISTSETREF m_pls;
    SAFEHANDLEREF m_compressedStackHandle;

public:
    void* GetUnmanagedCompressedStack();
    BOOL IsEmptyPLS() 
    {
        LIMITED_METHOD_CONTRACT;
        return (m_pls == NULL || m_pls->IsEmpty());
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<CompressedStackObject> COMPRESSEDSTACKREF;
#else
typedef CompressedStackObject*     COMPRESSEDSTACKREF;
#endif
#endif // #ifdef FEATURE_COMPRESSEDSTACK
    
#if defined(FEATURE_IMPERSONATION) || defined(FEATURE_COMPRESSEDSTACK)
class SecurityContextObject: public Object
{
    friend class MscorlibBinder;

private:
    
    // These field are also defined in the managed representation.  (SecurityContext.cs)If you
    // add or change these field you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size. 

    OBJECTREF               _executionContext;
#ifdef FEATURE_IMPERSONATION
    OBJECTREF               _windowsIdentity;
#endif // FEATURE_IMPERSONATION
#ifdef FEATURE_COMPRESSEDSTACK
    COMPRESSEDSTACKREF      _compressedStack;
#endif // FEATURE_COMPRESSEDSTACK
    INT32                   _disableFlow;
    CLR_BOOL                _isNewCapture;
public:
#ifdef FEATURE_COMPRESSEDSTACK    
    COMPRESSEDSTACKREF GetCompressedStack()
    {
        LIMITED_METHOD_CONTRACT;
        return _compressedStack;
    }
#endif // #ifdef FEATURE_COMPRESSEDSTACK
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<SecurityContextObject> SECURITYCONTEXTREF;
#else
typedef SecurityContextObject*     SECURITYCONTEXTREF;
#endif
#endif // #if defined(FEATURE_IMPERSONATION) || defined(FEATURE_COMPRESSEDSTACK)

#ifdef FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
#define SYNCCTXPROPS_REQUIRESWAITNOTIFICATION 0x1 // Keep in sync with SynchronizationContext.cs SynchronizationContextFlags
class ThreadBaseObject;
class SynchronizationContextObject: public Object
{
    friend class MscorlibBinder;
private:
    // These field are also defined in the managed representation.  (SecurityContext.cs)If you
    // add or change these field you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size. 
    INT32 _props;
public:
    BOOL IsWaitNotificationRequired()
    {
        LIMITED_METHOD_CONTRACT;
        if ((_props & SYNCCTXPROPS_REQUIRESWAITNOTIFICATION) != 0)
            return TRUE;
        return FALSE;
    }
};
#endif // FEATURE_SYNCHRONIZATIONCONTEXT_WAIT

#ifdef FEATURE_REMOTING
class CallContextRemotingDataObject : public Object
{
private:
    // These field are also defined in the managed representation.  (SecurityContext.cs)If you
    // add or change these field you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size. 
    OBJECTREF _logicalCallID;
public:
    OBJECTREF GetLogicalCallID()
    {
        LIMITED_METHOD_CONTRACT;
        return _logicalCallID;
    }
};

class CallContextSecurityDataObject : public Object
{
private:
    // These field are also defined in the managed representation.  (SecurityContext.cs)If you
    // add or change these field you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size. 
    OBJECTREF _principal;
public:
    OBJECTREF GetPrincipal()
    {
        LIMITED_METHOD_CONTRACT;
        return _principal;
    }

    void SetPrincipal(OBJECTREF ref)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReferenceUnchecked(&_principal, ref);
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<CallContextSecurityDataObject> CCSECURITYDATAREF;
typedef REF<CallContextRemotingDataObject> CCREMOTINGDATAREF;
#else
typedef CallContextSecurityDataObject*     CCSECURITYDATAREF;
typedef CallContextRemotingDataObject*     CCREMOTINGDATAREF;
#endif

class LogicalCallContextObject : public Object
{
    friend class MscorlibBinder;
    
    // These field are also defined in the managed representation.  (CallContext.cs) If you
    // add or change these field you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size.
private :
    OBJECTREF               m_Datastore;
    CCREMOTINGDATAREF       m_RemotingData;
    CCSECURITYDATAREF       m_SecurityData;
    OBJECTREF               m_HostContext;
    OBJECTREF               _sendHeaders;
    OBJECTREF               _recvHeaders;
    CLR_BOOL                m_IsCorrelationMgr;

public:
    CCSECURITYDATAREF GetSecurityData()
    {
        LIMITED_METHOD_CONTRACT;
        return m_SecurityData;
    }

    // This is an unmanaged equivalent of System.Runtime.Remoting.Messaging.LogicalCallContext.HasInfo
    BOOL ContainsDataForSerialization() 
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        return (ContainsNonSecurityDataForSerialization() ||
               (m_SecurityData != NULL && m_SecurityData->GetPrincipal() != NULL));
    }

    BOOL ContainsNonSecurityDataForSerialization() 
    {
        LIMITED_METHOD_CONTRACT;

        // m_Datastore may contain 0 items even if it's non-NULL in which case it does
        // not really contain any useful data for serialization and this function could
        // return FALSE. However we don't waste time trying to detect this case - it will
        // be reset to NULL the first time a call is made due to how LogicalCallContext's
        // ISerializable implementation works.
        return (m_Datastore != NULL ||
               (m_RemotingData != NULL && m_RemotingData->GetLogicalCallID() != NULL) ||
                m_HostContext != NULL);
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<LogicalCallContextObject> LOGICALCALLCONTEXTREF;
#else
typedef LogicalCallContextObject*     LOGICALCALLCONTEXTREF;
#endif

#endif // FEATURE_REMOTING

#ifndef FEATURE_CORECLR
class ExecutionContextObject : public Object
{
    friend class MscorlibBinder;
    
    // These fields are also defined in the managed representation.  (ExecutionContext.cs) If you
    // add or change these fields you must also change the managed code so that
    // it matches these.  This is necessary so that the object is the proper
    // size.
private :
#ifdef FEATURE_CAS_POLICY
    OBJECTREF               _hostExecutionContext;
#endif // FEATURE_CAS_POLICY
    OBJECTREF               _syncContext;
    OBJECTREF               _syncContextNoFlow;
#if defined(FEATURE_IMPERSONATION) || defined(FEATURE_COMPRESSEDSTACK)
    SECURITYCONTEXTREF      _securityContext;
#endif // #if defined(FEATURE_IMPERSONATION) || defined(FEATURE_COMPRESSEDSTACK)
#ifdef FEATURE_REMOTING
    LOGICALCALLCONTEXTREF   _logicalCallContext;
    OBJECTREF               _illogicalCallContext;
#endif // #ifdef FEATURE_REMOTING
    INT32                   _flags;
    OBJECTREF               _localValues;
    OBJECTREF               _localChangeNotifications;

public:
    OBJECTREF GetSynchronizationContext()
    {
        LIMITED_METHOD_CONTRACT;
        return _syncContext;
    }   
#if defined(FEATURE_IMPERSONATION) || defined(FEATURE_COMPRESSEDSTACK)    
    SECURITYCONTEXTREF GetSecurityContext()
    {
        LIMITED_METHOD_CONTRACT;
        return _securityContext;
    }
#endif // #if defined(FEATURE_IMPERSONATION) || defined(FEATURE_COMPRESSEDSTACK)
#ifdef FEATURE_REMOTING
    LOGICALCALLCONTEXTREF GetLogicalCallContext()
    {
        LIMITED_METHOD_CONTRACT;
        return _logicalCallContext;
    }
    void SetLogicalCallContext(LOGICALCALLCONTEXTREF ref)
    { 
        WRAPPER_NO_CONTRACT;
        SetObjectReferenceUnchecked((OBJECTREF*)&_logicalCallContext, (OBJECTREF)ref);
    }
    OBJECTREF GetIllogicalCallContext()
    {
        LIMITED_METHOD_CONTRACT;
        return _illogicalCallContext;
    }
    void SetIllogicalCallContext(OBJECTREF ref)
    { 
        WRAPPER_NO_CONTRACT;
        SetObjectReferenceUnchecked((OBJECTREF*)&_illogicalCallContext, ref);
    }
#endif //#ifdef FEATURE_REMOTING
#ifdef FEATURE_COMPRESSEDSTACK    
    COMPRESSEDSTACKREF GetCompressedStack()
    {
        WRAPPER_NO_CONTRACT;
        if (_securityContext != NULL)
            return _securityContext->GetCompressedStack();
        return NULL;
    }
#endif // #ifdef FEATURE_COMPRESSEDSTACK
        
};
#endif //FEATURE_CORECLR



typedef DPTR(class CultureInfoBaseObject) PTR_CultureInfoBaseObject;

#ifdef USE_CHECKED_OBJECTREFS
#ifdef FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
typedef REF<SynchronizationContextObject> SYNCHRONIZATIONCONTEXTREF;
#endif // FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
typedef REF<ExecutionContextObject> EXECUTIONCONTEXTREF;
typedef REF<CultureInfoBaseObject> CULTUREINFOBASEREF;
typedef REF<ArrayBase> ARRAYBASEREF;

#else
#ifdef FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
typedef SynchronizationContextObject*     SYNCHRONIZATIONCONTEXTREF;
#endif // FEATURE_SYNCHRONIZATIONCONTEXT_WAIT
#ifndef FEATURE_CORECLR
typedef ExecutionContextObject*     EXECUTIONCONTEXTREF;
#endif
typedef CultureInfoBaseObject*     CULTUREINFOBASEREF;
typedef PTR_ArrayBase ARRAYBASEREF;
#endif

// Note that the name must always be "" or "en-US".  Other cases and nulls
// aren't allowed (we already checked.)
__inline bool IsCultureEnglishOrInvariant(LPCWSTR localeName)
{
    LIMITED_METHOD_CONTRACT;
    if (localeName != NULL &&
        (localeName[0] == W('\0') ||
         wcscmp(localeName, W("en-US")) == 0))
    {
        return true;
    }
    return false;
    }

class CultureInfoBaseObject : public Object
{
    friend class MscorlibBinder;

private:
    OBJECTREF compareInfo;
    OBJECTREF textInfo;
#ifndef FEATURE_CORECLR
    OBJECTREF regionInfo;
#endif // !FEATURE_CORECLR
    OBJECTREF numInfo;
    OBJECTREF dateTimeInfo;
    OBJECTREF calendar;
    OBJECTREF m_cultureData;
#ifndef FEATURE_CORECLR
    OBJECTREF m_consoleFallbackCulture;
#endif // !FEATURE_CORECLR
    STRINGREF m_name;                       // "real" name - en-US, de-DE_phoneb or fj-FJ
    STRINGREF m_nonSortName;                // name w/o sort info (de-DE for de-DE_phoneb)
    STRINGREF m_sortName;                   // Sort only name (de-DE_phoneb, en-us for fj-fj (w/us sort)
    CULTUREINFOBASEREF m_parent;
#if !FEATURE_CORECLR
    INT32    iDataItem;                     // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
    INT32    iCultureID;                    // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
#endif // !FEATURE_CORECLR
#ifdef FEATURE_LEAK_CULTURE_INFO
    INT32 m_createdDomainID;
#endif // FEATURE_LEAK_CULTURE_INFO
    CLR_BOOL m_isReadOnly;
    CLR_BOOL m_isInherited;
#ifdef FEATURE_LEAK_CULTURE_INFO
    CLR_BOOL m_isSafeCrossDomain;
#endif // FEATURE_LEAK_CULTURE_INFO
#ifndef FEATURE_COREFX_GLOBALIZATION
    CLR_BOOL m_useUserOverride;
#endif

public:
    CULTUREINFOBASEREF GetParent()
    {
        LIMITED_METHOD_CONTRACT;
        return m_parent;
    }// GetParent


    STRINGREF GetName()
    {
        LIMITED_METHOD_CONTRACT;
        return m_name;
    }// GetName

#ifdef FEATURE_LEAK_CULTURE_INFO
    BOOL IsSafeCrossDomain()
    {
        return m_isSafeCrossDomain;
    }// IsSafeCrossDomain

    ADID GetCreatedDomainID()
    {
        return ADID(m_createdDomainID);
    }// GetCreatedDomain
#endif // FEATURE_LEAK_CULTURE_INFO

}; // class CultureInfoBaseObject


#ifndef FEATURE_COREFX_GLOBALIZATION
typedef DPTR(class CultureDataBaseObject) PTR_CultureDataBaseObject;
class CultureDataBaseObject : public Object
{
public:
        // offsets are for Silverlight
        /* 0x000 */ STRINGREF sRealName                ; // Name you passed in (ie: en-US, en, or de-DE_phoneb)
        /* 0x008 */ STRINGREF sWindowsName             ; // Name OS thinks the object is (ie: de-DE_phoneb, or en-US (even if en was passed in))       
        /* 0x010 */ STRINGREF sName                    ; // locale name (ie: en-us, NO sort info, but could be neutral)
        /* 0x012 */ STRINGREF sParent                  ; // Parent name (which may be a custom locale/culture)        
        /* 0x020 */ STRINGREF sLocalizedDisplayName    ; // Localized pretty name for this locale
        /* 0x028 */ STRINGREF sEnglishDisplayName      ; // English pretty name for this locale
        /* 0x030 */ STRINGREF sNativeDisplayName       ; // Native pretty name for this locale        
        /* 0x038 */ STRINGREF sSpecificCulture         ; // The culture name to be used in CultureInfo.CreateSpecificCulture(), en-US form if neutral, sort name if sort
        /* 0x040 */ STRINGREF sISO639Language          ; // ISO 639 Language Name
        /* 0x048 */ STRINGREF sLocalizedLanguage       ; // Localized name for this language
        /* 0x050 */ STRINGREF sEnglishLanguage         ; // English name for this language
        /* 0x058 */ STRINGREF sNativeLanguage          ; // Native name of this language
        /* 0x060 */ STRINGREF sRegionName              ; // (RegionInfo)        
        /* 0x068 */ STRINGREF sLocalizedCountry        ; // localized country name
        /* 0x070 */ STRINGREF sEnglishCountry          ; // english country name (RegionInfo)
        /* 0x078 */ STRINGREF sNativeCountry           ; // native country name
        /* 0x080 */ STRINGREF sISO3166CountryName      ; // (RegionInfo), ie: US
        /* 0x088 */ STRINGREF sPositiveSign            ; // (user can override) positive sign
        /* 0x090 */ STRINGREF sNegativeSign            ; // (user can override) negative sign

        /* 0x098 */ PTRARRAYREF saNativeDigits         ; // (user can override) native characters for digits 0-9
        /* 0x0a0 */ I4ARRAYREF  waGrouping             ; // (user can override) grouping of digits

        /* 0x0a8 */ STRINGREF sDecimalSeparator        ; // (user can override) decimal separator
        /* 0x0b0 */ STRINGREF sThousandSeparator       ; // (user can override) thousands separator
        /* 0x0b8 */ STRINGREF sNaN                     ; // Not a Number
        /* 0x0c0 */ STRINGREF sPositiveInfinity        ; // + Infinity
        /* 0x0c8 */ STRINGREF sNegativeInfinity        ; // - Infinity
        /* 0x0d0 */ STRINGREF sPercent                 ; // Percent (%) symbol
        /* 0x0d8 */ STRINGREF sPerMille                ; // PerMille (U+2030) symbol
        /* 0x0e0 */ STRINGREF sCurrency                ; // (user can override) local monetary symbol
        /* 0x0e8 */ STRINGREF sIntlMonetarySymbol      ; // international monetary symbol (RegionInfo)
        /* 0x0f0 */ STRINGREF sEnglishCurrency         ; // English name for this currency
        /* 0x0f8 */ STRINGREF sNativeCurrency          ; // Native name for this currency

        /* 0x100 */ I4ARRAYREF  waMonetaryGrouping     ; // (user can override) monetary grouping of digits

        /* 0x108 */ STRINGREF sMonetaryDecimal         ; // (user can override) monetary decimal separator
        /* 0x110 */ STRINGREF sMonetaryThousand        ; // (user can override) monetary thousands separator
        /* 0x118 */ STRINGREF sListSeparator           ; // (user can override) list separator       
        /* 0x120 */ STRINGREF sAM1159                  ; // (user can override) AM designator
        /* 0x128 */ STRINGREF sPM2359                  ; // (user can override) PM designator
                    STRINGREF sTimeSeparator           ; // Time Separator

        /* 0x130 */ PTRARRAYREF saLongTimes            ; // (user can override) time format
        /* 0x138 */ PTRARRAYREF saShortTimes           ; // short time format
        /* 0x140 */ PTRARRAYREF saDurationFormats      ; // time duration format 

        /* 0x148 */ I4ARRAYREF  waCalendars            ; // all available calendar type(s).  The first one is the default calendar

        /* 0x150 */ PTRARRAYREF calendars              ; // Store for specific calendar data

        /* 0x158 */ STRINGREF sTextInfo                ; // Text info name to use for custom
        /* 0x160 */ STRINGREF sCompareInfo             ; // Compare info name (including sorting key) to use if custom
        /* 0x168 */ STRINGREF sScripts                 ; // Typical Scripts for this locale (latn;cyrl; etc)

#if !defined(FEATURE_CORECLR)
        // desktop only fields - these are ordered correctly
        /* ????? */ STRINGREF sAbbrevLang              ; // abbreviated language name (Windows Language Name) ex: ENU
        /* ????? */ STRINGREF sAbbrevCountry           ; // abbreviated country name (RegionInfo) (Windows Region Name) ex: USA
        /* ????? */ STRINGREF sISO639Language2         ; // 3 char ISO 639 lang name 2 ex: eng
        /* ????? */ STRINGREF sISO3166CountryName2     ; // 3 char ISO 639 country name 2 2(RegionInfo) ex: USA (ISO)
        /* ????? */ STRINGREF sConsoleFallbackName     ; // The culture name for the console fallback UI culture
        /* ????? */ STRINGREF sKeyboardsToInstall      ; // Keyboard installation string.
        /* ????? */ STRINGREF fontSignature            ; // Font signature (16 WORDS)
#endif

// Unused for now:        /* ????? */ INT32    iCountry                  ; // (user can override) country code (RegionInfo)
        /* 0x170 */ INT32    iGeoId                    ; // GeoId
        /* 0x174 */ INT32    iDigitSubstitution        ; // (user can override) Digit substitution 0=context, 1=none/arabic, 2=Native/national (2 seems to be unused)
        /* 0x178 */ INT32    iLeadingZeros             ; // (user can override) leading zeros 0 = no leading zeros, 1 = leading zeros
        /* 0x17c */ INT32    iDigits                   ; // (user can override) number of fractional digits
        /* 0x180 */ INT32    iNegativeNumber           ; // (user can override) negative number format
        /* 0x184 */ INT32    iNegativePercent          ; // Negative Percent (0-3)
        /* 0x188 */ INT32    iPositivePercent          ; // Positive Percent (0-11)
        /* 0x18c */ INT32    iCurrencyDigits           ; // (user can override) # local monetary fractional digits
        /* 0x190 */ INT32    iCurrency                 ; // (user can override) positive currency format
        /* 0x194 */ INT32    iNegativeCurrency         ; // (user can override) negative currency format       
        /* 0x198 */ INT32    iMeasure                  ; // (user can override) system of measurement 0=metric, 1=US (RegionInfo)
// Unused for now        /* ????? */ INT32    iPaperSize                ; // default paper size (RegionInfo)
        /* 0x19c */ INT32    iFirstDayOfWeek           ; // (user can override) first day of week (gregorian really)
        /* 0x1a0 */ INT32    iFirstWeekOfYear          ; // (user can override) first week of year (gregorian really)

        /* ????? */ INT32    iReadingLayout; // Reading Layout Data (0-3)
#if !defined(FEATURE_CORECLR)
        // desktop only fields - these are ordered correctly
        /* ????? */ INT32    iDefaultAnsiCodePage      ; // default ansi code page ID (ACP)
        /* ????? */ INT32    iDefaultOemCodePage       ; // default oem code page ID (OCP or OEM)
        /* ????? */ INT32    iDefaultMacCodePage       ; // default macintosh code page
        /* ????? */ INT32    iDefaultEbcdicCodePage    ; // default EBCDIC code page
        /* ????? */ INT32    iLanguage                 ; // locale ID (0409) - NO sort information
        /* ????? */ INT32    iInputLanguageHandle      ; // input language handle
#endif
        /* 0x1a4 */ CLR_BOOL bUseOverrides             ; // use user overrides?
        /* 0x1a5 */ CLR_BOOL bNeutral                  ; // Flags for the culture (ie: neutral or not right now)        
#if !defined(FEATURE_CORECLR)
        /* ????? */ CLR_BOOL bWin32Installed           ; // Flags indicate if the culture is Win32 installed       
        /* ????? */ CLR_BOOL bFramework                ; // Flags for indicate if the culture is one of Whidbey cultures 
#endif

}; // class CultureDataBaseObject



typedef DPTR(class CalendarDataBaseObject) PTR_CalendarDataBaseObject;
class CalendarDataBaseObject : public Object
{
public:   
    /* 0x000 */ STRINGREF   sNativeName                 ; // Calendar Name for the locale
    
    // Formats
    
    /* 0x008 */ PTRARRAYREF saShortDates                ; // Short Data format, default first
    /* 0x010 */ PTRARRAYREF saYearMonths                ; // Year/Month Data format, default first
    /* 0x018 */ PTRARRAYREF saLongDates                 ; // Long Data format, default first
    /* 0x020 */ STRINGREF   sMonthDay                   ; // Month/Day format

    // Calendar Parts Names
    /* 0x028 */ PTRARRAYREF saEraNames                  ; // Names of Eras
    /* 0x030 */ PTRARRAYREF saAbbrevEraNames            ; // Abbreviated Era Names
    /* 0x038 */ PTRARRAYREF saAbbrevEnglishEraNames     ; // Abbreviated Era Names in English
    /* 0x040 */ PTRARRAYREF saDayNames                  ; // Day Names, null to use locale data, starts on Sunday
    /* 0x048 */ PTRARRAYREF saAbbrevDayNames            ; // Abbrev Day Names, null to use locale data, starts on Sunday
    /* 0x050 */ PTRARRAYREF saSuperShortDayNames        ; // Super short Day of week names
    /* 0x058 */ PTRARRAYREF saMonthNames                ; // Month Names (13)
    /* 0x060 */ PTRARRAYREF saAbbrevMonthNames          ; // Abbrev Month Names (13)
    /* 0x068 */ PTRARRAYREF saMonthGenitiveNames        ; // Genitive Month Names (13)
    /* 0x070 */ PTRARRAYREF saAbbrevMonthGenitiveNames  ; // Genitive Abbrev Month Names (13)
    /* 0x078 */ PTRARRAYREF saLeapYearMonthNames        ; // Multiple strings for the month names in a leap year.

    // Integers at end to make marshaller happier
    /* 0x080 */ INT32       iTwoDigitYearMax            ; // Max 2 digit year (for Y2K bug data entry)
    /* 0x084 */ INT32       iCurrentEra                 ; // current era # (usually 1)

    // Use overrides?
    /* 0x088 */ CLR_BOOL    bUseUserOverrides           ; // True if we want user overrides.
}; // class CalendarDataBaseObject
#endif


typedef DPTR(class ThreadBaseObject) PTR_ThreadBaseObject;
class ThreadBaseObject : public Object
{
    friend class ClrDataAccess;
    friend class ThreadNative;
    friend class MscorlibBinder;
    friend class Object;

private:

    // These field are also defined in the managed representation.  If you
    //  add or change these field you must also change the managed code so that
    //  it matches these.  This is necessary so that the object is the proper
    //  size.  The order here must match that order which the loader will choose
    //  when laying out the managed class.  Note that the layouts are checked
    //  at run time, not compile time.
#ifdef FEATURE_REMOTING    
    OBJECTREF     m_ExposedContext;
#endif    
#ifndef FEATURE_CORECLR
    EXECUTIONCONTEXTREF     m_ExecutionContext;
#endif
    OBJECTREF     m_Name;
    OBJECTREF     m_Delegate;
#ifdef FEATURE_LEAK_CULTURE_INFO
    CULTUREINFOBASEREF     m_CurrentUserCulture;
    CULTUREINFOBASEREF     m_CurrentUICulture;
#endif
#ifdef IO_CANCELLATION_ENABLED
    OBJECTREF     m_CancellationSignals;
#endif
    OBJECTREF     m_ThreadStartArg;

    // The next field (m_InternalThread) is declared as IntPtr in the managed
    // definition of Thread.  The loader will sort it next.

    // m_InternalThread is always valid -- unless the thread has finalized and been
    // resurrected.  (The thread stopped running before it was finalized).
    Thread       *m_InternalThread;
    INT32         m_Priority;    

    //We need to cache the thread id in managed code for perf reasons.
    INT32         m_ManagedThreadId;

    CLR_BOOL      m_ExecutionContextBelongsToCurrentScope;
#ifdef _DEBUG
    CLR_BOOL      m_ForbidExecutionContextMutation;
#endif

protected:
    // the ctor and dtor can do no useful work.
    ThreadBaseObject() {LIMITED_METHOD_CONTRACT;};
   ~ThreadBaseObject() {LIMITED_METHOD_CONTRACT;};

public:
    Thread   *GetInternal()
    {
        LIMITED_METHOD_CONTRACT;
        return m_InternalThread;
    }

    void SetInternal(Thread *it);
    void ClearInternal();

    INT32 GetManagedThreadId()
    {
        LIMITED_METHOD_CONTRACT;
        return m_ManagedThreadId;
    }

    void SetManagedThreadId(INT32 id)
    {
        LIMITED_METHOD_CONTRACT;
        m_ManagedThreadId = id;
    }

    OBJECTREF GetThreadStartArg() { LIMITED_METHOD_CONTRACT; return m_ThreadStartArg; }
    void SetThreadStartArg(OBJECTREF newThreadStartArg) 
    {
        WRAPPER_NO_CONTRACT;
    
        _ASSERTE(newThreadStartArg == NULL);
        // Note: this is an unchecked assignment.  We are cleaning out the ThreadStartArg field when 
        // a thread starts so that ADU does not cause problems
        SetObjectReferenceUnchecked( (OBJECTREF *)&m_ThreadStartArg, newThreadStartArg);
    
    }

    OBJECTREF GetDelegate()                   { LIMITED_METHOD_CONTRACT; return m_Delegate; }
    void      SetDelegate(OBJECTREF delegate);

#ifndef FEATURE_LEAK_CULTURE_INFO
    CULTUREINFOBASEREF GetCurrentUserCulture();
    CULTUREINFOBASEREF GetCurrentUICulture();
    OBJECTREF GetManagedThreadCulture(BOOL bUICulture);
    void ResetManagedThreadCulture(BOOL bUICulture);
    void ResetCurrentUserCulture();
    void ResetCurrentUICulture();
#endif

#ifdef FEATURE_REMOTING
    // These expose the remoting context (System\Remoting\Context)
    OBJECTREF GetExposedContext() { LIMITED_METHOD_CONTRACT; return m_ExposedContext; }
    OBJECTREF SetExposedContext(OBJECTREF newContext) 
    {
        WRAPPER_NO_CONTRACT;

        OBJECTREF oldContext = m_ExposedContext;

        // Note: this is a very dangerous unchecked assignment.  We are taking
        // responsibilty here for cleaning out the ExposedContext field when 
        // an app domain is unloaded.
        SetObjectReferenceUnchecked( (OBJECTREF *)&m_ExposedContext, newContext );

        return oldContext;
    }
#endif

#ifdef FEATURE_LEAK_CULTURE_INFO
    CULTUREINFOBASEREF GetCurrentUserCulture()
    { 
        LIMITED_METHOD_CONTRACT; 
        return m_CurrentUserCulture;
    }

    void ResetCurrentUserCulture()
    { 
        WRAPPER_NO_CONTRACT; 
        ClearObjectReference((OBJECTREF *)&m_CurrentUserCulture);
    }

    CULTUREINFOBASEREF GetCurrentUICulture() 
    { 
        LIMITED_METHOD_CONTRACT; 
        return m_CurrentUICulture;
    }

    void ResetCurrentUICulture()
    { 
        WRAPPER_NO_CONTRACT; 
        ClearObjectReference((OBJECTREF *)&m_CurrentUICulture);
    }
#endif // FEATURE_LEAK_CULTURE_INFO

#ifndef FEATURE_CORECLR
    OBJECTREF GetSynchronizationContext()
    {
        LIMITED_METHOD_CONTRACT; 
        if (m_ExecutionContext != NULL)
            return m_ExecutionContext->GetSynchronizationContext();
        return NULL;
    }
    OBJECTREF GetExecutionContext() 
    { 
        LIMITED_METHOD_CONTRACT; 
        return (OBJECTREF)m_ExecutionContext;
    }
    void SetExecutionContext(OBJECTREF ref)
    { 
        LIMITED_METHOD_CONTRACT;
        SetObjectReferenceUnchecked((OBJECTREF*)&m_ExecutionContext, ref);
    }
#endif //!FEATURE_CORECLR
#ifdef FEATURE_COMPRESSEDSTACK    
    COMPRESSEDSTACKREF GetCompressedStack()
    {
        WRAPPER_NO_CONTRACT;
        if (m_ExecutionContext != NULL)
            return m_ExecutionContext->GetCompressedStack();
        return NULL;
    }
#endif // #ifdef FEATURE_COMPRESSEDSTACK
    // SetDelegate is our "constructor" for the pathway where the exposed object is
    // created first.  InitExisting is our "constructor" for the pathway where an
    // existing physical thread is later exposed.
    void      InitExisting();

    void ResetCulture()
    {
        LIMITED_METHOD_CONTRACT;
        ResetCurrentUserCulture();
        ResetCurrentUICulture();
    }

    void ResetName()
    {
        LIMITED_METHOD_CONTRACT;
        m_Name = NULL;
    }
  
    void SetPriority(INT32 priority)
    {
        LIMITED_METHOD_CONTRACT;
        m_Priority = priority;
    }
    
    INT32 GetPriority() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_Priority;
    }
};

// MarshalByRefObjectBaseObject 
// This class is the base class for MarshalByRefObject
//  
class MarshalByRefObjectBaseObject : public Object
{
#ifdef FEATURE_REMOTING
    friend class MscorlibBinder;

  public:
    static int GetOffsetOfServerIdentity() { LIMITED_METHOD_CONTRACT; return offsetof(MarshalByRefObjectBaseObject, m_ServerIdentity); }

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.
    OBJECTREF     m_ServerIdentity;

  protected:
    MarshalByRefObjectBaseObject() {LIMITED_METHOD_CONTRACT;}
   ~MarshalByRefObjectBaseObject() {LIMITED_METHOD_CONTRACT;}   
#endif   
};


// ContextBaseObject 
// This class is the base class for Contexts
//  
class ContextBaseObject : public Object
{
    friend class Context;
    friend class MscorlibBinder;

  private:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.

    OBJECTREF m_ctxProps;   // array of name-value pairs of properties
    OBJECTREF m_dphCtx;     // dynamic property holder
    OBJECTREF m_localDataStore; // context local store
    OBJECTREF m_serverContextChain; // server context sink chain
    OBJECTREF m_clientContextChain; // client context sink chain
    OBJECTREF m_exposedAppDomain;       //appDomain ??
    PTRARRAYREF m_ctxStatics; // holder for context relative statics
    
    Context*  m_internalContext;            // Pointer to the VM context

    INT32 _ctxID;
    INT32 _ctxFlags;
    INT32 _numCtxProps;     // current count of properties

    INT32 _ctxStaticsCurrentBucket;
    INT32 _ctxStaticsFreeIndex;

  protected:
    ContextBaseObject() { LIMITED_METHOD_CONTRACT; }
   ~ContextBaseObject() { LIMITED_METHOD_CONTRACT; }
   
  public:

    void SetInternalContext(Context* pCtx) 
    {
        LIMITED_METHOD_CONTRACT;
        // either transitioning from NULL to non-NULL or vice versa.  
        // But not setting NULL to NULL or non-NULL to non-NULL.
        _ASSERTE((m_internalContext == NULL) != (pCtx == NULL));
        m_internalContext = pCtx;
    }
    
    Context* GetInternalContext() 
    {
        LIMITED_METHOD_CONTRACT;
        return m_internalContext;
    }

    OBJECTREF GetExposedDomain() { return m_exposedAppDomain; }
    OBJECTREF SetExposedDomain(OBJECTREF newDomain) 
    {
        LIMITED_METHOD_CONTRACT;
        OBJECTREF oldDomain = m_exposedAppDomain;
        SetObjectReference( (OBJECTREF *)&m_exposedAppDomain, newDomain, GetAppDomain() );
        return oldDomain;
    }

    PTRARRAYREF GetContextStaticsHolder() 
    { 
        LIMITED_METHOD_CONTRACT;
        SUPPORTS_DAC;
        // The code that needs this should have faulted it in by now!
        _ASSERTE(m_ctxStatics != NULL); 

        return m_ctxStatics; 
    }
};

typedef DPTR(ContextBaseObject) PTR_ContextBaseObject;

// AppDomainBaseObject 
// This class is the base class for application domains
//  
class AppDomainBaseObject : public MarshalByRefObjectBaseObject
{
    friend class AppDomain;
    friend class MscorlibBinder;

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.
    OBJECTREF    m_pDomainManager;     // AppDomainManager for host settings.
    OBJECTREF    m_LocalStore;
    OBJECTREF    m_FusionTable;
    OBJECTREF    m_pSecurityIdentity;  // Evidence associated with this domain
    OBJECTREF    m_pPolicies;          // Array of context policies associated with this domain
    OBJECTREF    m_pAssemblyEventHandler; // Delegate for 'loading assembly' event
    OBJECTREF    m_pTypeEventHandler;     // Delegate for 'resolve type' event
    OBJECTREF    m_pResourceEventHandler; // Delegate for 'resolve resource' event
    OBJECTREF    m_pAsmResolveEventHandler; // Delegate for 'resolve assembly' event
#ifdef FEATURE_REFLECTION_ONLY_LOAD
    OBJECTREF    m_pReflectionAsmResolveEventHandler; //Delegate for 'reflection resolve assembly' event
#endif    
#ifdef FEATURE_REMOTING
    OBJECTREF    m_pDefaultContext;     // Default managed context for this AD.
#endif    
#ifdef FEATURE_CLICKONCE
    OBJECTREF    m_pActivationContext;   // ClickOnce ActivationContext.
    OBJECTREF    m_pApplicationIdentity; // App ApplicationIdentity.
#endif    
    OBJECTREF    m_pApplicationTrust;    // App ApplicationTrust.
#ifdef FEATURE_IMPERSONATION
    OBJECTREF    m_pDefaultPrincipal;  // Lazily computed default principle object used by threads
#endif // FEATURE_IMPERSONATION
#ifdef FEATURE_REMOTING    
    OBJECTREF    m_pURITable;          // Identity table for remoting
#endif    
    OBJECTREF    m_pProcessExitEventHandler; // Delegate for 'process exit' event.  Only used in Default appdomain.
    OBJECTREF    m_pDomainUnloadEventHandler; // Delegate for 'about to unload domain' event
    OBJECTREF    m_pUnhandledExceptionEventHandler; // Delegate for 'unhandled exception' event
#ifdef FEATURE_APTCA
    OBJECTREF    m_aptcaVisibleAssemblies;  // array of conditional APTCA assembly names that should be APTCA visible
#endif

    OBJECTREF    m_compatFlags;

#ifdef FEATURE_EXCEPTION_NOTIFICATIONS
    OBJECTREF    m_pFirstChanceExceptionHandler; // Delegate for 'FirstChance Exception' event
#endif // FEATURE_EXCEPTION_NOTIFICATIONS

    AppDomain*   m_pDomain;            // Pointer to the BaseDomain Structure
#ifdef FEATURE_CAS_POLICY
    INT32        m_iPrincipalPolicy;   // Type of principal to create by default
#endif    
    CLR_BOOL     m_bHasSetPolicy;               // SetDomainPolicy has been called for this domain
    CLR_BOOL     m_bIsFastFullTrustDomain;      // We know for sure that this is a homogeneous full trust domain.  
    CLR_BOOL     m_compatFlagsInitialized;

  protected:
    AppDomainBaseObject() { LIMITED_METHOD_CONTRACT; }
   ~AppDomainBaseObject() { LIMITED_METHOD_CONTRACT; }
   
  public:

    void SetDomain(AppDomain* p) 
    {
        LIMITED_METHOD_CONTRACT;
        m_pDomain = p;
    }
    AppDomain* GetDomain() 
    {
        LIMITED_METHOD_CONTRACT;
        return m_pDomain;
    }

    OBJECTREF GetSecurityIdentity()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pSecurityIdentity;
    }

    OBJECTREF GetAppDomainManager()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pDomainManager;
    }

    OBJECTREF GetApplicationTrust()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pApplicationTrust;
    }

    BOOL GetIsFastFullTrustDomain()
    {
        LIMITED_METHOD_CONTRACT;
        return !!m_bIsFastFullTrustDomain;
    }

#ifdef FEATURE_APTCA
    OBJECTREF GetPartialTrustVisibleAssemblies()
    {
        LIMITED_METHOD_CONTRACT
        return m_aptcaVisibleAssemblies;
    }
#endif // FEATURE_APTCA

    // Ref needs to be a PTRARRAYREF
    void SetPolicies(OBJECTREF ref)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference(&m_pPolicies, ref, m_pDomain );
    }
#ifdef FEATURE_REMOTING
    void SetDefaultContext(OBJECTREF ref)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference(&m_pDefaultContext,ref,m_pDomain);
    }
#endif
    BOOL HasSetPolicy()
    {
        LIMITED_METHOD_CONTRACT;
        return m_bHasSetPolicy;
    }

#ifdef FEATURE_CLICKONCE
    BOOL HasActivationContext()
    {
        LIMITED_METHOD_CONTRACT;
        return m_pActivationContext != NULL;
    }
#endif // FEATURE_CLICKONCE

#ifdef FEATURE_EXCEPTION_NOTIFICATIONS
    // Returns the reference to the delegate of the first chance exception notification handler
    OBJECTREF GetFirstChanceExceptionNotificationHandler()
    {
        LIMITED_METHOD_CONTRACT;

        return m_pFirstChanceExceptionHandler;
    }
#endif // FEATURE_EXCEPTION_NOTIFICATIONS
};

#ifndef FEATURE_CORECLR
// The managed definition of AppDomainSortingSetupInfo is in BCL\System\Globalization\AppDomainSortingSetupInfo.cs
class AppDomainSortingSetupInfoObject : public Object
{
    friend class MscorlibBinder;

  protected:
    INT_PTR m_pfnIsNLSDefinedString;
    INT_PTR m_pfnCompareStringEx;
    INT_PTR m_pfnLCMapStringEx;
    INT_PTR m_pfnFindNLSStringEx;
    INT_PTR m_pfnCompareStringOrdinal;
    INT_PTR m_pfnGetNLSVersionEx;
    INT_PTR m_pfnFindStringOrdinal;
    CLR_BOOL m_useV2LegacySorting;
    CLR_BOOL m_useV4LegacySorting;

  protected:
    AppDomainSortingSetupInfoObject() { LIMITED_METHOD_CONTRACT; }
   ~AppDomainSortingSetupInfoObject() { LIMITED_METHOD_CONTRACT; }

  public:
    CLR_BOOL UseV2LegacySorting() { LIMITED_METHOD_CONTRACT; return m_useV2LegacySorting; }
    CLR_BOOL UseV4LegacySorting() { LIMITED_METHOD_CONTRACT; return m_useV4LegacySorting; }

    INT_PTR GetPFNIsNLSDefinedString() { LIMITED_METHOD_CONTRACT; return m_pfnIsNLSDefinedString; }
    INT_PTR GetPFNCompareStringEx() { LIMITED_METHOD_CONTRACT; return m_pfnCompareStringEx; }
    INT_PTR GetPFNLCMapStringEx() { LIMITED_METHOD_CONTRACT; return m_pfnLCMapStringEx; }
    INT_PTR GetPFNFindNLSStringEx() { LIMITED_METHOD_CONTRACT; return m_pfnFindNLSStringEx; }
    INT_PTR GetPFNCompareStringOrdinal() { LIMITED_METHOD_CONTRACT; return m_pfnCompareStringOrdinal; }
    INT_PTR GetPFNGetNLSVersionEx() { LIMITED_METHOD_CONTRACT; return m_pfnGetNLSVersionEx; }
    INT_PTR GetPFNFindStringOrdinal() { LIMITED_METHOD_CONTRACT; return m_pfnFindStringOrdinal; }
};
typedef DPTR(AppDomainSortingSetupInfoObject) PTR_AppDomainSortingSetupInfoObject;
#ifdef USE_CHECKED_OBJECTREFS
typedef REF<AppDomainSortingSetupInfoObject> APPDOMAINSORTINGSETUPINFOREF;
#else
typedef AppDomainSortingSetupInfoObject*     APPDOMAINSORTINGSETUPINFOREF;
#endif // USE_CHECKED_OBJECTREFS
#endif // FEATURE_CORECLR

// The managed definition of AppDomainSetup is in BCL\System\AppDomainSetup.cs
class AppDomainSetupObject : public Object
{
    friend class MscorlibBinder;

  protected:
    PTRARRAYREF m_Entries;
    STRINGREF m_AppBase;
    OBJECTREF m_AppDomainInitializer;
    PTRARRAYREF m_AppDomainInitializerArguments;
#ifdef FEATURE_CLICKONCE
    OBJECTREF m_ActivationArguments;
#endif // FEATURE_CLICKONCE
    STRINGREF m_ApplicationTrust;
    I1ARRAYREF m_ConfigurationBytes;
    STRINGREF m_AppDomainManagerAssembly;
    STRINGREF m_AppDomainManagerType;
#if FEATURE_APTCA
    PTRARRAYREF m_AptcaVisibleAssemblies;
#endif
    OBJECTREF m_CompatFlags;
    STRINGREF m_TargetFrameworkName;
#ifndef FEATURE_CORECLR
    APPDOMAINSORTINGSETUPINFOREF m_AppDomainSortingSetupInfo;
#endif // FEATURE_CORECLR
    INT32 m_LoaderOptimization;
#ifdef FEATURE_COMINTEROP
    CLR_BOOL m_DisableInterfaceCache;
#endif // FEATURE_COMINTEROP
    CLR_BOOL m_CheckedForTargetFrameworkName;
#ifdef FEATURE_RANDOMIZED_STRING_HASHING
    CLR_BOOL m_UseRandomizedStringHashing;
#endif


  protected:
    AppDomainSetupObject() { LIMITED_METHOD_CONTRACT; }
   ~AppDomainSetupObject() { LIMITED_METHOD_CONTRACT; }

  public:
#ifndef FEATURE_CORECLR
    APPDOMAINSORTINGSETUPINFOREF GetAppDomainSortingSetupInfo() { LIMITED_METHOD_CONTRACT; return m_AppDomainSortingSetupInfo; }
#endif // FEATURE_CORECLR
#ifdef FEATURE_RANDOMIZED_STRING_HASHING
    BOOL UseRandomizedStringHashing() { LIMITED_METHOD_CONTRACT; return (BOOL) m_UseRandomizedStringHashing; }
#endif // FEATURE_RANDOMIZED_STRING_HASHING
};
typedef DPTR(AppDomainSetupObject) PTR_AppDomainSetupObject;
#ifdef USE_CHECKED_OBJECTREFS
typedef REF<AppDomainSetupObject> APPDOMAINSETUPREF;
#else
typedef AppDomainSetupObject*     APPDOMAINSETUPREF;
#endif

// AssemblyBaseObject 
// This class is the base class for assemblies
//  
class AssemblyBaseObject : public Object
{
    friend class Assembly;
    friend class MscorlibBinder;

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.
    OBJECTREF     m_pModuleEventHandler;   // Delegate for 'resolve module' event
    STRINGREF     m_fullname;              // Slot for storing assemblies fullname
    OBJECTREF     m_pSyncRoot;             // Pointer to loader allocator to keep collectible types alive, and to serve as the syncroot for assembly building in ref.emit
    DomainAssembly* m_pAssembly;           // Pointer to the Assembly Structure
#ifdef FEATURE_APPX
    UINT32        m_flags;
#endif

  protected:
    AssemblyBaseObject() { LIMITED_METHOD_CONTRACT; }
   ~AssemblyBaseObject() { LIMITED_METHOD_CONTRACT; }
   
  public:

    void SetAssembly(DomainAssembly* p) 
    {
        LIMITED_METHOD_CONTRACT;
        m_pAssembly = p;
    }

    DomainAssembly* GetDomainAssembly() 
    {
        LIMITED_METHOD_CONTRACT;
        return m_pAssembly;
    }

    Assembly* GetAssembly();

    void SetSyncRoot(OBJECTREF pSyncRoot)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReferenceUnchecked(&m_pSyncRoot, pSyncRoot);
    }
};
NOINLINE AssemblyBaseObject* GetRuntimeAssemblyHelper(LPVOID __me, DomainAssembly *pAssembly, OBJECTREF keepAlive);
#define FC_RETURN_ASSEMBLY_OBJECT(pAssembly, refKeepAlive) FC_INNER_RETURN(AssemblyBaseObject*, GetRuntimeAssemblyHelper(__me, pAssembly, refKeepAlive))

// AssemblyNameBaseObject 
// This class is the base class for assembly names
//  
class AssemblyNameBaseObject : public Object
{
    friend class AssemblyNative;
    friend class AppDomainNative;
    friend class MscorlibBinder;

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.

    OBJECTREF     m_pSimpleName; 
    U1ARRAYREF    m_pPublicKey;
    U1ARRAYREF    m_pPublicKeyToken;
    OBJECTREF     m_pCultureInfo;
    OBJECTREF     m_pCodeBase;
    OBJECTREF     m_pVersion;
    OBJECTREF     m_StrongNameKeyPair;
#ifdef FEATURE_SERIALIZATION
    OBJECTREF     m_siInfo;
#endif
    U1ARRAYREF    m_HashForControl;
    DWORD         m_HashAlgorithm;
    DWORD         m_HashAlgorithmForControl;
    DWORD         m_VersionCompatibility;
    DWORD         m_Flags;

  protected:
    AssemblyNameBaseObject() { LIMITED_METHOD_CONTRACT; }
   ~AssemblyNameBaseObject() { LIMITED_METHOD_CONTRACT; }
   
  public:
    OBJECTREF GetSimpleName() { LIMITED_METHOD_CONTRACT; return m_pSimpleName; }
    U1ARRAYREF GetPublicKey() { LIMITED_METHOD_CONTRACT; return m_pPublicKey; }
    U1ARRAYREF GetPublicKeyToken() { LIMITED_METHOD_CONTRACT; return m_pPublicKeyToken; }
    OBJECTREF GetStrongNameKeyPair() { LIMITED_METHOD_CONTRACT; return m_StrongNameKeyPair; }
    OBJECTREF GetCultureInfo() { LIMITED_METHOD_CONTRACT; return m_pCultureInfo; }
    OBJECTREF GetAssemblyCodeBase() { LIMITED_METHOD_CONTRACT; return m_pCodeBase; }
    OBJECTREF GetVersion() { LIMITED_METHOD_CONTRACT; return m_pVersion; }
    DWORD GetAssemblyHashAlgorithm() { LIMITED_METHOD_CONTRACT; return m_HashAlgorithm; }
    DWORD GetFlags() { LIMITED_METHOD_CONTRACT; return m_Flags; }
    U1ARRAYREF GetHashForControl() { LIMITED_METHOD_CONTRACT; return m_HashForControl;}
    DWORD GetHashAlgorithmForControl() { LIMITED_METHOD_CONTRACT; return m_HashAlgorithmForControl; }
};

// VersionBaseObject
// This class is the base class for versions
//
class VersionBaseObject : public Object
{
    friend class MscorlibBinder;

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.

    int m_Major;
    int m_Minor;
    int m_Build;
    int m_Revision;
 
    VersionBaseObject() {LIMITED_METHOD_CONTRACT;}
   ~VersionBaseObject() {LIMITED_METHOD_CONTRACT;}

  public:    
    int GetMajor() { LIMITED_METHOD_CONTRACT; return m_Major; }
    int GetMinor() { LIMITED_METHOD_CONTRACT; return m_Minor; }
    int GetBuild() { LIMITED_METHOD_CONTRACT; return m_Build; }
    int GetRevision() { LIMITED_METHOD_CONTRACT; return m_Revision; }
};

// FrameSecurityDescriptorBaseObject 
// This class is the base class for the frame security descriptor
//  

class FrameSecurityDescriptorBaseObject : public Object
{
    friend class MscorlibBinder;

  protected:
    // READ ME:
    // Modifying the order or fields of this object may require other changes to the
    //  classlib class definition of this object.

    OBJECTREF       m_assertions;    // imperative
    OBJECTREF       m_denials;      // imperative
    OBJECTREF       m_restriction;  //  imperative
    OBJECTREF       m_DeclarativeAssertions;
    OBJECTREF       m_DeclarativeDenials;
    OBJECTREF       m_DeclarativeRestrictions;
#ifndef FEATURE_PAL
    SAFEHANDLEREF   m_callerToken; // the thread token (or process token if there was no thread token) when a call to Impersonate was made ("previous" token)
    SAFEHANDLEREF   m_impToken; // the thread token after a call to Impersonate is made (the "current" impersonation)
#endif // !FEATURE_PAL
    CLR_BOOL        m_assertFT;
    CLR_BOOL        m_assertAllPossible;
    CLR_BOOL        m_declSecComputed;
    


  protected:
    FrameSecurityDescriptorBaseObject() {LIMITED_METHOD_CONTRACT;}
   ~FrameSecurityDescriptorBaseObject() {LIMITED_METHOD_CONTRACT;}
   
  public:

    INT32 GetOverridesCount()
    {
        LIMITED_METHOD_CONTRACT;
        INT32 ret =0;
        if (m_restriction != NULL)
            ret++;
        if (m_denials != NULL)
            ret++;        
        if (m_DeclarativeDenials != NULL)
            ret++;
        if (m_DeclarativeRestrictions != NULL)
            ret++;
        return ret;
    }

    INT32 GetAssertCount()
    {
        LIMITED_METHOD_CONTRACT;
        INT32 ret =0;
        if (m_assertions != NULL || m_DeclarativeAssertions != NULL || HasAssertAllPossible())
            ret++;
        return ret;
    }  

    BOOL HasAssertFT()
    {
        LIMITED_METHOD_CONTRACT;
        return m_assertFT;
    }

    BOOL IsDeclSecComputed()
    {
        LIMITED_METHOD_CONTRACT;
        return m_declSecComputed;
    }

    BOOL HasAssertAllPossible()
    {
        LIMITED_METHOD_CONTRACT;
        return m_assertAllPossible;
    }

    OBJECTREF GetImperativeAssertions()
    {
        LIMITED_METHOD_CONTRACT;
        return m_assertions;
    }
   OBJECTREF GetDeclarativeAssertions()
    {
        LIMITED_METHOD_CONTRACT;
        return m_DeclarativeAssertions;
    }
    OBJECTREF GetImperativeDenials()
    {
        LIMITED_METHOD_CONTRACT;
        return m_denials;
    }
    OBJECTREF GetDeclarativeDenials()
    {
        LIMITED_METHOD_CONTRACT;
        return m_DeclarativeDenials;
    }
    OBJECTREF GetImperativeRestrictions()
    {
        LIMITED_METHOD_CONTRACT;
        return m_restriction;
    }
   OBJECTREF GetDeclarativeRestrictions()
    {
        LIMITED_METHOD_CONTRACT;
        return m_DeclarativeRestrictions;
    }
    void SetImperativeAssertions(OBJECTREF assertRef)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_assertions, assertRef, this->GetAppDomain());
    }
    void SetDeclarativeAssertions(OBJECTREF assertRef)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_DeclarativeAssertions, assertRef, this->GetAppDomain());
    }
    void SetImperativeDenials(OBJECTREF denialRef)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_denials, denialRef, this->GetAppDomain()); 
    }

    void SetDeclarativeDenials(OBJECTREF denialRef)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_DeclarativeDenials, denialRef, this->GetAppDomain()); 
    }

    void SetImperativeRestrictions(OBJECTREF restrictRef)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_restriction, restrictRef, this->GetAppDomain());
    }

    void SetDeclarativeRestrictions(OBJECTREF restrictRef)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_DeclarativeRestrictions, restrictRef, this->GetAppDomain());
    }
    void SetAssertAllPossible(BOOL assertAllPossible)
    {
        LIMITED_METHOD_CONTRACT;
        m_assertAllPossible = !!assertAllPossible;
    }
    
    void SetAssertFT(BOOL assertFT)
    {
        LIMITED_METHOD_CONTRACT;
        m_assertFT = !!assertFT;
    }
    void SetDeclSecComputed(BOOL declSec)
    {
        LIMITED_METHOD_CONTRACT;
        m_declSecComputed = !!declSec;
    }
    LPVOID GetCallerToken();
    LPVOID GetImpersonationToken();
};

#ifdef FEATURE_COMPRESSEDSTACK
class FrameSecurityDescriptorWithResolverBaseObject : public FrameSecurityDescriptorBaseObject
{
public:
    OBJECTREF m_resolver;

public:
    void SetDynamicMethodResolver(OBJECTREF resolver)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&m_resolver, resolver, this->GetAppDomain());
    }
};
#endif // FEATURE_COMPRESSEDSTACK

class WeakReferenceObject : public Object
{
public:
    Volatile<OBJECTHANDLE> m_Handle;
};

#ifdef USE_CHECKED_OBJECTREFS

typedef REF<ReflectModuleBaseObject> REFLECTMODULEBASEREF;

typedef REF<ReflectClassBaseObject> REFLECTCLASSBASEREF;

typedef REF<ReflectMethodObject> REFLECTMETHODREF;

typedef REF<ReflectFieldObject> REFLECTFIELDREF;

typedef REF<ThreadBaseObject> THREADBASEREF;

typedef REF<AppDomainBaseObject> APPDOMAINREF;

typedef REF<MarshalByRefObjectBaseObject> MARSHALBYREFOBJECTBASEREF;

typedef REF<ContextBaseObject> CONTEXTBASEREF;

typedef REF<AssemblyBaseObject> ASSEMBLYREF;

typedef REF<AssemblyNameBaseObject> ASSEMBLYNAMEREF;

typedef REF<VersionBaseObject> VERSIONREF;

typedef REF<FrameSecurityDescriptorBaseObject> FRAMESECDESCREF;

#ifdef FEATURE_COMPRESSEDSTACK
typedef REF<FrameSecurityDescriptorWithResolverBaseObject> FRAMESECDESWITHRESOLVERCREF;
#endif // FEATURE_COMPRESSEDSTACK

typedef REF<WeakReferenceObject> WEAKREFERENCEREF;

inline ARG_SLOT ObjToArgSlot(OBJECTREF objRef)
{
    LIMITED_METHOD_CONTRACT;
    LPVOID v;
    v = OBJECTREFToObject(objRef);
    return (ARG_SLOT)(SIZE_T)v;
}

inline OBJECTREF ArgSlotToObj(ARG_SLOT i)
{
    LIMITED_METHOD_CONTRACT;
    LPVOID v;
    v = (LPVOID)(SIZE_T)i;
    return ObjectToOBJECTREF ((Object*)v);
}

inline ARG_SLOT StringToArgSlot(STRINGREF sr)
{
    LIMITED_METHOD_CONTRACT;
    LPVOID v;
    v = OBJECTREFToObject(sr);
    return (ARG_SLOT)(SIZE_T)v;
}

inline STRINGREF ArgSlotToString(ARG_SLOT s)
{
    LIMITED_METHOD_CONTRACT;
    LPVOID v;
    v = (LPVOID)(SIZE_T)s;
    return ObjectToSTRINGREF ((StringObject*)v);
}

#else // USE_CHECKED_OBJECTREFS

typedef PTR_ReflectModuleBaseObject REFLECTMODULEBASEREF;
typedef PTR_ReflectClassBaseObject REFLECTCLASSBASEREF;
typedef PTR_ReflectMethodObject REFLECTMETHODREF;
typedef PTR_ReflectFieldObject REFLECTFIELDREF;
typedef PTR_ThreadBaseObject THREADBASEREF;
typedef PTR_AppDomainBaseObject APPDOMAINREF;
typedef PTR_AssemblyBaseObject ASSEMBLYREF;
typedef PTR_AssemblyNameBaseObject ASSEMBLYNAMEREF;
typedef PTR_ContextBaseObject CONTEXTBASEREF;

#ifndef DACCESS_COMPILE
typedef MarshalByRefObjectBaseObject* MARSHALBYREFOBJECTBASEREF;
typedef VersionBaseObject* VERSIONREF;
typedef FrameSecurityDescriptorBaseObject* FRAMESECDESCREF;

#ifdef FEATURE_COMPRESSEDSTACK
typedef FrameSecurityDescriptorWithResolverBaseObject* FRAMESECDESWITHRESOLVERCREF;
#endif // FEATURE_COMPRESSEDSTACK

typedef WeakReferenceObject* WEAKREFERENCEREF;
#endif // #ifndef DACCESS_COMPILE

#define ObjToArgSlot(objref) ((ARG_SLOT)(SIZE_T)(objref))
#define ArgSlotToObj(s) ((OBJECTREF)(SIZE_T)(s))

#define StringToArgSlot(objref) ((ARG_SLOT)(SIZE_T)(objref))
#define ArgSlotToString(s)    ((STRINGREF)(SIZE_T)(s))

#endif //USE_CHECKED_OBJECTREFS

#define PtrToArgSlot(ptr) ((ARG_SLOT)(SIZE_T)(ptr))
#define ArgSlotToPtr(s)   ((LPVOID)(SIZE_T)(s))

#define BoolToArgSlot(b)  ((ARG_SLOT)(CLR_BOOL)(!!(b)))
#define ArgSlotToBool(s)  ((BOOL)(s))

STRINGREF AllocateString(SString sstr);
CHARARRAYREF AllocateCharArray(DWORD dwArrayLength);


class TransparentProxyObject : public Object
{
    friend class MscorlibBinder;
    friend class CheckAsmOffsets;

public:
    MethodTable * GetMethodTableBeingProxied()
    {
        LIMITED_METHOD_CONTRACT;
        return _pMT;
    }
    void SetMethodTableBeingProxied(MethodTable * pMT)
    {
        LIMITED_METHOD_CONTRACT;
        _pMT = pMT;
    }

    MethodTable * GetInterfaceMethodTable()
    {
        LIMITED_METHOD_CONTRACT;
        return _pInterfaceMT;
    }
    void SetInterfaceMethodTable(MethodTable * pInterfaceMT)
    {
        LIMITED_METHOD_CONTRACT;
        _pInterfaceMT = pInterfaceMT;
    }

    void * GetStub()
    {
        LIMITED_METHOD_CONTRACT;
        return _stub;
    }
    void SetStub(void * pStub)
    {
        LIMITED_METHOD_CONTRACT;
        _stub = pStub;
    }

    OBJECTREF GetStubData()
    {
        LIMITED_METHOD_CONTRACT;
        return _stubData;
    }
    void SetStubData(OBJECTREF stubData)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&_stubData, stubData, GetAppDomain());
    }

    OBJECTREF GetRealProxy()
    {
        LIMITED_METHOD_CONTRACT;
        return _rp;
    }
    void SetRealProxy(OBJECTREF realProxy)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&_rp, realProxy, GetAppDomain());
    }

    static int GetOffsetOfRP() { LIMITED_METHOD_CONTRACT; return offsetof(TransparentProxyObject, _rp); }
    
protected:
    TransparentProxyObject()
    {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly
    ~TransparentProxyObject(){LIMITED_METHOD_CONTRACT;};

private:
    OBJECTREF       _rp;
    OBJECTREF       _stubData;
    MethodTable*    _pMT;
    MethodTable*    _pInterfaceMT;
    void*           _stub;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<TransparentProxyObject> TRANSPARENTPROXYREF;
#else
typedef TransparentProxyObject*     TRANSPARENTPROXYREF;
#endif


class RealProxyObject : public Object
{
    friend class MscorlibBinder;

public:
    DWORD GetOptFlags()
    {
        LIMITED_METHOD_CONTRACT;
        return _optFlags;
    }
    VOID SetOptFlags(DWORD flags)
    {
        LIMITED_METHOD_CONTRACT;
        _optFlags = flags;
    }

    DWORD GetDomainID()
    {
        LIMITED_METHOD_CONTRACT;
        return _domainID;
    }

    TRANSPARENTPROXYREF GetTransparentProxy()
    {
        LIMITED_METHOD_CONTRACT;
        return (TRANSPARENTPROXYREF&)_tp;
    }
    void SetTransparentProxy(TRANSPARENTPROXYREF tp)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReference(&_tp, (OBJECTREF)tp, GetAppDomain());
    }

    static int GetOffsetOfIdentity() { LIMITED_METHOD_CONTRACT; return offsetof(RealProxyObject, _identity); }
    static int GetOffsetOfServerObject() { LIMITED_METHOD_CONTRACT; return offsetof(RealProxyObject, _serverObject); }
    static int GetOffsetOfServerIdentity() { LIMITED_METHOD_CONTRACT; return offsetof(RealProxyObject, _srvIdentity); }

protected:
    RealProxyObject()
    {
        LIMITED_METHOD_CONTRACT;
    }; // don't instantiate this class directly
    ~RealProxyObject(){ LIMITED_METHOD_CONTRACT; };

private:
    OBJECTREF       _tp;
    OBJECTREF       _identity;
    OBJECTREF       _serverObject;
    DWORD           _flags;
    DWORD           _optFlags;
    DWORD           _domainID;
    OBJECTHANDLE    _srvIdentity;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<RealProxyObject> REALPROXYREF;
#else
typedef RealProxyObject*     REALPROXYREF;
#endif


#ifndef CLR_STANDALONE_BINDER
#ifdef FEATURE_COMINTEROP

//-------------------------------------------------------------
// class ComObject, Exposed class __ComObject
// 
// 
//-------------------------------------------------------------
class ComObject : public MarshalByRefObjectBaseObject
{
    friend class MscorlibBinder;

protected:

    ComObject()
    {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly
    ~ComObject(){LIMITED_METHOD_CONTRACT;};

public:
    OBJECTREF           m_ObjectToDataMap;

    //--------------------------------------------------------------------
    // SupportsInterface
    static BOOL SupportsInterface(OBJECTREF oref, MethodTable* pIntfTable);

    //--------------------------------------------------------------------
    // SupportsInterface
    static void ThrowInvalidCastException(OBJECTREF *pObj, MethodTable* pCastToMT);

    //-----------------------------------------------------------------
    // GetComIPFromRCW
    static IUnknown* GetComIPFromRCW(OBJECTREF *pObj, MethodTable* pIntfTable);

    //-----------------------------------------------------------------
    // GetComIPFromRCWThrowing
    static IUnknown* GetComIPFromRCWThrowing(OBJECTREF *pObj, MethodTable* pIntfTable);

    //-----------------------------------------------------------
    // create an empty ComObjectRef
    static OBJECTREF CreateComObjectRef(MethodTable* pMT);

    //-----------------------------------------------------------
    // Release all the data associated with the __ComObject.
    static void ReleaseAllData(OBJECTREF oref);

    //-----------------------------------------------------------
    // Redirection for ToString
    static FCDECL1(MethodDesc *, GetRedirectedToStringMD, Object *pThisUNSAFE);
    static FCDECL2(StringObject *, RedirectToString, Object *pThisUNSAFE, MethodDesc *pToStringMD);    

    //-----------------------------------------------------------
    // Redirection for GetHashCode
    static FCDECL1(MethodDesc *, GetRedirectedGetHashCodeMD, Object *pThisUNSAFE);
    static FCDECL2(int, RedirectGetHashCode, Object *pThisUNSAFE, MethodDesc *pGetHashCodeMD);    

    //-----------------------------------------------------------
    // Redirection for Equals
    static FCDECL1(MethodDesc *, GetRedirectedEqualsMD, Object *pThisUNSAFE);
    static FCDECL3(FC_BOOL_RET, RedirectEquals, Object *pThisUNSAFE, Object *pOtherUNSAFE, MethodDesc *pEqualsMD);    
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ComObject> COMOBJECTREF;
#else
typedef ComObject*     COMOBJECTREF;
#endif


//-------------------------------------------------------------
// class UnknownWrapper, Exposed class UnknownWrapper
// 
// 
//-------------------------------------------------------------
class UnknownWrapper : public Object
{
protected:

    UnknownWrapper(UnknownWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction.
    UnknownWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly
    ~UnknownWrapper() {LIMITED_METHOD_CONTRACT;};

    OBJECTREF m_WrappedObject;

public:
    OBJECTREF GetWrappedObject()
    {
        LIMITED_METHOD_CONTRACT;
        return m_WrappedObject;
    }

    void SetWrappedObject(OBJECTREF pWrappedObject)
    {
        LIMITED_METHOD_CONTRACT;
        m_WrappedObject = pWrappedObject;
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<UnknownWrapper> UNKNOWNWRAPPEROBJECTREF;
#else
typedef UnknownWrapper*     UNKNOWNWRAPPEROBJECTREF;
#endif


//-------------------------------------------------------------
// class DispatchWrapper, Exposed class DispatchWrapper
// 
// 
//-------------------------------------------------------------
class DispatchWrapper : public Object
{
protected:

    DispatchWrapper(DispatchWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction.
    DispatchWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly
    ~DispatchWrapper() {LIMITED_METHOD_CONTRACT;};

    OBJECTREF m_WrappedObject;

public:
    OBJECTREF GetWrappedObject()
    {
        LIMITED_METHOD_CONTRACT;
        return m_WrappedObject;
    }

    void SetWrappedObject(OBJECTREF pWrappedObject)
    {
        LIMITED_METHOD_CONTRACT;
        m_WrappedObject = pWrappedObject;
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<DispatchWrapper> DISPATCHWRAPPEROBJECTREF;
#else
typedef DispatchWrapper*     DISPATCHWRAPPEROBJECTREF;
#endif


//-------------------------------------------------------------
// class VariantWrapper, Exposed class VARIANTWRAPPEROBJECTREF
// 
// 
//-------------------------------------------------------------
class VariantWrapper : public Object
{
protected:

    VariantWrapper(VariantWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction.
    VariantWrapper() {LIMITED_METHOD_CONTRACT}; // don't instantiate this class directly
    ~VariantWrapper() {LIMITED_METHOD_CONTRACT};

    OBJECTREF m_WrappedObject;

public:
    OBJECTREF GetWrappedObject()
    {
        LIMITED_METHOD_CONTRACT;
        return m_WrappedObject;
    }

    void SetWrappedObject(OBJECTREF pWrappedObject)
    {
        LIMITED_METHOD_CONTRACT;
        m_WrappedObject = pWrappedObject;
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<VariantWrapper> VARIANTWRAPPEROBJECTREF;
#else
typedef VariantWrapper*     VARIANTWRAPPEROBJECTREF;
#endif


//-------------------------------------------------------------
// class ErrorWrapper, Exposed class ErrorWrapper
// 
// 
//-------------------------------------------------------------
class ErrorWrapper : public Object
{
protected:

    ErrorWrapper(ErrorWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction.
    ErrorWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly
    ~ErrorWrapper() {LIMITED_METHOD_CONTRACT;};

    INT32 m_ErrorCode;

public:
    INT32 GetErrorCode()
    {
        LIMITED_METHOD_CONTRACT;
        return m_ErrorCode;
    }

    void SetErrorCode(int ErrorCode)
    {
        LIMITED_METHOD_CONTRACT;
        m_ErrorCode = ErrorCode;
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ErrorWrapper> ERRORWRAPPEROBJECTREF;
#else
typedef ErrorWrapper*     ERRORWRAPPEROBJECTREF;
#endif


//-------------------------------------------------------------
// class CurrencyWrapper, Exposed class CurrencyWrapper
// 
// 
//-------------------------------------------------------------

// Keep this in sync with code:MethodTableBuilder.CheckForSystemTypes where
// alignment requirement of the managed System.Decimal structure is computed.
#if !defined(ALIGN_ACCESS) && !defined(FEATURE_64BIT_ALIGNMENT)
#include <pshpack4.h>
#endif // !ALIGN_ACCESS && !FEATURE_64BIT_ALIGNMENT

class CurrencyWrapper : public Object
{
protected:

    CurrencyWrapper(CurrencyWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction.
    CurrencyWrapper() {LIMITED_METHOD_CONTRACT;}; // don't instantiate this class directly
    ~CurrencyWrapper() {LIMITED_METHOD_CONTRACT;};

    DECIMAL m_WrappedObject;

public:
    DECIMAL GetWrappedObject()
    {
        LIMITED_METHOD_CONTRACT;
        return m_WrappedObject;
    }

    void SetWrappedObject(DECIMAL WrappedObj)
    {
        LIMITED_METHOD_CONTRACT;
        m_WrappedObject = WrappedObj;
    }
};

#if !defined(ALIGN_ACCESS) && !defined(FEATURE_64BIT_ALIGNMENT)
#include <poppack.h>
#endif // !ALIGN_ACCESS && !FEATURE_64BIT_ALIGNMENT

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<CurrencyWrapper> CURRENCYWRAPPEROBJECTREF;
#else
typedef CurrencyWrapper*     CURRENCYWRAPPEROBJECTREF;
#endif

//-------------------------------------------------------------
// class BStrWrapper, Exposed class BSTRWRAPPEROBJECTREF
// 
// 
//-------------------------------------------------------------
class BStrWrapper : public Object
{
protected:

    BStrWrapper(BStrWrapper &wrap) {LIMITED_METHOD_CONTRACT}; // dissalow copy construction.
    BStrWrapper() {LIMITED_METHOD_CONTRACT}; // don't instantiate this class directly
    ~BStrWrapper() {LIMITED_METHOD_CONTRACT};

    STRINGREF m_WrappedObject;

public:
    STRINGREF GetWrappedObject()
    {
        LIMITED_METHOD_CONTRACT;
        return m_WrappedObject;
    }

    void SetWrappedObject(STRINGREF pWrappedObject)
    {
        LIMITED_METHOD_CONTRACT;
        m_WrappedObject = pWrappedObject;
    }
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<BStrWrapper> BSTRWRAPPEROBJECTREF;
#else
typedef BStrWrapper*     BSTRWRAPPEROBJECTREF;
#endif

#endif // FEATURE_COMINTEROP
#endif // CLR_STANDALONE_BINDER

class StringBufferObject;
#ifdef USE_CHECKED_OBJECTREFS
typedef REF<StringBufferObject> STRINGBUFFERREF;
#else   // USE_CHECKED_OBJECTREFS
typedef StringBufferObject * STRINGBUFFERREF;
#endif  // USE_CHECKED_OBJECTREFS

//
// StringBufferObject
//
// Note that the "copy on write" bit is buried within the implementation
// of the object in order to make the implementation smaller.
//


class StringBufferObject : public Object
{
    friend class MscorlibBinder;

  private:
    CHARARRAYREF m_ChunkChars;
    StringBufferObject *m_ChunkPrevious;
    UINT32 m_ChunkLength;
    UINT32 m_ChunkOffset;
    INT32 m_MaxCapacity;

    WCHAR* GetBuffer()
    {
        LIMITED_METHOD_CONTRACT;
        return (WCHAR *)m_ChunkChars->GetDirectPointerToNonObjectElements();
    }
        
    // This function assumes that requiredLength will be less 
    // than the max capacity of the StringBufferObject   
    DWORD GetAllocationLength(DWORD dwRequiredLength)
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE((INT32)dwRequiredLength <= m_MaxCapacity);
        DWORD dwCurrentLength = GetArrayLength();

        // round the current length to the nearest multiple of 2
        // that is >= the required length
        if(dwCurrentLength < dwRequiredLength)
        {
            dwCurrentLength = (dwRequiredLength + 1) & ~1;        
        }
        return dwCurrentLength;
    }

  protected:
   StringBufferObject() { LIMITED_METHOD_CONTRACT; };
   ~StringBufferObject() { LIMITED_METHOD_CONTRACT; };

  public:
    INT32 GetMaxCapacity()
    {
        return m_MaxCapacity;
    }

    DWORD GetArrayLength() 
    {
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(m_ChunkChars);
        return m_ChunkOffset + m_ChunkChars->GetNumComponents();
    }

    // Given an ANSI string, use it to replace the StringBufferObject's internal buffer
    VOID ReplaceBufferWithAnsi(CHARARRAYREF *newArrayRef, __in CHAR *newChars, DWORD dwNewCapacity)
    {
#ifndef DACCESS_COMPILE
        SetObjectReference((OBJECTREF *)&m_ChunkChars, (OBJECTREF)(*newArrayRef), GetAppDomain());
#endif //!DACCESS_COMPILE
        WCHAR *thisChars = GetBuffer();
        // NOTE: This call to MultiByte also writes out the null terminator
        // which is currently part of the String representation.
        INT32 ncWritten = MultiByteToWideChar(CP_ACP,
                                              MB_PRECOMPOSED,
                                              newChars,
                                              -1,
                                              (LPWSTR)thisChars,
                                              dwNewCapacity+1);

        if (ncWritten == 0)
        {
            // Normally, we'd throw an exception if the string couldn't be converted.
            // In this particular case, we paper over it instead. The reason is
            // that most likely reason a P/Invoke-called api returned a
            // poison string is that the api failed for some reason, and hence
            // exercised its right to leave the buffer in a poison state.
            // Because P/Invoke cannot discover if an api failed, it cannot
            // know to ignore the buffer on the out marshaling path.
            // Because normal P/Invoke procedure is for the caller to check error
            // codes manually, we don't want to throw an exception on him.
            // We certainly don't want to randomly throw or not throw based on the
            // nondeterministic contents of a buffer passed to a failing api.
            *thisChars = W('\0');
            ncWritten++;
        }

        m_ChunkOffset = 0;
        m_ChunkLength = ncWritten-1;
        m_ChunkPrevious = NULL;
    }

    // Given a Unicode string, use it to replace the StringBufferObject's internal buffer
    VOID ReplaceBuffer(CHARARRAYREF *newArrayRef, __in_ecount(dwNewCapacity) WCHAR *newChars, DWORD dwNewCapacity)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
#ifndef DACCESS_COMPILE
        SetObjectReference((OBJECTREF *)&m_ChunkChars, (OBJECTREF)(*newArrayRef), GetAppDomain());
#endif //!DACCESS_COMPILE
        WCHAR *thisChars = GetBuffer();
        memcpyNoGCRefs(thisChars, newChars, sizeof(WCHAR)*dwNewCapacity);
        thisChars[dwNewCapacity] = W('\0');
        m_ChunkLength = dwNewCapacity;
        m_ChunkPrevious = NULL;
        m_ChunkOffset = 0; 
    }

    static void ReplaceBuffer(STRINGBUFFERREF *thisRef, __in_ecount(newLength) WCHAR *newBuffer, INT32 newLength);
    static void ReplaceBufferAnsi(STRINGBUFFERREF *thisRef, __in_ecount(newCapacity) CHAR *newBuffer, INT32 newCapacity);    
    static INT32 LocalIndexOfString(__in_ecount(strLength) WCHAR *base, __in_ecount(patternLength) WCHAR *search, int strLength, int patternLength, int startPos);
};

class SafeHandle : public Object
{
    friend class MscorlibBinder;

  private:
    // READ ME:
    //   Modifying the order or fields of this object may require
    //   other changes to the classlib class definition of this
    //   object or special handling when loading this system class.
#ifdef _DEBUG
    STRINGREF m_debugStackTrace;   // Where we allocated this SafeHandle
#endif
    Volatile<LPVOID> m_handle;
    Volatile<INT32> m_state;        // Combined ref count and closed/disposed state (for atomicity)
    Volatile<CLR_BOOL> m_ownsHandle;
    Volatile<CLR_BOOL> m_fullyInitialized;  // Did constructor finish?

    // Describe the bits in the m_state field above.
    enum StateBits
    {
        SH_State_Closed     = 0x00000001,
        SH_State_Disposed   = 0x00000002,
        SH_State_RefCount   = 0xfffffffc,
        SH_RefCountOne      = 4,            // Amount to increment state field to yield a ref count increment of 1
    };

    static WORD s_IsInvalidHandleMethodSlot;
    static WORD s_ReleaseHandleMethodSlot;

    static void RunReleaseMethod(SafeHandle* psh);
    BOOL IsFullyInitialized() const { LIMITED_METHOD_CONTRACT; return m_fullyInitialized; }

  public:
    static void Init();

    // To use the SafeHandle from native, look at the SafeHandleHolder, which
    // will do the AddRef & Release for you.
    LPVOID GetHandle() const { 
        LIMITED_METHOD_CONTRACT;
        _ASSERTE(((unsigned int) m_state) >= SH_RefCountOne);
        return m_handle;
    }

    BOOL OwnsHandle() const
    {
        LIMITED_METHOD_CONTRACT;
        return m_ownsHandle;
    }

    static size_t GetHandleOffset() { LIMITED_METHOD_CONTRACT; return offsetof(SafeHandle, m_handle); }

    void AddRef();
    void Release(bool fDispose = false);
    void Dispose();
    void SetHandle(LPVOID handle);

    static FCDECL1(void, DisposeNative, SafeHandle* refThisUNSAFE);
    static FCDECL1(void, Finalize, SafeHandle* refThisUNSAFE);
    static FCDECL1(void, SetHandleAsInvalid, SafeHandle* refThisUNSAFE);
    static FCDECL2(void, DangerousAddRef, SafeHandle* refThisUNSAFE, CLR_BOOL *pfSuccess);
    static FCDECL1(void, DangerousRelease, SafeHandle* refThisUNSAFE);
};

// SAFEHANDLEREF defined above because CompressedStackObject needs it

void AcquireSafeHandle(SAFEHANDLEREF* s);
void ReleaseSafeHandle(SAFEHANDLEREF* s);

typedef Holder<SAFEHANDLEREF*, AcquireSafeHandle, ReleaseSafeHandle> SafeHandleHolder;

class CriticalHandle : public Object
{
    friend class MscorlibBinder;

  private:
    // READ ME:
    //   Modifying the order or fields of this object may require
    //   other changes to the classlib class definition of this
    //   object or special handling when loading this system class.
#ifdef _DEBUG
    STRINGREF m_debugStackTrace;   // Where we allocated this CriticalHandle
#endif
    Volatile<LPVOID> m_handle;
    Volatile<CLR_BOOL> m_isClosed;

  public:
    LPVOID GetHandle() const { LIMITED_METHOD_CONTRACT; return m_handle; }
    static size_t GetHandleOffset() { LIMITED_METHOD_CONTRACT; return offsetof(CriticalHandle, m_handle); }

    void SetHandle(LPVOID handle) { LIMITED_METHOD_CONTRACT; m_handle = handle; }

    static FCDECL1(void, FireCustomerDebugProbe, CriticalHandle* refThisUNSAFE);
};


class ReflectClassBaseObject;

class SafeBuffer : SafeHandle
{
  private:
    size_t m_numBytes;

  public:
    static FCDECL1(UINT, SizeOfType, ReflectClassBaseObject* typeUNSAFE);
    static FCDECL1(UINT, AlignedSizeOfType, ReflectClassBaseObject* typeUNSAFE);
    static FCDECL3(void, PtrToStructure, BYTE* ptr, FC_TypedByRef structure, UINT32 sizeofT);
    static FCDECL3(void, StructureToPtr, FC_TypedByRef structure, BYTE* ptr, UINT32 sizeofT);
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<CriticalHandle> CRITICALHANDLE;
typedef REF<CriticalHandle> CRITICALHANDLEREF;
#else // USE_CHECKED_OBJECTREFS
typedef CriticalHandle * CRITICALHANDLE;
typedef CriticalHandle * CRITICALHANDLEREF;
#endif // USE_CHECKED_OBJECTREFS

// WaitHandleBase
// Base class for WaitHandle 
class WaitHandleBase :public MarshalByRefObjectBaseObject
{
    friend class WaitHandleNative;
    friend class MscorlibBinder;

public:
    __inline LPVOID GetWaitHandle() {LIMITED_METHOD_CONTRACT; return m_handle;}
    __inline SAFEHANDLEREF GetSafeHandle() {LIMITED_METHOD_CONTRACT; return m_safeHandle;}

private:
    SAFEHANDLEREF   m_safeHandle;
    LPVOID          m_handle;
    CLR_BOOL        m_hasThreadAffinity;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<WaitHandleBase> WAITHANDLEREF;
#else // USE_CHECKED_OBJECTREFS
typedef WaitHandleBase* WAITHANDLEREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to FileStreamAsyncResult on the managed side.
class AsyncResultBase :public Object
{
    friend class MscorlibBinder;

public: 
    WAITHANDLEREF GetWaitHandle() { LIMITED_METHOD_CONTRACT; return _waitHandle;}
    void SetErrorCode(int errcode) { LIMITED_METHOD_CONTRACT; _errorCode = errcode;}
    void SetNumBytes(int numBytes) { LIMITED_METHOD_CONTRACT; _numBytes = numBytes;}
    void SetIsComplete() { LIMITED_METHOD_CONTRACT; _isComplete = TRUE; }
    void SetCompletedAsynchronously() { LIMITED_METHOD_CONTRACT; _completedSynchronously = FALSE; }

    // README:
    // If you modify the order of these fields, make sure to update the definition in 
    // BCL for this object.
private:
    OBJECTREF _userCallback;
    OBJECTREF _userStateObject;

    WAITHANDLEREF _waitHandle;
    SAFEHANDLEREF _fileHandle;     // For cancellation.
    LPOVERLAPPED  _overlapped;
    int _EndXxxCalled;             // Whether we've called EndXxx already.
    int _numBytes;                 // number of bytes read OR written
    int _errorCode;
    int _numBufferedBytes;

    CLR_BOOL _isWrite;                 // Whether this is a read or a write
    CLR_BOOL _isComplete;
    CLR_BOOL _completedSynchronously;  // Which thread called callback
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<AsyncResultBase> ASYNCRESULTREF;
#else // USE_CHECKED_OBJECTREFS
typedef AsyncResultBase* ASYNCRESULTREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to System.MulticastDelegate on the managed side.
class DelegateObject : public Object
{
    friend class CheckAsmOffsets;
    friend class MscorlibBinder;

public:
    BOOL IsWrapperDelegate() { LIMITED_METHOD_CONTRACT; return _methodPtrAux == NULL; }
    
    OBJECTREF GetTarget() { LIMITED_METHOD_CONTRACT; return _target; }
    void SetTarget(OBJECTREF target) { WRAPPER_NO_CONTRACT; SetObjectReference(&_target, target, GetAppDomain()); }
    static int GetOffsetOfTarget() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _target); }

    PCODE GetMethodPtr() { LIMITED_METHOD_CONTRACT; return _methodPtr; }
    void SetMethodPtr(PCODE methodPtr) { LIMITED_METHOD_CONTRACT; _methodPtr = methodPtr; }
    static int GetOffsetOfMethodPtr() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _methodPtr); }

    PCODE GetMethodPtrAux() { LIMITED_METHOD_CONTRACT; return _methodPtrAux; }
    void SetMethodPtrAux(PCODE methodPtrAux) { LIMITED_METHOD_CONTRACT; _methodPtrAux = methodPtrAux; }
    static int GetOffsetOfMethodPtrAux() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _methodPtrAux); }

    OBJECTREF GetInvocationList() { LIMITED_METHOD_CONTRACT; return _invocationList; }
    void SetInvocationList(OBJECTREF invocationList) { WRAPPER_NO_CONTRACT; SetObjectReference(&_invocationList, invocationList, GetAppDomain()); }
    static int GetOffsetOfInvocationList() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _invocationList); }

    INT_PTR GetInvocationCount() { LIMITED_METHOD_CONTRACT; return _invocationCount; }
    void SetInvocationCount(INT_PTR invocationCount) { LIMITED_METHOD_CONTRACT; _invocationCount = invocationCount; }
    static int GetOffsetOfInvocationCount() { LIMITED_METHOD_CONTRACT; return offsetof(DelegateObject, _invocationCount); }

    void SetMethodBase(OBJECTREF newMethodBase) { LIMITED_METHOD_CONTRACT; SetObjectReference((OBJECTREF*)&_methodBase, newMethodBase, GetAppDomain()); }

    // README:
    // If you modify the order of these fields, make sure to update the definition in 
    // BCL for this object.
private:
    // System.Delegate
    OBJECTREF   _target;
    OBJECTREF   _methodBase;
    PCODE       _methodPtr;
    PCODE       _methodPtrAux;
    // System.MulticastDelegate
    OBJECTREF   _invocationList;
    INT_PTR     _invocationCount;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<DelegateObject> DELEGATEREF;
#else // USE_CHECKED_OBJECTREFS
typedef DelegateObject* DELEGATEREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to PermissionSet on the managed side.
class PermissionSetObject : public Object
{
    friend class MscorlibBinder;

public:
    BOOL AllPermissionsDecoded()
    {
        LIMITED_METHOD_CONTRACT;
        return _allPermissionsDecoded == TRUE;
    }

    BOOL ContainsCas()
    {
        LIMITED_METHOD_CONTRACT;
        return _ContainsCas == TRUE;
    }

    BOOL ContainsNonCas()
    {
        LIMITED_METHOD_CONTRACT;
        return _ContainsNonCas == TRUE;
    }

    BOOL CheckedForNonCas()
    {
        LIMITED_METHOD_CONTRACT;
        return _CheckedForNonCas == TRUE;
    }

    BOOL IsUnrestricted()
    {
        LIMITED_METHOD_CONTRACT;
        return _Unrestricted == TRUE;
    }

    OBJECTREF GetTokenBasedSet()
    {
        LIMITED_METHOD_CONTRACT;
        return _permSet;
    }


    // README:
    // If you modify the order of these fields, make sure to update the definition in 
    // BCL for this object.
private:
    // Order of the fields is important as it mirrors the layout of PermissionSet
    // to access the fields directly from unmanaged code given an OBJECTREF. 
    // Please keep them in sync when you make changes to the fields. 
    OBJECTREF _permSet;
    STRINGREF _serializedPermissionSet;
    OBJECTREF _permSetSaved;
    OBJECTREF _unrestrictedPermSet;
    OBJECTREF _normalPermSet;
    CLR_BOOL _Unrestricted;
    CLR_BOOL _allPermissionsDecoded;
    CLR_BOOL _ignoreTypeLoadFailures;
    CLR_BOOL _CheckedForNonCas;
    CLR_BOOL _ContainsCas;
    CLR_BOOL _ContainsNonCas;
    CLR_BOOL _Readable;
#ifdef FEATURE_CAS_POLICY
    CLR_BOOL _canUnrestrictedOverride;
#endif // FEATURE_CAS_POLICY
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<PermissionSetObject> PERMISSIONSETREF;
#else // USE_CHECKED_OBJECTREFS
typedef PermissionSetObject* PERMISSIONSETREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to TokenBasedSet on the managed side.
class TokenBasedSetObject : public Object
{
public:
    INT32 GetNumElements () {
        LIMITED_METHOD_CONTRACT;
        return _cElt;
    }

    OBJECTREF GetPermSet () {
        LIMITED_METHOD_CONTRACT;
        return _Obj;
    }

private:
    // If you modify the order of these fields, make sure
    // to update the definition in BCL for this object.
    OBJECTREF _objSet;
    OBJECTREF _Obj;
    OBJECTREF _Set;
    INT32 _initSize;
    INT32 _increment;
    INT32 _cElt;
    INT32 _maxIndex;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<TokenBasedSetObject> TOKENBASEDSETREF;
#else // USE_CHECKED_OBJECTREFS
typedef TokenBasedSetObject* TOKENBASEDSETREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to PolicyStatement on the managed side.
class PolicyStatementObject : public Object
{
    friend class MscorlibBinder;
private:
    PERMISSIONSETREF _permSet;
#ifdef FEATURE_CAS_POLICY
    OBJECTREF _dependentEvidence;
#endif // FEATURE_CAS_POLICY
    INT32 _attributes;

public:
    PERMISSIONSETREF GetPermissionSet()
    {
        LIMITED_METHOD_CONTRACT;
        return _permSet;
    }
};
#ifdef USE_CHECKED_OBJECTREFS
typedef REF<PolicyStatementObject> POLICYSTATEMENTREF;
#else // USE_CHECKED_OBJECTREFS
typedef PolicyStatementObject* POLICYSTATEMENTREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to ApplicationTrust on the managed side.
class ApplicationTrustObject : public Object
{
    friend class MscorlibBinder;
private:
#ifdef FEATURE_CLICKONCE
    OBJECTREF _appId;
    OBJECTREF _extraInfo;
    OBJECTREF _elExtraInfo;
#endif // FEATURE_CLICKONCE
    POLICYSTATEMENTREF _psDefaultGrant;
    OBJECTREF _fullTrustAssemblies;
    DWORD _grantSetSpecialFlags;
#ifdef FEATURE_CLICKONCE
    CLR_BOOL _appTrustedToRun;
    CLR_BOOL _persist;
#endif // FEATURE_CLICKONCE

public:
    POLICYSTATEMENTREF GetPolicyStatement()
    {
        LIMITED_METHOD_CONTRACT;
        return _psDefaultGrant;
    }

    // The grant set special flags are mapped in the BCL for the DefaultGrantSet of the ApplicationTrust. 
    // Since ApplicationTrust provides a reference to its DefaultGrantSet rather than a copy, the flags may
    // not be in sync if user code can ever get a hold of the ApplicationTrust object.  Therefore, these
    // flags should only be used in code paths where we are sure that only trusted code can ever get a
    // reference to the ApplicationTrust (such as the ApplicationTrust created when setting up a homogenous
    // AppDomain).
    DWORD GetGrantSetSpecialFlags()
    {
        LIMITED_METHOD_CONTRACT;
        return _grantSetSpecialFlags;
    }
};
#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ApplicationTrustObject> APPLICATIONTRUSTREF;
#else // USE_CHECKED_OBJECTREFS
typedef ApplicationTrustObject* APPLICATIONTRUSTREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to SecurityPermission on the managed side.
class SecurityPermissionObject : public Object
{
public:
    DWORD GetFlags () {
        LIMITED_METHOD_CONTRACT;
        return _flags;
    }

private:
    // If you modify the order of these fields, make sure
    // to update the definition in BCL for this object.
    DWORD _flags;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<SecurityPermissionObject> SECURITYPERMISSIONREF;
#else // USE_CHECKED_OBJECTREFS
typedef SecurityPermissionObject* SECURITYPERMISSIONREF;
#endif // USE_CHECKED_OBJECTREFS

// This class corresponds to ReflectionPermission on the managed side.
class ReflectionPermissionObject : public Object
{
public:
    DWORD GetFlags () {
        LIMITED_METHOD_CONTRACT;
        return _flags;
    }

private:
    DWORD _flags;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ReflectionPermissionObject> REFLECTIONPERMISSIONREF;
#else // USE_CHECKED_OBJECTREFS
typedef ReflectionPermissionObject* REFLECTIONPERMISSIONREF;
#endif // USE_CHECKED_OBJECTREFS

struct StackTraceElement;
class ClrDataAccess;


typedef DPTR(StackTraceElement) PTR_StackTraceElement;

class StackTraceArray
{
    struct ArrayHeader
    {
        size_t m_size;
        Thread * m_thread;
    };

    typedef DPTR(ArrayHeader) PTR_ArrayHeader;

public:
    StackTraceArray()
        : m_array(static_cast<I1Array *>(NULL))
    {
        WRAPPER_NO_CONTRACT;
    }
    
    StackTraceArray(I1ARRAYREF array)
        : m_array(array)
    {
        LIMITED_METHOD_CONTRACT;
    }

    void Swap(StackTraceArray & rhs)
    {
        CONTRACTL
        {
            NOTHROW;
            GC_NOTRIGGER;
            SO_TOLERANT;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        SUPPORTS_DAC;
        I1ARRAYREF t = m_array;
        m_array = rhs.m_array;
        rhs.m_array = t;
    }
    
    size_t Size() const
    {
        WRAPPER_NO_CONTRACT;
        if (!m_array)
            return 0;
        else
            return GetSize();
    }
    
    StackTraceElement const & operator[](size_t index) const;
    StackTraceElement & operator[](size_t index);

    void Append(StackTraceElement const * begin, StackTraceElement const * end);
    void AppendSkipLast(StackTraceElement const * begin, StackTraceElement const * end);

    I1ARRAYREF Get() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return m_array;
    }

    // Deep copies the array
    void CopyFrom(StackTraceArray const & src);
    
private:
    StackTraceArray(StackTraceArray const & rhs);

    StackTraceArray & operator=(StackTraceArray const & rhs)
    {
        WRAPPER_NO_CONTRACT;
        StackTraceArray copy(rhs);
        this->Swap(copy);
        return *this;
    }

    void Grow(size_t size);
    void EnsureThreadAffinity();
    void CheckState() const;

    size_t Capacity() const
    {
        WRAPPER_NO_CONTRACT;
        assert(!!m_array);

        return m_array->GetNumComponents();
    }
    
    size_t GetSize() const
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->m_size;
    }

    void SetSize(size_t size)
    {
        WRAPPER_NO_CONTRACT;
        GetHeader()->m_size = size;
    }

    Thread * GetObjectThread() const
    {
        WRAPPER_NO_CONTRACT;
        return GetHeader()->m_thread;
    }

#ifndef BINDER
    void SetObjectThread()
    {
        WRAPPER_NO_CONTRACT;
        GetHeader()->m_thread = GetThread();
    }
#endif //!BINDER

    StackTraceElement const * GetData() const
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        return dac_cast<PTR_StackTraceElement>(GetRaw() + sizeof(ArrayHeader));
    }

    PTR_StackTraceElement GetData()
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        return dac_cast<PTR_StackTraceElement>(GetRaw() + sizeof(ArrayHeader));
    }

    I1 const * GetRaw() const
    {
        WRAPPER_NO_CONTRACT;
        assert(!!m_array);

        return const_cast<I1ARRAYREF &>(m_array)->GetDirectPointerToNonObjectElements();
    }

    PTR_I1 GetRaw()
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        assert(!!m_array);

        return dac_cast<PTR_I1>(m_array->GetDirectPointerToNonObjectElements());
    }

    ArrayHeader const * GetHeader() const
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        return dac_cast<PTR_ArrayHeader>(GetRaw());
    }

    PTR_ArrayHeader GetHeader()
    {
        WRAPPER_NO_CONTRACT;
        SUPPORTS_DAC;
        return dac_cast<PTR_ArrayHeader>(GetRaw());
    }

    void SetArray(I1ARRAYREF const & arr)
    {
        LIMITED_METHOD_CONTRACT;
        m_array = arr;
    }

private:
    // put only things here that can be protected with GCPROTECT
    I1ARRAYREF m_array;
};

#ifdef FEATURE_COLLECTIBLE_TYPES

class LoaderAllocatorScoutObject : public Object
{
    friend class MscorlibBinder;
    friend class LoaderAllocatorObject;

protected:
    LoaderAllocator * m_nativeLoaderAllocator;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<LoaderAllocatorScoutObject> LOADERALLOCATORSCOUTREF;
#else // USE_CHECKED_OBJECTREFS
typedef LoaderAllocatorScoutObject* LOADERALLOCATORSCOUTREF;
#endif // USE_CHECKED_OBJECTREFS

class LoaderAllocatorObject : public Object
{
    friend class MscorlibBinder;

public:
    PTRARRAYREF GetHandleTable()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return (PTRARRAYREF)m_pSlots;
    }

    void SetHandleTable(PTRARRAYREF handleTable)
    {
        LIMITED_METHOD_CONTRACT;
        SetObjectReferenceUnchecked(&m_pSlots, (OBJECTREF)handleTable);
    }

    INT32 GetSlotsUsed()
    {
        LIMITED_METHOD_CONTRACT;
        return m_slotsUsed;
    }

    void SetSlotsUsed(INT32 newSlotsUsed)
    {
        LIMITED_METHOD_CONTRACT;
        m_slotsUsed = newSlotsUsed;
    }

    void SetNativeLoaderAllocator(LoaderAllocator * pLoaderAllocator)
    {
        LIMITED_METHOD_CONTRACT;
        m_pLoaderAllocatorScout->m_nativeLoaderAllocator = pLoaderAllocator;
    }

    // README:
    // If you modify the order of these fields, make sure to update the definition in 
    // BCL for this object.
protected:
    LOADERALLOCATORSCOUTREF m_pLoaderAllocatorScout;
    OBJECTREF   m_pSlots;
    INT32       m_slotsUsed;
    OBJECTREF   m_methodInstantiationsTable;
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<LoaderAllocatorObject> LOADERALLOCATORREF;
#else // USE_CHECKED_OBJECTREFS
typedef DPTR(LoaderAllocatorObject) PTR_LoaderAllocatorObject;
typedef PTR_LoaderAllocatorObject LOADERALLOCATORREF;
#endif // USE_CHECKED_OBJECTREFS

#endif // FEATURE_COLLECTIBLE_TYPES

#if !defined(DACCESS_COMPILE) && !defined(CLR_STANDALONE_BINDER)
// Define the lock used to access stacktrace from an exception object
EXTERN_C SpinLock g_StackTraceArrayLock;
#endif // !defined(DACCESS_COMPILE) && !defined(CLR_STANDALONE_BINDER)

// This class corresponds to Exception on the managed side.
typedef DPTR(class ExceptionObject) PTR_ExceptionObject;
#include "pshpack4.h"
class ExceptionObject : public Object
{
    friend class MscorlibBinder;

public:
    void SetHResult(HRESULT hr)
    {
        LIMITED_METHOD_CONTRACT;
        _HResult = hr;
    }

    HRESULT GetHResult()
    {
        LIMITED_METHOD_CONTRACT;
        return _HResult;
    }

    void SetXCode(DWORD code)
    {
        LIMITED_METHOD_CONTRACT;
        _xcode = code;
    }

    DWORD GetXCode()
    {
        LIMITED_METHOD_CONTRACT;
        return _xcode;
    }

    void SetXPtrs(void* xptrs)
    {
        LIMITED_METHOD_CONTRACT;
        _xptrs = xptrs;
    }

    void* GetXPtrs()
    {
        LIMITED_METHOD_CONTRACT;
        return _xptrs;
    }

    void SetStackTrace(StackTraceArray const & stackTrace, PTRARRAYREF dynamicMethodArray);
    void SetNullStackTrace();

    void GetStackTrace(StackTraceArray & stackTrace, PTRARRAYREF * outDynamicMethodArray = NULL) const;

#ifdef DACCESS_COMPILE
    I1ARRAYREF GetStackTraceArrayObject() const
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return _stackTrace;
    }
#endif // DACCESS_COMPILE

    void SetInnerException(OBJECTREF innerException)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference((OBJECTREF*)&_innerException, (OBJECTREF)innerException, GetAppDomain());
    }

    OBJECTREF GetInnerException()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return _innerException;
    }

    // Returns the innermost exception object - equivalent of the
    // managed System.Exception.GetBaseException method.
    OBJECTREF GetBaseException()
    {
        LIMITED_METHOD_CONTRACT;

        // Loop and get the innermost exception object
        OBJECTREF oInnerMostException = NULL;
        OBJECTREF oCurrent = NULL;

        oCurrent = _innerException;
        while(oCurrent != NULL)
        {
            oInnerMostException = oCurrent;
            oCurrent = ((ExceptionObject*)(Object *)OBJECTREFToObject(oCurrent))->GetInnerException();
        }

        // return the innermost exception
        return oInnerMostException;
    }

    void SetMessage(STRINGREF message)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference((OBJECTREF*)&_message, (OBJECTREF)message, GetAppDomain());
    }

    STRINGREF GetMessage()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return _message;
    }

    void SetStackTraceString(STRINGREF stackTraceString)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference((OBJECTREF*)&_stackTraceString, (OBJECTREF)stackTraceString, GetAppDomain());
    }

    STRINGREF GetStackTraceString()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return _stackTraceString;
    }

    STRINGREF GetRemoteStackTraceString()
    {
        LIMITED_METHOD_DAC_CONTRACT;
        return _remoteStackTraceString;
    }

    void SetHelpURL(STRINGREF helpURL)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference((OBJECTREF*)&_helpURL, (OBJECTREF)helpURL, GetAppDomain());
    }

    void SetSource(STRINGREF source)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference((OBJECTREF*)&_source, (OBJECTREF)source, GetAppDomain());
    }

    void ClearStackTraceForThrow()
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReferenceUnchecked((OBJECTREF*)&_remoteStackTraceString, NULL);
        SetObjectReferenceUnchecked((OBJECTREF*)&_stackTrace, NULL);
        SetObjectReferenceUnchecked((OBJECTREF*)&_stackTraceString, NULL);
    }

    void ClearStackTracePreservingRemoteStackTrace()
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReferenceUnchecked((OBJECTREF*)&_stackTrace, NULL);
        SetObjectReferenceUnchecked((OBJECTREF*)&_stackTraceString, NULL);
    }

    // This method will set the reference to the array
    // containing the watson bucket information (in byte[] form).
    void SetWatsonBucketReference(OBJECTREF oWatsonBucketArray)
    {
        WRAPPER_NO_CONTRACT;
        SetObjectReference((OBJECTREF*)&_watsonBuckets, (OBJECTREF)oWatsonBucketArray, GetAppDomain());
    }

    // This method will return the reference to the array
    // containing the watson buckets
    U1ARRAYREF GetWatsonBucketReference()
    {
        LIMITED_METHOD_CONTRACT;
        return _watsonBuckets;
    }

    // This method will return a BOOL to indicate if the 
    // watson buckets are present or not.
    BOOL AreWatsonBucketsPresent()
    {
        LIMITED_METHOD_CONTRACT;
        return (_watsonBuckets != NULL)?TRUE:FALSE;
    }

    // This method will save the IP to be used for watson bucketing.
    void SetIPForWatsonBuckets(UINT_PTR ip)
    {
        LIMITED_METHOD_CONTRACT;

        _ipForWatsonBuckets = ip;
    }

    // This method will return a BOOL to indicate if Watson bucketing IP
    // is present (or not).
    BOOL IsIPForWatsonBucketsPresent()
    {
        LIMITED_METHOD_CONTRACT;

        return (_ipForWatsonBuckets != NULL);
    }

    // This method returns the IP for Watson Buckets.
    UINT_PTR GetIPForWatsonBuckets()
    {
        LIMITED_METHOD_CONTRACT;

        return _ipForWatsonBuckets;
    }

    // README:
    // If you modify the order of these fields, make sure to update the definition in 
    // BCL for this object.
private:
    STRINGREF   _className;  //Needed for serialization.
    OBJECTREF   _exceptionMethod;  //Needed for serialization.
    STRINGREF   _exceptionMethodString; //Needed for serialization.
    STRINGREF   _message;
    OBJECTREF   _data;
    OBJECTREF   _innerException;
    STRINGREF   _helpURL;
    I1ARRAYREF  _stackTrace;
    U1ARRAYREF  _watsonBuckets;
    STRINGREF   _stackTraceString; //Needed for serialization.
    STRINGREF   _remoteStackTraceString;
    PTRARRAYREF _dynamicMethods;
    STRINGREF   _source;         // Mainly used by VB.
#ifdef FEATURE_SERIALIZATION
    OBJECTREF   _safeSerializationManager;
#endif // FEATURE_SERIALIZATION
    IN_WIN64(void* _xptrs;)
    IN_WIN64(UINT_PTR    _ipForWatsonBuckets;) // Contains the IP of exception for watson bucketing
    INT32       _remoteStackIndex;
    INT32       _HResult;
    IN_WIN32(void* _xptrs;)
    INT32       _xcode;
    IN_WIN32(UINT_PTR    _ipForWatsonBuckets;) // Contains the IP of exception for watson bucketing
};

// Defined in Contracts.cs
enum ContractFailureKind
{
    CONTRACT_FAILURE_PRECONDITION = 0,
    CONTRACT_FAILURE_POSTCONDITION,
    CONTRACT_FAILURE_POSTCONDITION_ON_EXCEPTION,
    CONTRACT_FAILURE_INVARIANT,
    CONTRACT_FAILURE_ASSERT,
    CONTRACT_FAILURE_ASSUME,
};

typedef DPTR(class ContractExceptionObject) PTR_ContractExceptionObject;
class ContractExceptionObject : public ExceptionObject
{
    friend class MscorlibBinder;

public:
    ContractFailureKind GetContractFailureKind()
    {
        LIMITED_METHOD_CONTRACT;

        return static_cast<ContractFailureKind>(_Kind);
    }

private:
    // keep these in sync with ndp/clr/src/bcl/system/diagnostics/contracts/contractsbcl.cs
    IN_WIN64(INT32 _Kind;)
    STRINGREF _UserMessage;
    STRINGREF _Condition;
    IN_WIN32(INT32 _Kind;)
};
#include "poppack.h"

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ContractExceptionObject> CONTRACTEXCEPTIONREF;
#else // USE_CHECKED_OBJECTREFS
typedef PTR_ContractExceptionObject CONTRACTEXCEPTIONREF;
#endif // USE_CHECKED_OBJECTREFS

class NumberFormatInfo: public Object
{
public:
    // C++ data members                 // Corresponding data member in NumberFormatInfo.cs
                                        // Also update mscorlib.h when you add/remove fields

    I4ARRAYREF cNumberGroup;        // numberGroupSize
    I4ARRAYREF cCurrencyGroup;      // currencyGroupSize
    I4ARRAYREF cPercentGroup;       // percentGroupSize
    
    STRINGREF sPositive;            // positiveSign
    STRINGREF sNegative;            // negativeSign
    STRINGREF sNumberDecimal;       // numberDecimalSeparator
    STRINGREF sNumberGroup;         // numberGroupSeparator
    STRINGREF sCurrencyGroup;       // currencyDecimalSeparator
    STRINGREF sCurrencyDecimal;     // currencyGroupSeparator
    STRINGREF sCurrency;            // currencySymbol
#ifndef FEATURE_COREFX_GLOBALIZATION
    STRINGREF sAnsiCurrency;        // ansiCurrencySymbol
#endif
    STRINGREF sNaN;                 // nanSymbol
    STRINGREF sPositiveInfinity;    // positiveInfinitySymbol
    STRINGREF sNegativeInfinity;    // negativeInfinitySymbol
    STRINGREF sPercentDecimal;      // percentDecimalSeparator
    STRINGREF sPercentGroup;        // percentGroupSeparator
    STRINGREF sPercent;             // percentSymbol
    STRINGREF sPerMille;            // perMilleSymbol

    PTRARRAYREF sNativeDigits;      // nativeDigits (a string array)

#ifndef FEATURE_COREFX_GLOBALIZATION    
    INT32 iDataItem;                // Index into the CultureInfo Table.  Only used from managed code.
#endif
    INT32 cNumberDecimals;          // numberDecimalDigits
    INT32 cCurrencyDecimals;        // currencyDecimalDigits
    INT32 cPosCurrencyFormat;       // positiveCurrencyFormat
    INT32 cNegCurrencyFormat;       // negativeCurrencyFormat
    INT32 cNegativeNumberFormat;    // negativeNumberFormat
    INT32 cPositivePercentFormat;   // positivePercentFormat
    INT32 cNegativePercentFormat;   // negativePercentFormat
    INT32 cPercentDecimals;         // percentDecimalDigits
#ifndef FEATURE_CORECLR    
    INT32 iDigitSubstitution;       // digitSubstitution
#endif    

    CLR_BOOL bIsReadOnly;              // Is this NumberFormatInfo ReadOnly?
#ifndef FEATURE_COREFX_GLOBALIZATION
    CLR_BOOL bUseUserOverride;         // Flag to use user override. Only used from managed code.
#endif
    CLR_BOOL bIsInvariant;             // Is this the NumberFormatInfo for the Invariant Culture?
#ifndef FEATURE_CORECLR    
    CLR_BOOL bvalidForParseAsNumber;   // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
    CLR_BOOL bvalidForParseAsCurrency; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
#endif // !FEATURE_CORECLR
};

typedef NumberFormatInfo * NUMFMTREF;

//===============================================================================
// #NullableFeature
// #NullableArchitecture
// 
// In a nutshell it is counterintuitive to have a boxed Nullable<T>, since a boxed
// object already has a representation for null (the null pointer), and having 
// multiple representations for the 'not present' value just causes grief.  Thus the
// feature is build make Nullable<T> box to a boxed<T> (not boxed<Nullable<T>).
//
// We want to do this in a way that does not impact the perf of the runtime in the 
// non-nullable case.  
//
// To do this we need to 
//     * Modify the boxing helper code:JIT_Box (we don't need a special one because
//           the JIT inlines the common case, so this only gets call in uncommon cases)
//     * Make a new helper for the Unbox case (see code:JIT_Unbox_Nullable)
//     * Plumb the JIT to ask for what kind of Boxing helper is needed 
//          (see code:CEEInfo.getBoxHelper, code:CEEInfo.getUnBoxHelper
//     * change all the places in the CLR where we box or unbox by hand, and force
//          them to use code:MethodTable.Box, and code:MethodTable.Unbox which in 
//          turn call code:Nullable.Box and code:Nullable.UnBox, most of these 
//          are in reflection, and remoting (passing and returning value types).
//
// #NullableVerification
//
// Sadly, the IL Verifier also needs to know about this change.  Basically the 'box'
// instruction returns a boxed(T) (not a boxed(Nullable<T>)) for the purposes of 
// verfication.  The JIT finds out what box returns by calling back to the EE with
// the code:CEEInfo.getTypeForBox API.  
//
// #NullableDebugging 
//
// Sadly, because the debugger also does its own boxing 'by hand' for expression 
// evaluation inside visual studio, it measn that debuggers also need to be aware
// of the fact that Nullable<T> boxes to a boxed<T>.  It is the responcibility of
// debuggers to follow this convention (which is why this is sad). 
// 

//===============================================================================
// Nullable represents the managed generic value type Nullable<T> 
//
// The runtime has special logic for this value class.  When it is boxed
// it becomes either null or a boxed T.   Similarly a boxed T can be unboxed
// either as a T (as normal), or as a Nullable<T>
//
// See code:Nullable#NullableArchitecture for more. 
//
class Nullable {
    Nullable();   // This is purposefully undefined.  Do not make instances
                  // of this class.  
public:
    static void CheckFieldOffsets(TypeHandle nullableType);
    static BOOL IsNullableType(TypeHandle nullableType);
    static BOOL IsNullableForType(TypeHandle nullableType, MethodTable* paramMT);
    static BOOL IsNullableForTypeNoGC(TypeHandle nullableType, MethodTable* paramMT);

    static OBJECTREF Box(void* src, MethodTable* nullable);
    static BOOL UnBox(void* dest, OBJECTREF boxedVal, MethodTable* destMT);
    static BOOL UnBoxNoGC(void* dest, OBJECTREF boxedVal, MethodTable* destMT);
    static BOOL UnBoxIntoArgNoGC(ArgDestination *argDest, OBJECTREF boxedVal, MethodTable* destMT);
    static void UnBoxNoCheck(void* dest, OBJECTREF boxedVal, MethodTable* destMT);
    static OBJECTREF BoxedNullableNull(TypeHandle nullableType) { return 0; }

    // if 'Obj' is a true boxed nullable, return the form we want (either null or a boxed T)
    static OBJECTREF NormalizeBox(OBJECTREF obj);

    static inline CLR_BOOL HasValue(void *src, MethodTable *nullableMT)
    {
        Nullable *nullable = (Nullable *)src;
        return *(nullable->HasValueAddr(nullableMT));
    }

    static inline void *Value(void *src, MethodTable *nullableMT)
    {
        Nullable *nullable = (Nullable *)src;
        return nullable->ValueAddr(nullableMT);        
    }
    
private:
    static BOOL IsNullableForTypeHelper(MethodTable* nullableMT, MethodTable* paramMT);
    static BOOL IsNullableForTypeHelperNoGC(MethodTable* nullableMT, MethodTable* paramMT);

    CLR_BOOL* HasValueAddr(MethodTable* nullableMT);
    void* ValueAddr(MethodTable* nullableMT);
};

#ifdef USE_CHECKED_OBJECTREFS
typedef REF<ExceptionObject> EXCEPTIONREF;
#else // USE_CHECKED_OBJECTREFS
typedef PTR_ExceptionObject EXCEPTIONREF;
#endif // USE_CHECKED_OBJECTREFS

#endif // _OBJECT_H_