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
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//
// OBJECT.CPP
//
// Definitions of a Com+ Object
//
#include "common.h"
#include "vars.hpp"
#include "class.h"
#include "object.h"
#include "threads.h"
#include "excep.h"
#include "eeconfig.h"
#include "gc.h"
#ifdef FEATURE_REMOTING
#include "remoting.h"
#endif
#include "field.h"
#include "gcscan.h"
#include "argdestination.h"
#ifdef FEATURE_COMPRESSEDSTACK
void* CompressedStackObject::GetUnmanagedCompressedStack()
{
LIMITED_METHOD_CONTRACT;
return ((m_compressedStackHandle != NULL)?m_compressedStackHandle->GetHandle():NULL);
}
#endif // FEATURE_COMPRESSEDSTACK
#ifndef FEATURE_PAL
LPVOID FrameSecurityDescriptorBaseObject::GetCallerToken()
{
LIMITED_METHOD_CONTRACT;
return ((m_callerToken!= NULL)?m_callerToken->GetHandle():NULL);
}
LPVOID FrameSecurityDescriptorBaseObject::GetImpersonationToken()
{
LIMITED_METHOD_CONTRACT;
return ((m_impToken != NULL)?m_impToken->GetHandle():NULL);
}
#endif
SVAL_IMPL(INT32, ArrayBase, s_arrayBoundsZero);
// follow the necessary rules to get a new valid hashcode for an object
DWORD Object::ComputeHashCode()
{
DWORD hashCode;
// note that this algorithm now uses at most HASHCODE_BITS so that it will
// fit into the objheader if the hashcode has to be moved back into the objheader
// such as for an object that is being frozen
do
{
// we use the high order bits in this case because they're more random
hashCode = GetThread()->GetNewHashCode() >> (32-HASHCODE_BITS);
}
while (hashCode == 0); // need to enforce hashCode != 0
// verify that it really fits into HASHCODE_BITS
_ASSERTE((hashCode & ((1<<HASHCODE_BITS)-1)) == hashCode);
return hashCode;
}
#ifndef DACCESS_COMPILE
INT32 Object::GetHashCodeEx()
{
CONTRACTL
{
MODE_COOPERATIVE;
THROWS;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END
// This loop exists because we're inspecting the header dword of the object
// and it may change under us because of races with other threads.
// On top of that, it may have the spin lock bit set, in which case we're
// not supposed to change it.
// In all of these case, we need to retry the operation.
DWORD iter = 0;
DWORD dwSwitchCount = 0;
while (true)
{
DWORD bits = GetHeader()->GetBits();
if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
{
if (bits & BIT_SBLK_IS_HASHCODE)
{
// Common case: the object already has a hash code
return bits & MASK_HASHCODE;
}
else
{
// We have a sync block index. This means if we already have a hash code,
// it is in the sync block, otherwise we generate a new one and store it there
SyncBlock *psb = GetSyncBlock();
DWORD hashCode = psb->GetHashCode();
if (hashCode != 0)
return hashCode;
hashCode = ComputeHashCode();
return psb->SetHashCode(hashCode);
}
}
else
{
// If a thread is holding the thin lock or an appdomain index is set, we need a syncblock
if ((bits & (SBLK_MASK_LOCK_THREADID | (SBLK_MASK_APPDOMAININDEX << SBLK_APPDOMAIN_SHIFT))) != 0)
{
GetSyncBlock();
// No need to replicate the above code dealing with sync blocks
// here - in the next iteration of the loop, we'll realize
// we have a syncblock, and we'll do the right thing.
}
else
{
// We want to change the header in this case, so we have to check the BIT_SBLK_SPIN_LOCK bit first
if (bits & BIT_SBLK_SPIN_LOCK)
{
iter++;
if ((iter % 1024) != 0 && g_SystemInfo.dwNumberOfProcessors > 1)
{
YieldProcessor(); // indicate to the processor that we are spining
}
else
{
__SwitchToThread(0, ++dwSwitchCount);
}
continue;
}
DWORD hashCode = ComputeHashCode();
DWORD newBits = bits | BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE | hashCode;
if (GetHeader()->SetBits(newBits, bits) == bits)
return hashCode;
// Header changed under us - let's restart this whole thing.
}
}
}
}
#endif // #ifndef DACCESS_COMPILE
BOOL Object::ValidateObjectWithPossibleAV()
{
CANNOT_HAVE_CONTRACT;
SUPPORTS_DAC;
return GetGCSafeMethodTable()->ValidateWithPossibleAV();
}
#ifndef DACCESS_COMPILE
MethodTable *Object::GetTrueMethodTable()
{
CONTRACT(MethodTable*)
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
SO_TOLERANT;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
MethodTable *mt = GetMethodTable();
#ifdef FEATURE_REMOTING
if(mt->IsTransparentProxy())
{
mt = ((TransparentProxyObject *)this)->GetMethodTableBeingProxied();
}
_ASSERTE(!mt->IsTransparentProxy());
#endif
RETURN mt;
}
TypeHandle Object::GetTrueTypeHandle()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (m_pMethTab->IsArray())
return ((ArrayBase*) this)->GetTypeHandle();
else
return TypeHandle(GetTrueMethodTable());
}
// There are cases where it is not possible to get a type handle during a GC.
// If we can get the type handle, this method will return it.
// Otherwise, the method will return NULL.
TypeHandle Object::GetGCSafeTypeHandleIfPossible() const
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
if(!IsGCThread()) { MODE_COOPERATIVE; }
}
CONTRACTL_END;
// Although getting the type handle is unsafe and could cause recursive type lookups
// in some cases, it's always safe and straightforward to get to the MethodTable.
MethodTable * pMT = GetGCSafeMethodTable();
_ASSERTE(pMT != NULL);
// Don't look at types that belong to an unloading AppDomain, or else
// pObj->GetGCSafeTypeHandle() can AV. For example, we encountered this AV when pObj
// was an array like this:
//
// MyValueType1<MyValueType2>[] myArray
//
// where MyValueType1<T> & MyValueType2 are defined in different assemblies. In such
// a case, looking up the type handle for myArray requires looking in
// MyValueType1<T>'s module's m_AssemblyRefByNameTable, which is garbage if its
// AppDomain is unloading.
//
// Another AV was encountered in a similar case,
//
// MyRefType1<MyRefType2>[] myArray
//
// where MyRefType2's module was unloaded by the time the GC occurred. In at least
// one case, the GC was caused by the AD unload itself (AppDomain::Unload ->
// AppDomain::Exit -> GCInterface::AddMemoryPressure -> WKS::GCHeap::GarbageCollect).
//
// To protect against all scenarios, verify that
//
// * The MT of the object is not getting unloaded, OR
// * In the case of arrays (potentially of arrays of arrays of arrays ...), the
// MT of the innermost element is not getting unloaded. This then ensures the
// MT of the original object (i.e., array) itself must not be getting
// unloaded either, since the MTs of arrays and of their elements are
// allocated on the same loader heap, except the case where the array is
// Object[], in which case its MT is in mscorlib and thus doesn't unload.
MethodTable * pMTToCheck = pMT;
if (pMTToCheck->IsArray())
{
TypeHandle thElem = static_cast<const ArrayBase * const>(this)->GetArrayElementTypeHandle();
// Ideally, we would just call thElem.GetLoaderModule() here. Unfortunately, the
// current TypeDesc::GetLoaderModule() implementation depends on data structures
// that might have been unloaded already. So we just simulate
// TypeDesc::GetLoaderModule() for the limited array case that we care about. In
// case we're dealing with an array of arrays of arrays etc. traverse until we
// find the deepest element, and that's the type we'll check
while (thElem.HasTypeParam())
{
thElem = thElem.GetTypeParam();
}
pMTToCheck = thElem.GetMethodTable();
}
Module * pLoaderModule = pMTToCheck->GetLoaderModule();
BaseDomain * pBaseDomain = pLoaderModule->GetDomain();
if ((pBaseDomain != NULL) &&
(pBaseDomain->IsAppDomain()) &&
(pBaseDomain->AsAppDomain()->IsUnloading()))
{
return NULL;
}
// Don't look up types that are unloading due to Collectible Assemblies. Haven't been
// able to find a case where we actually encounter objects like this that can cause
// problems; however, it seems prudent to add this protection just in case.
LoaderAllocator * pLoaderAllocator = pLoaderModule->GetLoaderAllocator();
_ASSERTE(pLoaderAllocator != NULL);
if ((pLoaderAllocator->IsCollectible()) &&
(ObjectHandleIsNull(pLoaderAllocator->GetLoaderAllocatorObjectHandle())))
{
return NULL;
}
// Ok, it should now be safe to get the type handle
return GetGCSafeTypeHandle();
}
/* static */ BOOL Object::SupportsInterface(OBJECTREF pObj, MethodTable* pInterfaceMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
INJECT_FAULT(COMPlusThrowOM());
PRECONDITION(CheckPointer(pInterfaceMT));
PRECONDITION(pObj->GetTrueMethodTable()->IsRestored_NoLogging());
PRECONDITION(pInterfaceMT->IsInterface());
}
CONTRACTL_END
BOOL bSupportsItf = FALSE;
GCPROTECT_BEGIN(pObj)
{
// Make sure the interface method table has been restored.
pInterfaceMT->CheckRestore();
// Check to see if the static class definition indicates we implement the interface.
MethodTable * pMT = pObj->GetTrueMethodTable();
if (pMT->CanCastToInterface(pInterfaceMT))
{
bSupportsItf = TRUE;
}
#ifdef FEATURE_COMINTEROP
else
if (pMT->IsComObjectType())
{
// If this is a COM object, the static class definition might not be complete so we need
// to check if the COM object implements the interface.
bSupportsItf = ComObject::SupportsInterface(pObj, pInterfaceMT);
}
#endif // FEATURE_COMINTEROP
}
GCPROTECT_END();
return bSupportsItf;
}
Assembly *AssemblyBaseObject::GetAssembly()
{
WRAPPER_NO_CONTRACT;
return m_pAssembly->GetAssembly();
}
#ifdef _DEBUG
// Object::DEBUG_SetAppDomain specified DEBUG_ONLY in the contract to disable SO-tolerance
// checking for paths that are DEBUG-only.
//
// NOTE: currently this is only used by WIN64 allocation helpers, but they really should
// be calling the JIT helper SetObjectAppDomain (which currently only exists for
// x86).
void Object::DEBUG_SetAppDomain(AppDomain *pDomain)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
DEBUG_ONLY;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pDomain));
}
CONTRACTL_END;
/*_ASSERTE(GetThread()->IsSOTolerant());*/
SetAppDomain(pDomain);
}
#endif
void Object::SetAppDomain(AppDomain *pDomain)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
SO_INTOLERANT;
INJECT_FAULT(COMPlusThrowOM(););
PRECONDITION(CheckPointer(pDomain));
}
CONTRACTL_END;
#ifndef _DEBUG
if (!GetMethodTable()->IsDomainNeutral())
{
//
// If we have a per-app-domain method table, we can
// infer the app domain from the method table, so
// there is no reason to mark the object.
//
// But we don't do this in a debug build, because
// we want to be able to detect the case when the
// domain was unloaded from underneath an object (and
// the MethodTable will be toast in that case.)
//
_ASSERTE(pDomain == GetMethodTable()->GetDomain());
}
else
#endif
{
ADIndex index = pDomain->GetIndex();
GetHeader()->SetAppDomainIndex(index);
}
_ASSERTE(GetHeader()->GetAppDomainIndex().m_dwIndex != 0);
}
AppDomain *Object::GetAppDomain()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_COOPERATIVE;
}
CONTRACTL_END;
#ifndef _DEBUG
if (!GetMethodTable()->IsDomainNeutral())
return (AppDomain*) GetMethodTable()->GetDomain();
#endif
ADIndex index = GetHeader()->GetAppDomainIndex();
if (index.m_dwIndex == 0)
return NULL;
AppDomain *pDomain = SystemDomain::TestGetAppDomainAtIndex(index);
#if CHECK_APP_DOMAIN_LEAKS
if (! g_pConfig->AppDomainLeaks())
return pDomain;
if (IsAppDomainAgile())
return NULL;
//
// If an object has an index of an unloaded domain (its ok to be of a
// domain where an unload is in progress through), go ahead
// and make it agile. If this fails, we have an invalid reference
// to an unloaded domain. If it succeeds, the object is no longer
// contained in that app domain so we can continue.
//
if (pDomain == NULL)
{
if (SystemDomain::IndexOfAppDomainBeingUnloaded() == index) {
// if appdomain is unloading but still alive and is valid to have instances
// in that domain, then use it.
AppDomain *tmpDomain = SystemDomain::AppDomainBeingUnloaded();
if (tmpDomain && tmpDomain->ShouldHaveInstances())
pDomain = tmpDomain;
}
if (!pDomain && ! TrySetAppDomainAgile(FALSE))
{
_ASSERTE(!"Attempt to reference an object belonging to an unloaded domain");
}
}
#endif
return pDomain;
}
STRINGREF AllocateString(SString sstr)
{
CONTRACTL {
THROWS;
GC_TRIGGERS;
} CONTRACTL_END;
COUNT_T length = sstr.GetCount(); // count of WCHARs excluding terminating NULL
STRINGREF strObj = AllocateString(length);
memcpyNoGCRefs(strObj->GetBuffer(), sstr.GetUnicode(), length*sizeof(WCHAR));
return strObj;
}
CHARARRAYREF AllocateCharArray(DWORD dwArrayLength)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
return (CHARARRAYREF)AllocatePrimitiveArray(ELEMENT_TYPE_CHAR, dwArrayLength);
}
#if CHECK_APP_DOMAIN_LEAKS
BOOL Object::IsAppDomainAgile()
{
WRAPPER_NO_CONTRACT;
DEBUG_ONLY_FUNCTION;
SyncBlock *psb = PassiveGetSyncBlock();
if (psb)
{
if (psb->IsAppDomainAgile())
return TRUE;
if (psb->IsCheckedForAppDomainAgile())
return FALSE;
}
return CheckAppDomain(NULL);
}
BOOL Object::TrySetAppDomainAgile(BOOL raiseAssert)
{
LIMITED_METHOD_CONTRACT;
FAULT_NOT_FATAL();
DEBUG_ONLY_FUNCTION;
BOOL ret = TRUE;
EX_TRY
{
ret = SetAppDomainAgile(raiseAssert);
}
EX_CATCH{}
EX_END_CATCH(SwallowAllExceptions);
return ret;
}
BOOL Object::ShouldCheckAppDomainAgile (BOOL raiseAssert, BOOL *pfResult)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
if (!g_pConfig->AppDomainLeaks())
{
*pfResult = TRUE;
return FALSE;
}
if (this == NULL)
{
*pfResult = TRUE;
return FALSE;
}
if (IsAppDomainAgile())
{
*pfResult = TRUE;
return FALSE;
}
// if it's not agile and we've already checked it, just bail early
if (IsCheckedForAppDomainAgile())
{
*pfResult = FALSE;
return FALSE;
}
if (IsTypeNeverAppDomainAgile())
{
if (raiseAssert)
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
*pfResult = FALSE;
return FALSE;
}
//
// Do not allow any object to be set to be agile unless we
// are compiling field access checking into the class. This
// will help guard against unintentional "agile" propagation
// as well.
//
if (!IsTypeAppDomainAgile() && !IsTypeCheckAppDomainAgile())
{
if (raiseAssert)
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
*pfResult = FALSE;
return FALSE;
}
return TRUE;
}
BOOL Object::SetAppDomainAgile(BOOL raiseAssert, SetAppDomainAgilePendingTable *pTable)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
DEBUG_ONLY;
}
CONTRACTL_END;
BEGIN_DEBUG_ONLY_CODE;
BOOL fResult;
if (!this->ShouldCheckAppDomainAgile(raiseAssert, &fResult))
return fResult;
//
// If a SetAppDomainAgilePendingTable is provided, then SetAppDomainAgile
// was called via SetAppDomainAgile. Simply store this object in the
// table, and let the calling SetAppDomainAgile process it later in a
// non-recursive manner.
//
if (pTable == NULL)
{
pTable = (SetAppDomainAgilePendingTable *)ClrFlsGetValue(TlsIdx_AppDomainAgilePendingTable);
}
if (pTable)
{
//
// If the object is already being checked (on this thread or another),
// don't duplicate the effort. Return TRUE to tell the caller to
// continue processing other references. Since we're just testing
// the bit we don't need to take the spin lock.
//
ObjHeader* pOh = this->GetHeader();
_ASSERTE(pOh);
if (pOh->GetBits() & BIT_SBLK_AGILE_IN_PROGRESS)
{
return TRUE;
}
pTable->PushReference(this);
}
else
{
//
// Initialize the table of pending objects
//
SetAppDomainAgilePendingTable table;
class ResetPendingTable
{
public:
ResetPendingTable(SetAppDomainAgilePendingTable *pTable)
{
ClrFlsSetValue(TlsIdx_AppDomainAgilePendingTable, pTable);
}
~ResetPendingTable()
{
ClrFlsSetValue(TlsIdx_AppDomainAgilePendingTable, NULL);
}
};
ResetPendingTable resetPendingTable(&table);
//
// Iterate over the table, processing all referenced objects until the
// entire graph has its sync block marked, or a non-agile object is
// found. The loop will start with the current object, as though we
// just removed it from the table as a pending reference.
//
Object *pObject = this;
do
{
//
// Mark the object to identify recursion.
// ~SetAppDomainAgilePendingTable will clean up
// BIT_SBLK_AGILE_IN_PROGRESS, so attempt to push the object first
// in case it needs to throw an exception.
//
table.PushParent(pObject);
ObjHeader* pOh = pObject->GetHeader();
_ASSERTE(pOh);
bool fInProgress = false;
{
ENTER_SPIN_LOCK(pOh);
{
if (pOh->GetBits() & BIT_SBLK_AGILE_IN_PROGRESS)
{
fInProgress = true;
}
else
{
pOh->SetBit(BIT_SBLK_AGILE_IN_PROGRESS);
}
}
LEAVE_SPIN_LOCK(pOh);
}
if (fInProgress)
{
//
// Object is already being processed, so just remove it from
// the table and look for another object.
//
bool fReturnedToParent = false;
Object *pLastObject = table.GetPendingObject(&fReturnedToParent);
CONSISTENCY_CHECK(pLastObject == pObject && fReturnedToParent);
}
else
{
//
// Finish processing this object. Any references will be added to
// the table.
//
if (!pObject->SetAppDomainAgileWorker(raiseAssert, &table))
return FALSE;
}
//
// Find the next object to explore.
//
for (;;)
{
bool fReturnedToParent;
pObject = table.GetPendingObject(&fReturnedToParent);
//
// No more objects in the table?
//
if (!pObject)
break;
//
// If we've processed all objects reachable through an object,
// then clear BIT_SBLK_AGILE_IN_PROGRESS, and look for another
// object in the table.
//
if (fReturnedToParent)
{
pOh = pObject->GetHeader();
_ASSERTE(pOh);
ENTER_SPIN_LOCK(pOh);
pOh->ClrBit(BIT_SBLK_AGILE_IN_PROGRESS);
LEAVE_SPIN_LOCK(pOh);
}
else
{
//
// Re-check whether we should explore through this reference.
//
if (pObject->ShouldCheckAppDomainAgile(raiseAssert, &fResult))
break;
if (!fResult)
return FALSE;
}
}
}
while (pObject);
}
END_DEBUG_ONLY_CODE;
return TRUE;
}
BOOL Object::SetAppDomainAgileWorker(BOOL raiseAssert, SetAppDomainAgilePendingTable *pTable)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
BOOL ret = TRUE;
if (! IsTypeAppDomainAgile() && ! SetFieldsAgile(raiseAssert, pTable))
{
SetIsCheckedForAppDomainAgile();
ret = FALSE;
}
if (ret)
{
SetSyncBlockAppDomainAgile();
}
return ret;
}
SetAppDomainAgilePendingTable::SetAppDomainAgilePendingTable ()
: m_Stack(sizeof(PendingEntry))
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
}
SetAppDomainAgilePendingTable::~SetAppDomainAgilePendingTable ()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
while (TRUE)
{
Object *pObj;
bool fObjMarked;
pObj = GetPendingObject(&fObjMarked);
if (pObj == NULL)
{
break;
}
if (fObjMarked)
{
ObjHeader* pOh = pObj->GetHeader();
_ASSERTE(pOh);
ENTER_SPIN_LOCK(pOh);
pOh->ClrBit(BIT_SBLK_AGILE_IN_PROGRESS);
LEAVE_SPIN_LOCK(pOh);
}
}
}
void Object::SetSyncBlockAppDomainAgile()
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
SyncBlock *psb = PassiveGetSyncBlock();
if (! psb)
{
psb = GetSyncBlock();
}
psb->SetIsAppDomainAgile();
}
#if CHECK_APP_DOMAIN_LEAKS
BOOL Object::CheckAppDomain(AppDomain *pAppDomain)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
DEBUG_ONLY_FUNCTION;
if (!g_pConfig->AppDomainLeaks())
return TRUE;
if (this == NULL)
return TRUE;
if (IsAppDomainAgileRaw())
return TRUE;
#ifndef _DEBUG
MethodTable *pMT = GetGCSafeMethodTable();
if (!pMT->IsDomainNeutral())
return pAppDomain == pMT->GetDomain();
#endif
ADIndex index = GetHeader()->GetAppDomainIndex();
_ASSERTE(index.m_dwIndex != 0);
return (pAppDomain != NULL && index == pAppDomain->GetIndex());
}
#endif
BOOL Object::IsTypeAppDomainAgile()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
DEBUG_ONLY_FUNCTION;
MethodTable *pMT = GetGCSafeMethodTable();
if (pMT->IsArray())
{
TypeHandle th = pMT->GetApproxArrayElementTypeHandle();
return th.IsArrayOfElementsAppDomainAgile();
}
else
return pMT->GetClass()->IsAppDomainAgile();
}
BOOL Object::IsTypeCheckAppDomainAgile()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
DEBUG_ONLY_FUNCTION;
MethodTable *pMT = GetGCSafeMethodTable();
if (pMT->IsArray())
{
TypeHandle th = pMT->GetApproxArrayElementTypeHandle();
return th.IsArrayOfElementsCheckAppDomainAgile();
}
else
return pMT->GetClass()->IsCheckAppDomainAgile();
}
BOOL Object::IsTypeNeverAppDomainAgile()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
DEBUG_ONLY_FUNCTION;
return !IsTypeAppDomainAgile() && !IsTypeCheckAppDomainAgile();
}
BOOL Object::IsTypeTypesafeAppDomainAgile()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
DEBUG_ONLY_FUNCTION;
return IsTypeAppDomainAgile() && !IsTypeCheckAppDomainAgile();
}
BOOL Object::TryAssignAppDomain(AppDomain *pAppDomain, BOOL raiseAssert)
{
LIMITED_METHOD_CONTRACT;
FAULT_NOT_FATAL();
DEBUG_ONLY_FUNCTION;
BOOL ret = TRUE;
EX_TRY
{
ret = AssignAppDomain(pAppDomain,raiseAssert);
}
EX_CATCH{}
EX_END_CATCH(SwallowAllExceptions);
return ret;
}
BOOL Object::AssignAppDomain(AppDomain *pAppDomain, BOOL raiseAssert)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
if (!g_pConfig->AppDomainLeaks())
return TRUE;
if (CheckAppDomain(pAppDomain))
return TRUE;
//
// App domain does not match; try to make this object agile
//
if (IsTypeNeverAppDomainAgile())
{
if (raiseAssert)
{
if (pAppDomain == NULL)
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
else
_ASSERTE(!"Attempt to reference a domain bound object from a different domain");
}
return FALSE;
}
else
{
//
// Make object agile
//
if (! IsTypeAppDomainAgile() && ! SetFieldsAgile(raiseAssert))
{
SetIsCheckedForAppDomainAgile();
return FALSE;
}
SetSyncBlockAppDomainAgile();
return TRUE;
}
}
BOOL Object::AssignValueTypeAppDomain(MethodTable *pMT, void *base, AppDomain *pAppDomain, BOOL raiseAssert)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
DEBUG_ONLY_FUNCTION;
if (!g_pConfig->AppDomainLeaks())
return TRUE;
if (pMT->GetClass()->IsAppDomainAgile())
return TRUE;
if (pAppDomain == NULL)
{
//
// Do not allow any object to be set to be agile unless we
// are compiling field access checking into the class. This
// will help guard against unintentional "agile" propagation
// as well.
//
if (pMT->GetClass()->IsNeverAppDomainAgile())
{
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
return FALSE;
}
return SetClassFieldsAgile(pMT, base, TRUE/*=baseIsVT*/, raiseAssert);
}
else
{
return ValidateClassFields(pMT, base, TRUE/*=baseIsVT*/, pAppDomain, raiseAssert);
}
}
BOOL Object::SetFieldsAgile(BOOL raiseAssert, SetAppDomainAgilePendingTable *pTable)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
INJECT_FAULT(COMPlusThrowOM(););
DEBUG_ONLY;
}
CONTRACTL_END;
BOOL result = TRUE;
MethodTable *pMT= GetGCSafeMethodTable();
if (pMT->IsArray())
{
switch (pMT->GetArrayElementType())
{
case ELEMENT_TYPE_CLASS:
case ELEMENT_TYPE_ARRAY:
case ELEMENT_TYPE_SZARRAY:
{
PtrArray *pArray = (PtrArray *) this;
DWORD n = pArray->GetNumComponents();
OBJECTREF *p = (OBJECTREF *)
(((BYTE*)pArray) + ArrayBase::GetDataPtrOffset(GetGCSafeMethodTable()));
for (DWORD i=0; i<n; i++)
{
if (!p[i]->SetAppDomainAgile(raiseAssert, pTable))
result = FALSE;
}
break;
}
case ELEMENT_TYPE_VALUETYPE:
{
ArrayBase *pArray = (ArrayBase *) this;
MethodTable *pElemMT = pMT->GetApproxArrayElementTypeHandle().GetMethodTable();
BYTE *p = ((BYTE*)pArray) + ArrayBase::GetDataPtrOffset(GetGCSafeMethodTable());
SIZE_T size = pArray->GetComponentSize();
SIZE_T n = pArray->GetNumComponents();
for (SIZE_T i=0; i<n; i++)
if (!SetClassFieldsAgile(pElemMT, p + i*size, TRUE/*=baseIsVT*/, raiseAssert, pTable))
result = FALSE;
break;
}
default:
_ASSERTE(!"Unexpected array type");
}
}
else
{
if (pMT->GetClass()->IsNeverAppDomainAgile())
{
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
return FALSE;
}
while (pMT != NULL && !pMT->GetClass()->IsTypesafeAppDomainAgile())
{
if (!SetClassFieldsAgile(pMT, this, FALSE/*=baseIsVT*/, raiseAssert, pTable))
result = FALSE;
pMT = pMT->GetParentMethodTable();
if (pMT->GetClass()->IsNeverAppDomainAgile())
{
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
return FALSE;
}
}
}
return result;
}
BOOL Object::SetClassFieldsAgile(MethodTable *pMT, void *base, BOOL baseIsVT, BOOL raiseAssert, SetAppDomainAgilePendingTable *pTable)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
BOOL result = TRUE;
if (pMT->GetClass()->IsNeverAppDomainAgile())
{
_ASSERTE(!"Attempt to reference a domain bound object from an agile location");
return FALSE;
}
// This type approximation is OK since we are only checking some layout information
// and all compatible instantiations share the same GC characteristics
ApproxFieldDescIterator fdIterator(pMT, ApproxFieldDescIterator::INSTANCE_FIELDS);
FieldDesc* pField;
while ((pField = fdIterator.Next()) != NULL)
{
if (pField->IsDangerousAppDomainAgileField())
{
if (pField->GetFieldType() == ELEMENT_TYPE_CLASS)
{
OBJECTREF ref;
if (baseIsVT)
ref = *(OBJECTREF*) pField->GetAddressNoThrowNoGC(base);
else
ref = *(OBJECTREF*) pField->GetAddressGuaranteedInHeap(base);
if (ref != 0 && !ref->IsAppDomainAgile())
{
if (!ref->SetAppDomainAgile(raiseAssert, pTable))
result = FALSE;
}
}
else if (pField->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
{
// Be careful here - we may not have loaded a value
// type field of a class under prejit, and we don't
// want to trigger class loading here.
TypeHandle th = pField->LookupFieldTypeHandle();
if (!th.IsNull())
{
void *nestedBase;
if (baseIsVT)
nestedBase = pField->GetAddressNoThrowNoGC(base);
else
nestedBase = pField->GetAddressGuaranteedInHeap(base);
if (!SetClassFieldsAgile(th.GetMethodTable(),
nestedBase,
TRUE/*=baseIsVT*/,
raiseAssert,
pTable))
{
result = FALSE;
}
}
}
else
{
_ASSERTE(!"Bad field type");
}
}
}
return result;
}
BOOL Object::ValidateAppDomain(AppDomain *pAppDomain)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
if (!g_pConfig->AppDomainLeaks())
return TRUE;
if (this == NULL)
return TRUE;
if (CheckAppDomain())
return ValidateAppDomainFields(pAppDomain);
return AssignAppDomain(pAppDomain);
}
BOOL Object::ValidateAppDomainFields(AppDomain *pAppDomain)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
BOOL result = TRUE;
MethodTable *pMT = GetGCSafeMethodTable();
while (pMT != NULL && !pMT->GetClass()->IsTypesafeAppDomainAgile())
{
if (!ValidateClassFields(pMT, this, FALSE/*=baseIsVT*/, pAppDomain))
result = FALSE;
pMT = pMT->GetParentMethodTable();
}
return result;
}
BOOL Object::ValidateValueTypeAppDomain(MethodTable *pMT, void *base, AppDomain *pAppDomain, BOOL raiseAssert)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
if (!g_pConfig->AppDomainLeaks())
return TRUE;
if (pAppDomain == NULL)
{
if (pMT->GetClass()->IsTypesafeAppDomainAgile())
return TRUE;
else if (pMT->GetClass()->IsNeverAppDomainAgile())
{
if (raiseAssert)
_ASSERTE(!"Value type cannot be app domain agile");
return FALSE;
}
}
return ValidateClassFields(pMT, base, TRUE/*=baseIsVT*/, pAppDomain, raiseAssert);
}
BOOL Object::ValidateClassFields(MethodTable *pMT, void *base, BOOL baseIsVT, AppDomain *pAppDomain, BOOL raiseAssert)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_NOTRIGGER;
BOOL result = TRUE;
// This type approximation is OK since we are only checking some layout information
// and all compatible instantiations share the same GC characteristics
ApproxFieldDescIterator fdIterator(pMT, ApproxFieldDescIterator::INSTANCE_FIELDS);
FieldDesc* pField;
while ((pField = fdIterator.Next()) != NULL)
{
if (!pMT->GetClass()->IsCheckAppDomainAgile()
|| pField->IsDangerousAppDomainAgileField())
{
if (pField->GetFieldType() == ELEMENT_TYPE_CLASS)
{
OBJECTREF ref;
if (baseIsVT)
ref = ObjectToOBJECTREF(*(Object**) pField->GetAddressNoThrowNoGC(base));
else
ref = ObjectToOBJECTREF(*(Object**) pField->GetAddressGuaranteedInHeap(base));
if (ref != 0 && !ref->AssignAppDomain(pAppDomain, raiseAssert))
result = FALSE;
}
else if (pField->GetFieldType() == ELEMENT_TYPE_VALUETYPE)
{
// Be careful here - we may not have loaded a value
// type field of a class under prejit, and we don't
// want to trigger class loading here.
TypeHandle th = pField->LookupFieldTypeHandle();
if (!th.IsNull())
{
void *nestedBase;
if (baseIsVT)
nestedBase = pField->GetAddressNoThrowNoGC(base);
else
nestedBase = pField->GetAddressGuaranteedInHeap(base);
if (!ValidateValueTypeAppDomain(th.GetMethodTable(),
nestedBase,
pAppDomain,
raiseAssert
))
result = FALSE;
}
}
}
}
return result;
}
#endif // CHECK_APP_DOMAIN_LEAKS
void Object::ValidatePromote(ScanContext *sc, DWORD flags)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
#if defined (VERIFY_HEAP)
Validate();
#endif
#if CHECK_APP_DOMAIN_LEAKS
// Do app domain integrity checking here
if (g_pConfig->AppDomainLeaks())
{
AppDomain *pDomain = GetAppDomain();
// This assert will incorrectly trip when
// InternalCrossContextCallback is on the stack. InternalCrossContextCallback
// intentionally passes an object across domains on the same thread.
#if 0
if (flags & GC_CALL_CHECK_APP_DOMAIN)
_ASSERTE(TryAssignAppDomain(sc->pCurrentDomain));
#endif
if ((flags & GC_CALL_CHECK_APP_DOMAIN)
&& pDomain != NULL
&& !pDomain->ShouldHaveRoots()
&& !TrySetAppDomainAgile(FALSE))
{
_ASSERTE(!"Found GC object which should have been purged during app domain unload.");
}
}
#endif
}
void Object::ValidateHeap(Object *from, BOOL bDeep)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
#if defined (VERIFY_HEAP)
//no need to verify next object's header in this case
//since this is called in verify_heap, which will verfiy every object anyway
Validate(bDeep, FALSE);
#endif
#if CHECK_APP_DOMAIN_LEAKS
// Do app domain integrity checking here
if (g_pConfig->AppDomainLeaks() && bDeep)
{
AppDomain *pDomain = from->GetAppDomain();
//
// Don't perform check if we're checking for agility, and the containing type is not
// marked checked agile - this will cover "proxy" type agility
// where cross references are allowed
//
// Changed the GetMethodTable calls in this function to GetGCSafeMethodTable
// because GC could use the mark bit to simulate a mark and can have it set during
// verify heap (and would be cleared when verify heap is done).
// We'd get AV pretty soon anyway if it was truly mistakenly set.
if (pDomain != NULL || from->GetGCSafeMethodTable()->GetClass()->IsCheckAppDomainAgile())
{
//special case:thread object is allowed to hold a context belonging to current domain
if (from->GetGCSafeMethodTable() == g_pThreadClass &&
(
#ifdef FEATURE_REMOTING
this == OBJECTREFToObject(((ThreadBaseObject *)from)->m_ExposedContext) ||
#endif
#ifndef FEATURE_CORECLR
this == OBJECTREFToObject(((ThreadBaseObject *)from)->m_ExecutionContext) ||
#endif
false))
{
if (((ThreadBaseObject *)from)->m_InternalThread)
_ASSERTE (CheckAppDomain (((ThreadBaseObject *)from)->m_InternalThread->GetDomain ()));
}
// special case: Overlapped has a field OverlappedData which may be moved to default domain
// during AD unload
else if (GetGCSafeMethodTable() == g_pOverlappedDataClass &&
GetAppDomainIndex() == SystemDomain::System()->DefaultDomain()->GetIndex())
{
}
else
{
TryAssignAppDomain(pDomain);
}
}
if (pDomain != NULL
&& !pDomain->ShouldHaveInstances()
&& !TrySetAppDomainAgile(FALSE))
_ASSERTE(!"Found GC object which should have been purged during app domain unload.");
}
#endif
}
void Object::SetOffsetObjectRef(DWORD dwOffset, size_t dwValue)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_SO_TOLERANT;
OBJECTREF* location;
OBJECTREF o;
location = (OBJECTREF *) &GetData()[dwOffset];
o = ObjectToOBJECTREF(*(Object **) &dwValue);
SetObjectReference( location, o, GetAppDomain() );
}
/******************************************************************/
/*
* Write Barrier Helper
*
* Use this function to assign an object reference into
* another object.
*
* It will set the appropriate GC Write Barrier data
*/
#if CHECK_APP_DOMAIN_LEAKS
void SetObjectReferenceChecked(OBJECTREF *dst,OBJECTREF ref,AppDomain *pAppDomain)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
DEBUG_ONLY_FUNCTION;
ref->TryAssignAppDomain(pAppDomain);
return SetObjectReferenceUnchecked(dst,ref);
}
#endif
void SetObjectReferenceUnchecked(OBJECTREF *dst,OBJECTREF ref)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
// Assign value. We use casting to avoid going thru the overloaded
// OBJECTREF= operator which in this case would trigger a false
// write-barrier violation assert.
VolatileStore((Object**)dst, OBJECTREFToObject(ref));
#ifdef _DEBUG
Thread::ObjectRefAssign(dst);
#endif
ErectWriteBarrier(dst, ref);
}
/******************************************************************/
// copies src to dest worrying about write barriers.
// Note that it can work on normal objects (but not arrays)
// if dest, points just after the VTABLE.
#if CHECK_APP_DOMAIN_LEAKS
void CopyValueClassChecked(void* dest, void* src, MethodTable *pMT, AppDomain *pDomain)
{
STATIC_CONTRACT_DEBUG_ONLY;
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
DEBUG_ONLY_FUNCTION;
FAULT_NOT_FATAL();
EX_TRY
{
Object::AssignValueTypeAppDomain(pMT, src, pDomain);
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
CopyValueClassUnchecked(dest,src,pMT);
}
// Copy value class into the argument specified by the argDest, performing an appdomain check first.
// The destOffset is nonzero when copying values into Nullable<T>, it is the offset
// of the T value inside of the Nullable<T>
void CopyValueClassArgChecked(ArgDestination *argDest, void* src, MethodTable *pMT, AppDomain *pDomain, int destOffset)
{
STATIC_CONTRACT_DEBUG_ONLY;
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
DEBUG_ONLY_FUNCTION;
FAULT_NOT_FATAL();
EX_TRY
{
Object::AssignValueTypeAppDomain(pMT, src, pDomain);
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
CopyValueClassArgUnchecked(argDest, src, pMT, destOffset);
}
#endif
void STDCALL CopyValueClassUnchecked(void* dest, void* src, MethodTable *pMT)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
_ASSERTE(!pMT->IsArray()); // bunch of assumptions about arrays wrong.
// Copy the bulk of the data, and any non-GC refs.
switch (pMT->GetNumInstanceFieldBytes())
{
case 1:
VolatileStore((UINT8*)dest, *(UINT8*)src);
break;
#ifndef ALIGN_ACCESS
// we can hit an alignment fault if the value type has multiple
// smaller fields. Example: if there are two I4 fields, the
// value class can be aligned to 4-byte boundaries, yet the
// NumInstanceFieldBytes is 8
case 2:
VolatileStore((UINT16*)dest, *(UINT16*)src);
break;
case 4:
VolatileStore((UINT32*)dest, *(UINT32*)src);
break;
case 8:
VolatileStore((UINT64*)dest, *(UINT64*)src);
break;
#endif // !ALIGN_ACCESS
default:
memcpyNoGCRefs(dest, src, pMT->GetNumInstanceFieldBytes());
break;
}
// Tell the GC about any copies.
if (pMT->ContainsPointers())
{
CGCDesc* map = CGCDesc::GetCGCDescFromMT(pMT);
CGCDescSeries* cur = map->GetHighestSeries();
CGCDescSeries* last = map->GetLowestSeries();
DWORD size = pMT->GetBaseSize();
_ASSERTE(cur >= last);
do
{
// offset to embedded references in this series must be
// adjusted by the VTable pointer, when in the unboxed state.
size_t offset = cur->GetSeriesOffset() - sizeof(void*);
OBJECTREF* srcPtr = (OBJECTREF*)(((BYTE*) src) + offset);
OBJECTREF* destPtr = (OBJECTREF*)(((BYTE*) dest) + offset);
OBJECTREF* srcPtrStop = (OBJECTREF*)((BYTE*) srcPtr + cur->GetSeriesSize() + size);
while (srcPtr < srcPtrStop)
{
SetObjectReferenceUnchecked(destPtr, ObjectToOBJECTREF(*(Object**)srcPtr));
srcPtr++;
destPtr++;
}
cur--;
} while (cur >= last);
}
}
// Copy value class into the argument specified by the argDest.
// The destOffset is nonzero when copying values into Nullable<T>, it is the offset
// of the T value inside of the Nullable<T>
void STDCALL CopyValueClassArgUnchecked(ArgDestination *argDest, void* src, MethodTable *pMT, int destOffset)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
#if defined(UNIX_AMD64_ABI) && defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
if (argDest->IsStructPassedInRegs())
{
argDest->CopyStructToRegisters(src, pMT->GetNumInstanceFieldBytes(), destOffset);
return;
}
#endif // UNIX_AMD64_ABI && FEATURE_UNIX_AMD64_STRUCT_PASSING
// destOffset is only valid for Nullable<T> passed in registers
_ASSERTE(destOffset == 0);
CopyValueClassUnchecked(argDest->GetDestinationAddress(), src, pMT);
}
// Initialize the value class argument to zeros
void InitValueClassArg(ArgDestination *argDest, MethodTable *pMT)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
#if defined(UNIX_AMD64_ABI) && defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
if (argDest->IsStructPassedInRegs())
{
argDest->ZeroStructInRegisters(pMT->GetNumInstanceFieldBytes());
return;
}
#endif
InitValueClass(argDest->GetDestinationAddress(), pMT);
}
#if defined (VERIFY_HEAP)
#include "dbginterface.h"
// make the checking code goes as fast as possible!
#if defined(_MSC_VER)
#pragma optimize("tgy", on)
#endif
#define CREATE_CHECK_STRING(x) #x
#define CHECK_AND_TEAR_DOWN(x) \
do{ \
if (!(x)) \
{ \
_ASSERTE(!CREATE_CHECK_STRING(x)); \
EEPOLICY_HANDLE_FATAL_ERROR(COR_E_EXECUTIONENGINE); \
} \
} while (0)
VOID Object::Validate(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
if (this == NULL)
{
return; // NULL is ok
}
if (g_IBCLogger.InstrEnabled() && !GCStress<cfg_any>::IsEnabled())
{
// If we are instrumenting for IBC (and GCStress is not enabled)
// then skip these Object::Validate() as they slow down the
// instrument phase by an order of magnitude
return;
}
if (g_fEEShutDown & ShutDown_Phase2)
{
// During second phase of shutdown the code below is not guaranteed to work.
return;
}
#ifdef _DEBUG
{
BEGIN_GETTHREAD_ALLOWED_IN_NO_THROW_REGION;
Thread *pThread = GetThread();
if (pThread != NULL && !(pThread->PreemptiveGCDisabled()))
{
// Debugger helper threads are special in that they take over for
// what would normally be a nonEE thread (the RCThread). If an
// EE thread is doing RCThread duty, then it should be treated
// as such.
//
// There are some GC threads in the same kind of category. Note that
// GetThread() sometimes returns them, if DLL_THREAD_ATTACH notifications
// have run some managed code.
if (!dbgOnly_IsSpecialEEThread() && !IsGCSpecialThread())
_ASSERTE(!"OBJECTREF being accessed while thread is in preemptive GC mode.");
}
END_GETTHREAD_ALLOWED_IN_NO_THROW_REGION;
}
#endif
{ // ValidateInner can throw or fault on failure which violates contract.
CONTRACT_VIOLATION(ThrowsViolation | FaultViolation);
// using inner helper because of TRY and stack objects with destructors.
ValidateInner(bDeep, bVerifyNextHeader, bVerifySyncBlock);
}
}
VOID Object::ValidateInner(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock)
{
STATIC_CONTRACT_THROWS; // See CONTRACT_VIOLATION above
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FAULT; // See CONTRACT_VIOLATION above
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
int lastTest = 0;
EX_TRY
{
// in order to avoid contract violations in the EH code we'll allow AVs here,
// they'll be handled in the catch block
AVInRuntimeImplOkayHolder avOk;
MethodTable *pMT = GetGCSafeMethodTable();
lastTest = 1;
CHECK_AND_TEAR_DOWN(pMT->Validate());
lastTest = 2;
bool noRangeChecks =
(g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_NO_RANGE_CHECKS) == EEConfig::HEAPVERIFY_NO_RANGE_CHECKS;
// noRangeChecks depends on initial values being FALSE
BOOL bSmallObjectHeapPtr = FALSE, bLargeObjectHeapPtr = FALSE;
if (!noRangeChecks)
{
bSmallObjectHeapPtr = GCHeap::GetGCHeap()->IsHeapPointer(this, TRUE);
if (!bSmallObjectHeapPtr)
bLargeObjectHeapPtr = GCHeap::GetGCHeap()->IsHeapPointer(this);
CHECK_AND_TEAR_DOWN(bSmallObjectHeapPtr || bLargeObjectHeapPtr);
}
lastTest = 3;
if (bDeep)
{
CHECK_AND_TEAR_DOWN(GetHeader()->Validate(bVerifySyncBlock));
}
lastTest = 4;
if (bDeep && (g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_GC)) {
GCHeap::GetGCHeap()->ValidateObjectMember(this);
}
lastTest = 5;
// since bSmallObjectHeapPtr is initialized to FALSE
// we skip checking noRangeChecks since if skipping
// is enabled bSmallObjectHeapPtr will always be false.
if (bSmallObjectHeapPtr) {
CHECK_AND_TEAR_DOWN(!GCHeap::GetGCHeap()->IsObjectInFixedHeap(this));
}
lastTest = 6;
#if CHECK_APP_DOMAIN_LEAKS
// when it's not safe to verify the fields, it's not safe to verify AppDomain either
// because the process might try to access fields.
if (bDeep && g_pConfig->AppDomainLeaks())
{
//
// Check to see that our domain is valid. This will assert if it has been unloaded.
//
SCAN_IGNORE_FAULT;
GetAppDomain();
}
#endif
lastTest = 7;
// try to validate next object's header
if (bDeep
&& bVerifyNextHeader
&& CNameSpace::GetGcRuntimeStructuresValid ()
//NextObj could be very slow if concurrent GC is going on
&& !(GCHeap::IsGCHeapInitialized() && GCHeap::GetGCHeap ()->IsConcurrentGCInProgress ()))
{
Object * nextObj = GCHeap::GetGCHeap ()->NextObj (this);
if ((nextObj != NULL) &&
(nextObj->GetGCSafeMethodTable() != g_pFreeObjectMethodTable))
{
CHECK_AND_TEAR_DOWN(nextObj->GetHeader()->Validate(FALSE));
}
}
lastTest = 8;
#ifdef FEATURE_64BIT_ALIGNMENT
if (pMT->RequiresAlign8())
{
CHECK_AND_TEAR_DOWN((((size_t)this) & 0x7) == (pMT->IsValueType()? 4:0));
}
lastTest = 9;
#endif // FEATURE_64BIT_ALIGNMENT
}
EX_CATCH
{
STRESS_LOG3(LF_ASSERT, LL_ALWAYS, "Detected use of corrupted OBJECTREF: %p [MT=%p] (lastTest=%d)", this, lastTest > 0 ? (*(size_t*)this) : 0, lastTest);
CHECK_AND_TEAR_DOWN(!"Detected use of a corrupted OBJECTREF. Possible GC hole.");
}
EX_END_CATCH(SwallowAllExceptions);
}
#endif // VERIFY_HEAP
/*==================================NewString===================================
**Action: Creates a System.String object.
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
STRINGREF StringObject::NewString(INT32 length) {
CONTRACTL {
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(length>=0);
} CONTRACTL_END;
STRINGREF pString;
if (length<0) {
return NULL;
} else if (length == 0) {
return GetEmptyString();
} else {
pString = AllocateString(length);
_ASSERTE(pString->GetBuffer()[length] == 0);
return pString;
}
}
/*==================================NewString===================================
**Action: Many years ago, VB didn't have the concept of a byte array, so enterprising
** users created one by allocating a BSTR with an odd length and using it to
** store bytes. A generation later, we're still stuck supporting this behavior.
** The way that we do this is to take advantage of the difference between the
** array length and the string length. The string length will always be the
** number of characters between the start of the string and the terminating 0.
** If we need an odd number of bytes, we'll take one wchar after the terminating 0.
** (e.g. at position StringLength+1). The high-order byte of this wchar is
** reserved for flags and the low-order byte is our odd byte. This function is
** used to allocate a string of that shape, but we don't actually mark the
** trailing byte as being in use yet.
**Returns: A newly allocated string. Null if length is less than 0.
**Arguments: length -- the length of the string to allocate
** bHasTrailByte -- whether the string also has a trailing byte.
**Exceptions: OutOfMemoryException if AllocateString fails.
==============================================================================*/
STRINGREF StringObject::NewString(INT32 length, BOOL bHasTrailByte) {
CONTRACTL {
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(length>=0 && length != INT32_MAX);
} CONTRACTL_END;
STRINGREF pString;
if (length<0 || length == INT32_MAX) {
return NULL;
} else if (length == 0) {
return GetEmptyString();
} else {
pString = AllocateString(length);
_ASSERTE(pString->GetBuffer()[length]==0);
if (bHasTrailByte) {
_ASSERTE(pString->GetBuffer()[length+1]==0);
}
}
return pString;
}
//========================================================================
// Creates a System.String object and initializes from
// the supplied null-terminated C string.
//
// Maps NULL to null. This function does *not* return null to indicate
// error situations: it throws an exception instead.
//========================================================================
STRINGREF StringObject::NewString(const WCHAR *pwsz)
{
CONTRACTL {
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
if (!pwsz)
{
return NULL;
}
else
{
DWORD nch = (DWORD)wcslen(pwsz);
if (nch==0) {
return GetEmptyString();
}
#if 0
//
// This assert is disabled because it is valid for us to get a
// pointer from the gc heap here as long as it is pinned. This
// can happen when a string is marshalled to unmanaged by
// pinning and then later put into a struct and that struct is
// then marshalled to managed.
//
_ASSERTE(!GCHeap::GetGCHeap()->IsHeapPointer((BYTE *) pwsz) ||
!"pwsz can not point to GC Heap");
#endif // 0
STRINGREF pString = AllocateString( nch );
memcpyNoGCRefs(pString->GetBuffer(), pwsz, nch*sizeof(WCHAR));
_ASSERTE(pString->GetBuffer()[nch] == 0);
return pString;
}
}
#if defined(_MSC_VER) && defined(_TARGET_X86_)
#pragma optimize("y", on) // Small critical routines, don't put in EBP frame
#endif
STRINGREF StringObject::NewString(const WCHAR *pwsz, int length) {
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(length>=0);
} CONTRACTL_END;
if (!pwsz)
{
return NULL;
}
else if (length <= 0) {
return GetEmptyString();
} else {
#if 0
//
// This assert is disabled because it is valid for us to get a
// pointer from the gc heap here as long as it is pinned. This
// can happen when a string is marshalled to unmanaged by
// pinning and then later put into a struct and that struct is
// then marshalled to managed.
//
_ASSERTE(!GCHeap::GetGCHeap()->IsHeapPointer((BYTE *) pwsz) ||
!"pwsz can not point to GC Heap");
#endif // 0
STRINGREF pString = AllocateString(length);
memcpyNoGCRefs(pString->GetBuffer(), pwsz, length*sizeof(WCHAR));
_ASSERTE(pString->GetBuffer()[length] == 0);
return pString;
}
}
#if defined(_MSC_VER) && defined(_TARGET_X86_)
#pragma optimize("", on) // Go back to command line default optimizations
#endif
STRINGREF StringObject::NewString(LPCUTF8 psz)
{
CONTRACTL {
GC_TRIGGERS;
MODE_COOPERATIVE;
THROWS;
PRECONDITION(CheckPointer(psz));
} CONTRACTL_END;
int length = (int)strlen(psz);
if (length == 0) {
return GetEmptyString();
}
CQuickBytes qb;
WCHAR* pwsz = (WCHAR*) qb.AllocThrows((length) * sizeof(WCHAR));
length = WszMultiByteToWideChar(CP_UTF8, 0, psz, length, pwsz, length);
if (length == 0) {
COMPlusThrow(kArgumentException, W("Arg_InvalidUTF8String"));
}
return NewString(pwsz, length);
}
STRINGREF StringObject::NewString(LPCUTF8 psz, int cBytes)
{
CONTRACTL {
GC_TRIGGERS;
MODE_COOPERATIVE;
THROWS;
PRECONDITION(CheckPointer(psz, NULL_OK));
} CONTRACTL_END;
if (!psz)
return NULL;
_ASSERTE(psz);
_ASSERTE(cBytes >= 0);
if (cBytes == 0) {
return GetEmptyString();
}
int cWszBytes = 0;
if (!ClrSafeInt<int>::multiply(cBytes, sizeof(WCHAR), cWszBytes))
COMPlusThrowOM();
CQuickBytes qb;
WCHAR* pwsz = (WCHAR*) qb.AllocThrows(cWszBytes);
int length = WszMultiByteToWideChar(CP_UTF8, 0, psz, cBytes, pwsz, cBytes);
if (length == 0) {
COMPlusThrow(kArgumentException, W("Arg_InvalidUTF8String"));
}
return NewString(pwsz, length);
}
//
//
// STATIC MEMBER VARIABLES
//
//
STRINGREF* StringObject::EmptyStringRefPtr=NULL;
//The special string helpers are used as flag bits for weird strings that have bytes
//after the terminating 0. The only case where we use this right now is the VB BSTR as
//byte array which is described in MakeStringAsByteArrayFromBytes.
#define SPECIAL_STRING_VB_BYTE_ARRAY 0x100
FORCEINLINE BOOL MARKS_VB_BYTE_ARRAY(WCHAR x)
{
return static_cast<BOOL>(x & SPECIAL_STRING_VB_BYTE_ARRAY);
}
FORCEINLINE WCHAR MAKE_VB_TRAIL_BYTE(BYTE x)
{
return static_cast<WCHAR>(x) | SPECIAL_STRING_VB_BYTE_ARRAY;
}
FORCEINLINE BYTE GET_VB_TRAIL_BYTE(WCHAR x)
{
return static_cast<BYTE>(x & 0xFF);
}
/*==============================InitEmptyStringRefPtr============================
**Action: Gets an empty string refptr, cache the result.
**Returns: The retrieved STRINGREF.
==============================================================================*/
STRINGREF* StringObject::InitEmptyStringRefPtr() {
CONTRACTL {
THROWS;
MODE_ANY;
GC_TRIGGERS;
} CONTRACTL_END;
GCX_COOP();
EEStringData data(0, W(""), TRUE);
EmptyStringRefPtr = SystemDomain::System()->DefaultDomain()->GetLoaderAllocator()->GetStringObjRefPtrFromUnicodeString(&data);
return EmptyStringRefPtr;
}
/*=============================StringInitCharHelper=============================
**Action:
**Returns:
**Arguments:
**Exceptions:
**Note this
==============================================================================*/
STRINGREF __stdcall StringObject::StringInitCharHelper(LPCSTR pszSource, int length) {
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
} CONTRACTL_END;
STRINGREF pString=NULL;
int dwSizeRequired=0;
_ASSERTE(length>=-1);
if (!pszSource || length == 0) {
return StringObject::GetEmptyString();
}
else if ((size_t)pszSource < 64000) {
COMPlusThrow(kArgumentException, W("Arg_MustBeStringPtrNotAtom"));
}
// Make sure we can read from the pointer.
// This is better than try to read from the pointer and catch the access violation exceptions.
if( length == -1) {
length = (INT32)strlen(pszSource);
}
if(length > 0) {
dwSizeRequired=WszMultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pszSource, length, NULL, 0);
}
if (dwSizeRequired == 0) {
if (length == 0) {
return StringObject::GetEmptyString();
}
COMPlusThrow(kArgumentException, W("Arg_InvalidANSIString"));
}
pString = AllocateString(dwSizeRequired);
dwSizeRequired = WszMultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)pszSource, length, pString->GetBuffer(), dwSizeRequired);
if (dwSizeRequired == 0) {
COMPlusThrow(kArgumentException, W("Arg_InvalidANSIString"));
}
_ASSERTE(dwSizeRequired != INT32_MAX && pString->GetBuffer()[dwSizeRequired]==0);
return pString;
}
// strAChars must be null-terminated, with an appropriate aLength
// strBChars must be null-terminated, with an appropriate bLength OR bLength == -1
// If bLength == -1, we stop on the first null character in strBChars
BOOL StringObject::CaseInsensitiveCompHelper(__in_ecount(aLength) WCHAR *strAChars, __in_z INT8 *strBChars, INT32 aLength, INT32 bLength, INT32 *result) {
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(CheckPointer(strAChars));
PRECONDITION(CheckPointer(strBChars));
PRECONDITION(CheckPointer(result));
SO_TOLERANT;
} CONTRACTL_END;
WCHAR *strAStart = strAChars;
INT8 *strBStart = strBChars;
unsigned charA;
unsigned charB;
for(;;) {
charA = *strAChars;
charB = (unsigned) *strBChars;
//Case-insensitive comparison on chars greater than 0x7F
//requires a locale-aware casing operation and we're not going there.
if ((charA|charB)>0x7F) {
*result = 0;
return FALSE;
}
// uppercase both chars.
if (charA>='a' && charA<='z') {
charA ^= 0x20;
}
if (charB>='a' && charB<='z') {
charB ^= 0x20;
}
//Return the (case-insensitive) difference between them.
if (charA!=charB) {
*result = (int)(charA-charB);
return TRUE;
}
if (charA==0) // both strings have null character
{
if (bLength == -1)
{
*result = aLength - static_cast<INT32>(strAChars - strAStart);
return TRUE;
}
if (strAChars==strAStart + aLength || strBChars==strBStart + bLength)
{
*result = aLength - bLength;
return TRUE;
}
// else both embedded zeros
}
// Next char
strAChars++; strBChars++;
}
}
INT32 StringObject::FastCompareStringHelper(DWORD* strAChars, INT32 countA, DWORD* strBChars, INT32 countB)
{
STATIC_CONTRACT_SO_TOLERANT;
INT32 count = (countA < countB) ? countA : countB;
PREFIX_ASSUME(count >= 0);
ptrdiff_t diff = (char *)strAChars - (char *)strBChars;
#if defined(_WIN64) || defined(ALIGN_ACCESS)
int alignmentA = ((SIZE_T)strAChars) & (sizeof(SIZE_T) - 1);
int alignmentB = ((SIZE_T)strBChars) & (sizeof(SIZE_T) - 1);
#endif // _WIN64 || ALIGN_ACCESS
#if defined(_WIN64)
if (alignmentA == alignmentB)
{
if ((alignmentA == 2 || alignmentA == 6) && (count >= 1))
{
LPWSTR ptr2 = (WCHAR *)strBChars;
if (( *((WCHAR*)((char *)ptr2 + diff)) - *ptr2) != 0)
{
return ((int)*((WCHAR*)((char *)ptr2 + diff)) - (int)*ptr2);
}
strBChars = (DWORD*)(++ptr2);
count -= 1;
alignmentA = (alignmentA == 2 ? 4 : 0);
}
if ((alignmentA == 4) && (count >= 2))
{
DWORD* ptr2 = (DWORD*)strBChars;
if (( *((DWORD*)((char *)ptr2 + diff)) - *ptr2) != 0)
{
LPWSTR chkptr1 = (WCHAR*)((char *)strBChars + diff);
LPWSTR chkptr2 = (WCHAR*)strBChars;
if (*chkptr1 != *chkptr2)
{
return ((int)*chkptr1 - (int)*chkptr2);
}
return ((int)*(chkptr1+1) - (int)*(chkptr2+1));
}
strBChars = ++ptr2;
count -= 2;
alignmentA = 0;
}
if (alignmentA == 0)
{
while (count >= 4)
{
SIZE_T* ptr2 = (SIZE_T*)strBChars;
if (( *((SIZE_T*)((char *)ptr2 + diff)) - *ptr2) != 0)
{
if (( *((DWORD*)((char *)ptr2 + diff)) - *(DWORD*)ptr2) != 0)
{
LPWSTR chkptr1 = (WCHAR*)((char *)strBChars + diff);
LPWSTR chkptr2 = (WCHAR*)strBChars;
if (*chkptr1 != *chkptr2)
{
return ((int)*chkptr1 - (int)*chkptr2);
}
return ((int)*(chkptr1+1) - (int)*(chkptr2+1));
}
else
{
LPWSTR chkptr1 = (WCHAR*)((DWORD*)((char *)strBChars + diff) + 1);
LPWSTR chkptr2 = (WCHAR*)((DWORD*)strBChars + 1);
if (*chkptr1 != *chkptr2)
{
return ((int)*chkptr1 - (int)*chkptr2);
}
return ((int)*(chkptr1+1) - (int)*(chkptr2+1));
}
}
strBChars = (DWORD*)(++ptr2);
count -= 4;
}
}
LPWSTR ptr2 = (WCHAR*)strBChars;
while ((count -= 1) >= 0)
{
if (( *((WCHAR*)((char *)ptr2 + diff)) - *ptr2) != 0)
{
return ((int)*((WCHAR*)((char *)ptr2 + diff)) - (int)*ptr2);
}
++ptr2;
}
}
else
#endif // _WIN64
#if defined(ALIGN_ACCESS)
if ( ( !IS_ALIGNED((size_t)strAChars, sizeof(DWORD)) ||
!IS_ALIGNED((size_t)strBChars, sizeof(DWORD)) ) &&
(abs(alignmentA - alignmentB) != 4) )
{
_ASSERTE(IS_ALIGNED((size_t)strAChars, sizeof(WCHAR)));
_ASSERTE(IS_ALIGNED((size_t)strBChars, sizeof(WCHAR)));
LPWSTR ptr2 = (WCHAR *)strBChars;
while ((count -= 1) >= 0)
{
if (( *((WCHAR*)((char *)ptr2 + diff)) - *ptr2) != 0)
{
return ((int)*((WCHAR*)((char *)ptr2 + diff)) - (int)*ptr2);
}
++ptr2;
}
}
else
#endif // ALIGN_ACCESS
{
#if defined(_WIN64) || defined(ALIGN_ACCESS)
if (abs(alignmentA - alignmentB) == 4)
{
if ((alignmentA == 2) || (alignmentB == 2))
{
LPWSTR ptr2 = (WCHAR *)strBChars;
if (( *((WCHAR*)((char *)ptr2 + diff)) - *ptr2) != 0)
{
return ((int)*((WCHAR*)((char *)ptr2 + diff)) - (int)*ptr2);
}
strBChars = (DWORD*)(++ptr2);
count -= 1;
}
}
#endif // WIN64 || ALIGN_ACCESS
// Loop comparing a DWORD at a time.
while ((count -= 2) >= 0)
{
if ((*((DWORD* )((char *)strBChars + diff)) - *strBChars) != 0)
{
LPWSTR ptr1 = (WCHAR*)((char *)strBChars + diff);
LPWSTR ptr2 = (WCHAR*)strBChars;
if (*ptr1 != *ptr2) {
return ((int)*ptr1 - (int)*ptr2);
}
return ((int)*(ptr1+1) - (int)*(ptr2+1));
}
++strBChars;
}
int c;
if (count == -1)
if ((c = *((WCHAR *) ((char *)strBChars + diff)) - *((WCHAR *) strBChars)) != 0)
return c;
}
return countA - countB;
}
/*=============================InternalHasHighChars=============================
**Action: Checks if the string can be sorted quickly. The requirements are that
** the string contain no character greater than 0x80 and that the string not
** contain an apostrophe or a hypen. Apostrophe and hyphen are excluded so that
** words like co-op and coop sort together.
**Returns: Void. The side effect is to set a bit on the string indicating whether or not
** the string contains high chars.
**Arguments: The String to be checked.
**Exceptions: None
==============================================================================*/
DWORD StringObject::InternalCheckHighChars() {
WRAPPER_NO_CONTRACT;
WCHAR *chars;
WCHAR c;
INT32 length;
RefInterpretGetStringValuesDangerousForGC((WCHAR **) &chars, &length);
DWORD stringState = STRING_STATE_FAST_OPS;
for (int i=0; i<length; i++) {
c = chars[i];
if (c>=0x80) {
SetHighCharState(STRING_STATE_HIGH_CHARS);
return STRING_STATE_HIGH_CHARS;
} else if (HighCharHelper::IsHighChar((int)c)) {
//This means that we have a character which forces special sorting,
//but doesn't necessarily force slower casing and indexing. We'll
//set a value to remember this, but we need to check the rest of
//the string because we may still find a charcter greater than 0x7f.
stringState = STRING_STATE_SPECIAL_SORT;
}
}
SetHighCharState(stringState);
return stringState;
}
#ifdef VERIFY_HEAP
/*=============================ValidateHighChars=============================
**Action: Validate if the HighChars bits is set correctly, no side effect
**Returns: BOOL for result of validation
**Arguments: The String to be checked.
**Exceptions: None
==============================================================================*/
BOOL StringObject::ValidateHighChars()
{
WRAPPER_NO_CONTRACT;
DWORD curStringState = GetHighCharState ();
// state could always be undetermined
if (curStringState == STRING_STATE_UNDETERMINED)
{
return TRUE;
}
WCHAR *chars;
INT32 length;
RefInterpretGetStringValuesDangerousForGC((WCHAR **) &chars, &length);
DWORD stringState = STRING_STATE_FAST_OPS;
for (int i=0; i<length; i++) {
WCHAR c = chars[i];
if (c>=0x80)
{
// if there is a high char in the string, the state has to be STRING_STATE_HIGH_CHARS
return curStringState == STRING_STATE_HIGH_CHARS;
}
else if (HighCharHelper::IsHighChar((int)c)) {
//This means that we have a character which forces special sorting,
//but doesn't necessarily force slower casing and indexing. We'll
//set a value to remember this, but we need to check the rest of
//the string because we may still find a charcter greater than 0x7f.
stringState = STRING_STATE_SPECIAL_SORT;
}
}
return stringState == curStringState;
}
#endif //VERIFY_HEAP
/*============================InternalTrailByteCheck============================
**Action: Many years ago, VB didn't have the concept of a byte array, so enterprising
** users created one by allocating a BSTR with an odd length and using it to
** store bytes. A generation later, we're still stuck supporting this behavior.
** The way that we do this is stick the trail byte in the sync block
** whenever we encounter such a situation. Since we expect this to be a very corner case
** accessing the sync block seems like a good enough solution
**
**Returns: True if <CODE>str</CODE> contains a VB trail byte, false otherwise.
**Arguments: str -- The string to be examined.
**Exceptions: None
==============================================================================*/
BOOL StringObject::HasTrailByte() {
WRAPPER_NO_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
SyncBlock * pSyncBlock = PassiveGetSyncBlock();
if(pSyncBlock != NULL)
{
return pSyncBlock->HasCOMBstrTrailByte();
}
return FALSE;
}
/*=================================GetTrailByte=================================
**Action: If <CODE>str</CODE> contains a vb trail byte, returns a copy of it.
**Returns: True if <CODE>str</CODE> contains a trail byte. *bTrailByte is set to
** the byte in question if <CODE>str</CODE> does have a trail byte, otherwise
** it's set to 0.
**Arguments: str -- The string being examined.
** bTrailByte -- An out param to hold the value of the trail byte.
**Exceptions: None.
==============================================================================*/
BOOL StringObject::GetTrailByte(BYTE *bTrailByte) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(bTrailByte);
*bTrailByte=0;
BOOL retValue = HasTrailByte();
if(retValue)
{
*bTrailByte = GET_VB_TRAIL_BYTE(GetHeader()->PassiveGetSyncBlock()->GetCOMBstrTrailByte());
}
return retValue;
}
/*=================================SetTrailByte=================================
**Action: Sets the trail byte in the sync block
**Returns: True.
**Arguments: str -- The string into which to set the trail byte.
** bTrailByte -- The trail byte to be added to the string.
**Exceptions: None.
==============================================================================*/
BOOL StringObject::SetTrailByte(BYTE bTrailByte) {
WRAPPER_NO_CONTRACT;
GetHeader()->GetSyncBlock()->SetCOMBstrTrailByte(MAKE_VB_TRAIL_BYTE(bTrailByte));
return TRUE;
}
#define DEFAULT_CAPACITY 16
#define DEFAULT_MAX_CAPACITY 0x7FFFFFFF
/*================================ReplaceBuffer=================================
**This is a helper function designed to be used by N/Direct it replaces the entire
**contents of the String with a new string created by some native method. This
**will not be exposed through the StringBuilder class.
==============================================================================*/
void StringBufferObject::ReplaceBuffer(STRINGBUFFERREF *thisRef, __in_ecount(newLength) WCHAR *newBuffer, INT32 newLength) {
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(newBuffer));
PRECONDITION(newLength>=0);
PRECONDITION(CheckPointer(thisRef));
PRECONDITION(IsProtectedByGCFrame(thisRef));
} CONTRACTL_END;
if(newLength > (*thisRef)->GetMaxCapacity())
{
COMPlusThrowArgumentOutOfRange(W("capacity"), W("ArgumentOutOfRange_Capacity"));
}
CHARARRAYREF newCharArray = AllocateCharArray((*thisRef)->GetAllocationLength(newLength+1));
(*thisRef)->ReplaceBuffer(&newCharArray, newBuffer, newLength);
}
/*================================ReplaceBufferAnsi=================================
**This is a helper function designed to be used by N/Direct it replaces the entire
**contents of the String with a new string created by some native method. This
**will not be exposed through the StringBuilder class.
**
**This version does Ansi->Unicode conversion along the way. Although
**making it a member of COMStringBuffer exposes more stringbuffer internals
**than necessary, it does avoid requiring a temporary buffer to hold
**the Ansi->Unicode conversion.
==============================================================================*/
void StringBufferObject::ReplaceBufferAnsi(STRINGBUFFERREF *thisRef, __in_ecount(newCapacity) CHAR *newBuffer, INT32 newCapacity) {
CONTRACTL {
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(newBuffer));
PRECONDITION(CheckPointer(thisRef));
PRECONDITION(IsProtectedByGCFrame(thisRef));
PRECONDITION(newCapacity>=0);
} CONTRACTL_END;
if(newCapacity > (*thisRef)->GetMaxCapacity())
{
COMPlusThrowArgumentOutOfRange(W("capacity"), W("ArgumentOutOfRange_Capacity"));
}
CHARARRAYREF newCharArray = AllocateCharArray((*thisRef)->GetAllocationLength(newCapacity+1));
(*thisRef)->ReplaceBufferWithAnsi(&newCharArray, newBuffer, newCapacity);
}
/*==============================LocalIndexOfString==============================
**Finds search within base and returns the index where it was found. The search
**starts from startPos and we return -1 if search isn't found. This is a direct
**copy from COMString::IndexOfString, but doesn't require that we build up
**an instance of indexOfStringArgs before calling it.
**
**Args:
**base -- the string in which to search
**search -- the string for which to search
**strLength -- the length of base
**patternLength -- the length of search
**startPos -- the place from which to start searching.
**
==============================================================================*/
/* static */ INT32 StringBufferObject::LocalIndexOfString(__in_ecount(strLength) WCHAR *base, __in_ecount(patternLength) WCHAR *search, int strLength, int patternLength, int startPos) {
LIMITED_METHOD_CONTRACT
_ASSERTE(base != NULL);
_ASSERTE(search != NULL);
int iThis, iPattern;
for (iThis=startPos; iThis < (strLength-patternLength+1); iThis++) {
for (iPattern=0; iPattern<patternLength && base[iThis+iPattern]==search[iPattern]; iPattern++);
if (iPattern == patternLength) return iThis;
}
return -1;
}
#ifdef USE_CHECKED_OBJECTREFS
//-------------------------------------------------------------
// Default constructor, for non-initializing declarations:
//
// OBJECTREF or;
//-------------------------------------------------------------
OBJECTREF::OBJECTREF()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_VIOLATION(SOToleranceViolation);
m_asObj = (Object*)POISONC;
Thread::ObjectRefNew(this);
}
//-------------------------------------------------------------
// Copy constructor, for passing OBJECTREF's as function arguments.
//-------------------------------------------------------------
OBJECTREF::OBJECTREF(const OBJECTREF & objref)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_VIOLATION(SOToleranceViolation);
VALIDATEOBJECT(objref.m_asObj);
// !!! If this assert is fired, there are two possibilities:
// !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj
// !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj),
// !!! or ObjectToSTRINGREF(*(StringObject**)pObj)
// !!! 2. There is a real GC hole here.
// !!! Either way you need to fix the code.
_ASSERTE(Thread::IsObjRefValid(&objref));
if ((objref.m_asObj != 0) &&
((GCHeap*)GCHeap::GetGCHeap())->IsHeapPointer( (BYTE*)this ))
{
_ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!");
}
m_asObj = objref.m_asObj;
if (m_asObj != 0) {
ENABLESTRESSHEAP();
}
Thread::ObjectRefNew(this);
}
//-------------------------------------------------------------
// To allow NULL to be used as an OBJECTREF.
//-------------------------------------------------------------
OBJECTREF::OBJECTREF(TADDR nul)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_VIOLATION(SOToleranceViolation);
//_ASSERTE(nul == 0);
m_asObj = (Object*)nul;
if( m_asObj != NULL)
{
// REVISIT_TODO: fix this, why is this constructor being used for non-null object refs?
STATIC_CONTRACT_VIOLATION(ModeViolation);
VALIDATEOBJECT(m_asObj);
ENABLESTRESSHEAP();
}
Thread::ObjectRefNew(this);
}
//-------------------------------------------------------------
// This is for the GC's use only. Non-GC code should never
// use the "Object" class directly. The unused "int" argument
// prevents C++ from using this to implicitly convert Object*'s
// to OBJECTREF.
//-------------------------------------------------------------
OBJECTREF::OBJECTREF(Object *pObject)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_MODE_COOPERATIVE;
STATIC_CONTRACT_FORBID_FAULT;
DEBUG_ONLY_FUNCTION;
if ((pObject != 0) &&
((GCHeap*)GCHeap::GetGCHeap())->IsHeapPointer( (BYTE*)this ))
{
_ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!");
}
m_asObj = pObject;
VALIDATEOBJECT(m_asObj);
if (m_asObj != 0) {
ENABLESTRESSHEAP();
}
Thread::ObjectRefNew(this);
}
void OBJECTREF::Validate(BOOL bDeep, BOOL bVerifyNextHeader, BOOL bVerifySyncBlock)
{
LIMITED_METHOD_CONTRACT;
m_asObj->Validate(bDeep, bVerifyNextHeader, bVerifySyncBlock);
}
//-------------------------------------------------------------
// Test against NULL.
//-------------------------------------------------------------
int OBJECTREF::operator!() const
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
// We don't do any validation here, as we want to allow zero comparison in preemptive mode
return !m_asObj;
}
//-------------------------------------------------------------
// Compare two OBJECTREF's.
//-------------------------------------------------------------
int OBJECTREF::operator==(const OBJECTREF &objref) const
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
if (objref.m_asObj != NULL) // Allow comparison to zero in preemptive mode
{
// REVISIT_TODO: Weakening the contract system a little bit here. We should really
// add a special NULLOBJECTREF which can be used for these situations and have
// a seperate code path for that with the correct contract protections.
STATIC_CONTRACT_VIOLATION(ModeViolation);
VALIDATEOBJECT(objref.m_asObj);
// !!! If this assert is fired, there are two possibilities:
// !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj
// !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj),
// !!! or ObjectToSTRINGREF(*(StringObject**)pObj)
// !!! 2. There is a real GC hole here.
// !!! Either way you need to fix the code.
_ASSERTE(Thread::IsObjRefValid(&objref));
VALIDATEOBJECT(m_asObj);
// If this assert fires, you probably did not protect
// your OBJECTREF and a GC might have occurred. To
// where the possible GC was, set a breakpoint in Thread::TriggersGC
_ASSERTE(Thread::IsObjRefValid(this));
if (m_asObj != 0 || objref.m_asObj != 0) {
ENABLESTRESSHEAP();
}
}
return m_asObj == objref.m_asObj;
}
//-------------------------------------------------------------
// Compare two OBJECTREF's.
//-------------------------------------------------------------
int OBJECTREF::operator!=(const OBJECTREF &objref) const
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
if (objref.m_asObj != NULL) // Allow comparison to zero in preemptive mode
{
// REVISIT_TODO: Weakening the contract system a little bit here. We should really
// add a special NULLOBJECTREF which can be used for these situations and have
// a seperate code path for that with the correct contract protections.
STATIC_CONTRACT_VIOLATION(ModeViolation);
VALIDATEOBJECT(objref.m_asObj);
// !!! If this assert is fired, there are two possibilities:
// !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj
// !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj),
// !!! or ObjectToSTRINGREF(*(StringObject**)pObj)
// !!! 2. There is a real GC hole here.
// !!! Either way you need to fix the code.
_ASSERTE(Thread::IsObjRefValid(&objref));
VALIDATEOBJECT(m_asObj);
// If this assert fires, you probably did not protect
// your OBJECTREF and a GC might have occurred. To
// where the possible GC was, set a breakpoint in Thread::TriggersGC
_ASSERTE(Thread::IsObjRefValid(this));
if (m_asObj != 0 || objref.m_asObj != 0) {
ENABLESTRESSHEAP();
}
}
return m_asObj != objref.m_asObj;
}
//-------------------------------------------------------------
// Forward method calls.
//-------------------------------------------------------------
Object* OBJECTREF::operator->()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
VALIDATEOBJECT(m_asObj);
// If this assert fires, you probably did not protect
// your OBJECTREF and a GC might have occurred. To
// where the possible GC was, set a breakpoint in Thread::TriggersGC
_ASSERTE(Thread::IsObjRefValid(this));
if (m_asObj != 0) {
ENABLESTRESSHEAP();
}
// if you are using OBJECTREF directly,
// you probably want an Object *
return (Object *)m_asObj;
}
//-------------------------------------------------------------
// Forward method calls.
//-------------------------------------------------------------
const Object* OBJECTREF::operator->() const
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
VALIDATEOBJECT(m_asObj);
// If this assert fires, you probably did not protect
// your OBJECTREF and a GC might have occurred. To
// where the possible GC was, set a breakpoint in Thread::TriggersGC
_ASSERTE(Thread::IsObjRefValid(this));
if (m_asObj != 0) {
ENABLESTRESSHEAP();
}
// if you are using OBJECTREF directly,
// you probably want an Object *
return (Object *)m_asObj;
}
//-------------------------------------------------------------
// Assignment. We don't validate the destination so as not
// to break the sequence:
//
// OBJECTREF or;
// or = ...;
//-------------------------------------------------------------
OBJECTREF& OBJECTREF::operator=(const OBJECTREF &objref)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
VALIDATEOBJECT(objref.m_asObj);
// !!! If this assert is fired, there are two possibilities:
// !!! 1. You are doing a type cast, e.g. *(OBJECTREF*)pObj
// !!! Instead, you should use ObjectToOBJECTREF(*(Object**)pObj),
// !!! or ObjectToSTRINGREF(*(StringObject**)pObj)
// !!! 2. There is a real GC hole here.
// !!! Either way you need to fix the code.
_ASSERTE(Thread::IsObjRefValid(&objref));
if ((objref.m_asObj != 0) &&
((GCHeap*)GCHeap::GetGCHeap())->IsHeapPointer( (BYTE*)this ))
{
_ASSERTE(!"Write Barrier violation. Must use SetObjectReference() to assign OBJECTREF's into the GC heap!");
}
Thread::ObjectRefAssign(this);
m_asObj = objref.m_asObj;
if (m_asObj != 0) {
ENABLESTRESSHEAP();
}
return *this;
}
//-------------------------------------------------------------
// Allows for the assignment of NULL to a OBJECTREF
//-------------------------------------------------------------
OBJECTREF& OBJECTREF::operator=(TADDR nul)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
_ASSERTE(nul == 0);
Thread::ObjectRefAssign(this);
m_asObj = (Object*)nul;
if (m_asObj != 0) {
ENABLESTRESSHEAP();
}
return *this;
}
#endif // DEBUG
#ifdef _DEBUG
void* __cdecl GCSafeMemCpy(void * dest, const void * src, size_t len)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
STATIC_CONTRACT_SO_TOLERANT;
if (!(((*(BYTE**)&dest) < g_lowest_address ) ||
((*(BYTE**)&dest) >= g_highest_address)))
{
Thread* pThread = GetThread();
// GCHeap::IsHeapPointer has race when called in preemptive mode. It walks the list of segments
// that can be modified by GC. Do the check below only if it is safe to do so.
if (pThread != NULL && pThread->PreemptiveGCDisabled())
{
// Note there is memcpyNoGCRefs which will allow you to do a memcpy into the GC
// heap if you really know you don't need to call the write barrier
_ASSERTE(!GCHeap::GetGCHeap()->IsHeapPointer((BYTE *) dest) ||
!"using memcpy to copy into the GC heap, use CopyValueClass");
}
}
return memcpyNoGCRefs(dest, src, len);
}
#endif // _DEBUG
// This function clears a piece of memory in a GC safe way. It makes the guarantee
// that it will clear memory in at least pointer sized chunks whenever possible.
// Unaligned memory at the beginning and remaining bytes at the end are written bytewise.
// We must make this guarantee whenever we clear memory in the GC heap that could contain
// object references. The GC or other user threads can read object references at any time,
// clearing them bytewise can result in a read on another thread getting incorrect data.
void __fastcall ZeroMemoryInGCHeap(void* mem, size_t size)
{
WRAPPER_NO_CONTRACT;
BYTE* memBytes = (BYTE*) mem;
BYTE* endBytes = &memBytes[size];
// handle unaligned bytes at the beginning
while (!IS_ALIGNED(memBytes, sizeof(PTR_PTR_VOID)) && memBytes < endBytes)
*memBytes++ = 0;
// now write pointer sized pieces
size_t nPtrs = (endBytes - memBytes) / sizeof(PTR_PTR_VOID);
PTR_PTR_VOID memPtr = (PTR_PTR_VOID) memBytes;
for (size_t i = 0; i < nPtrs; i++)
*memPtr++ = 0;
// handle remaining bytes at the end
memBytes = (BYTE*) memPtr;
while (memBytes < endBytes)
*memBytes++ = 0;
}
void StackTraceArray::Append(StackTraceElement const * begin, StackTraceElement const * end)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// ensure that only one thread can write to the array
EnsureThreadAffinity();
size_t newsize = Size() + (end - begin);
Grow(newsize);
memcpyNoGCRefs(GetData() + Size(), begin, (end - begin) * sizeof(StackTraceElement));
MemoryBarrier(); // prevent the newsize from being reordered with the array copy
SetSize(newsize);
#if defined(_DEBUG)
CheckState();
#endif
}
void StackTraceArray::AppendSkipLast(StackTraceElement const * begin, StackTraceElement const * end)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
// to skip the last element, we need to replace it with the first element
// from m_pStackTrace and do it atomically if possible,
// otherwise we'll create a copy of the entire array, which is bad for performance,
// and so should not be on the main path
//
// ensure that only one thread can write to the array
EnsureThreadAffinity();
assert(Size() > 0);
StackTraceElement & last = GetData()[Size() - 1];
if (last.PartiallyEqual(*begin))
{
// fast path: atomic update
last.PartialAtomicUpdate(*begin);
// append the rest
if (end - begin > 1)
Append(begin + 1, end);
}
else
{
// slow path: create a copy and append
StackTraceArray copy(*this);
GCPROTECT_BEGIN(copy);
copy.SetSize(copy.Size() - 1);
copy.Append(begin, end);
this->Swap(copy);
GCPROTECT_END();
}
#if defined(_DEBUG)
CheckState();
#endif
}
void StackTraceArray::CheckState() const
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (!m_array)
return;
assert(GetObjectThread() == GetThread());
size_t size = Size();
StackTraceElement const * p;
p = GetData();
for (size_t i = 0; i < size; ++i)
assert(p[i].pFunc != NULL);
}
void StackTraceArray::Grow(size_t grow_size)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory(););
}
CONTRACTL_END;
size_t raw_size = grow_size * sizeof(StackTraceElement) + sizeof(ArrayHeader);
if (!m_array)
{
SetArray(I1ARRAYREF(AllocatePrimitiveArray(ELEMENT_TYPE_I1, static_cast<DWORD>(raw_size))));
SetSize(0);
SetObjectThread();
}
else
{
if (Capacity() >= raw_size)
return;
// allocate a new array, copy the data
size_t new_capacity = Max(Capacity() * 2, raw_size);
_ASSERTE(new_capacity >= grow_size * sizeof(StackTraceElement) + sizeof(ArrayHeader));
I1ARRAYREF newarr = (I1ARRAYREF) AllocatePrimitiveArray(ELEMENT_TYPE_I1, static_cast<DWORD>(new_capacity));
memcpyNoGCRefs(newarr->GetDirectPointerToNonObjectElements(),
GetRaw(),
Size() * sizeof(StackTraceElement) + sizeof(ArrayHeader));
SetArray(newarr);
}
}
void StackTraceArray::EnsureThreadAffinity()
{
WRAPPER_NO_CONTRACT;
if (!m_array)
return;
if (GetObjectThread() != GetThread())
{
// object is being changed by a thread different from the one which created it
// make a copy of the array to prevent a race condition when two different threads try to change it
StackTraceArray copy(*this);
this->Swap(copy);
}
}
#ifdef _MSC_VER
#pragma warning(disable: 4267)
#endif
StackTraceArray::StackTraceArray(StackTraceArray const & rhs)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory(););
}
CONTRACTL_END;
m_array = (I1ARRAYREF) AllocatePrimitiveArray(ELEMENT_TYPE_I1, static_cast<DWORD>(rhs.Capacity()));
GCPROTECT_BEGIN(m_array);
Volatile<size_t> size = rhs.Size();
memcpyNoGCRefs(GetRaw(), rhs.GetRaw(), size * sizeof(StackTraceElement) + sizeof(ArrayHeader));
SetSize(size); // set size to the exact value which was used when we copied the data
// another thread might have changed it at the time of copying
SetObjectThread(); // affinitize the newly created array with the current thread
GCPROTECT_END();
}
// Deep copies the stack trace array
void StackTraceArray::CopyFrom(StackTraceArray const & src)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory(););
}
CONTRACTL_END;
m_array = (I1ARRAYREF) AllocatePrimitiveArray(ELEMENT_TYPE_I1, static_cast<DWORD>(src.Capacity()));
GCPROTECT_BEGIN(m_array);
Volatile<size_t> size = src.Size();
memcpyNoGCRefs(GetRaw(), src.GetRaw(), size * sizeof(StackTraceElement) + sizeof(ArrayHeader));
SetSize(size); // set size to the exact value which was used when we copied the data
// another thread might have changed it at the time of copying
SetObjectThread(); // affinitize the newly created array with the current thread
GCPROTECT_END();
}
#ifdef _MSC_VER
#pragma warning(default: 4267)
#endif
#ifdef _DEBUG
//===============================================================================
// Code that insures that our unmanaged version of Nullable is consistant with
// the managed version Nullable<T> for all T.
void Nullable::CheckFieldOffsets(TypeHandle nullableType)
{
LIMITED_METHOD_CONTRACT;
/***
// The non-instantiated method tables like List<T> that are used
// by reflection and verification do not have correct field offsets
// but we never make instances of these anyway.
if (nullableMT->ContainsGenericVariables())
return;
***/
MethodTable* nullableMT = nullableType.GetMethodTable();
// insure that the managed version of the table is the same as the
// unmanaged. Note that we can't do this in mscorlib.h because this
// class is generic and field layout depends on the instantiation.
_ASSERTE(nullableMT->GetNumInstanceFields() == 2);
FieldDesc* field = nullableMT->GetApproxFieldDescListRaw();
_ASSERTE(strcmp(field->GetDebugName(), "hasValue") == 0);
// _ASSERTE(field->GetOffset() == offsetof(Nullable, hasValue));
field++;
_ASSERTE(strcmp(field->GetDebugName(), "value") == 0);
// _ASSERTE(field->GetOffset() == offsetof(Nullable, value));
}
#endif
//===============================================================================
// Returns true if nullableMT is Nullable<T> for T is equivalent to paramMT
BOOL Nullable::IsNullableForTypeHelper(MethodTable* nullableMT, MethodTable* paramMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
if (!nullableMT->IsNullable())
return FALSE;
// we require the parameter types to be equivalent
return TypeHandle(paramMT).IsEquivalentTo(nullableMT->GetInstantiation()[0]);
}
//===============================================================================
// Returns true if nullableMT is Nullable<T> for T == paramMT
BOOL Nullable::IsNullableForTypeHelperNoGC(MethodTable* nullableMT, MethodTable* paramMT)
{
LIMITED_METHOD_CONTRACT;
if (!nullableMT->IsNullable())
return FALSE;
// we require an exact match of the parameter types
return TypeHandle(paramMT) == nullableMT->GetInstantiation()[0];
}
//===============================================================================
CLR_BOOL* Nullable::HasValueAddr(MethodTable* nullableMT) {
LIMITED_METHOD_CONTRACT;
_ASSERTE(strcmp(nullableMT->GetApproxFieldDescListRaw()[0].GetDebugName(), "hasValue") == 0);
_ASSERTE(nullableMT->GetApproxFieldDescListRaw()[0].GetOffset() == 0);
return (CLR_BOOL*) this;
}
//===============================================================================
void* Nullable::ValueAddr(MethodTable* nullableMT) {
LIMITED_METHOD_CONTRACT;
_ASSERTE(strcmp(nullableMT->GetApproxFieldDescListRaw()[1].GetDebugName(), "value") == 0);
return (((BYTE*) this) + nullableMT->GetApproxFieldDescListRaw()[1].GetOffset());
}
//===============================================================================
// Special Logic to box a nullable<T> as a boxed<T>
OBJECTREF Nullable::Box(void* srcPtr, MethodTable* nullableMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
FAULT_NOT_FATAL(); // FIX_NOW: why do we need this?
Nullable* src = (Nullable*) srcPtr;
_ASSERTE(IsNullableType(nullableMT));
// We better have a concrete instantiation, or our field offset asserts are not useful
_ASSERTE(!nullableMT->ContainsGenericVariables());
if (!*src->HasValueAddr(nullableMT))
return NULL;
OBJECTREF obj = 0;
GCPROTECT_BEGININTERIOR (src);
MethodTable* argMT = nullableMT->GetInstantiation()[0].GetMethodTable();
obj = argMT->Allocate();
CopyValueClass(obj->UnBox(), src->ValueAddr(nullableMT), argMT, obj->GetAppDomain());
GCPROTECT_END ();
return obj;
}
//===============================================================================
// Special Logic to unbox a boxed T as a nullable<T>
BOOL Nullable::UnBox(void* destPtr, OBJECTREF boxedVal, MethodTable* destMT)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
Nullable* dest = (Nullable*) destPtr;
BOOL fRet = TRUE;
// We should only get here if we are unboxing a T as a Nullable<T>
_ASSERTE(IsNullableType(destMT));
// We better have a concrete instantiation, or our field offset asserts are not useful
_ASSERTE(!destMT->ContainsGenericVariables());
if (boxedVal == NULL)
{
// Logically we are doing *dest->HasValueAddr(destMT) = false;
// We zero out the whole structure becasue it may contain GC references
// and these need to be initialized to zero. (could optimize in the non-GC case)
InitValueClass(destPtr, destMT);
fRet = TRUE;
}
else
{
GCPROTECT_BEGIN(boxedVal);
if (!IsNullableForType(destMT, boxedVal->GetMethodTable()))
{
// For safety's sake, also allow true nullables to be unboxed normally.
// This should not happen normally, but we want to be robust
if (destMT->IsEquivalentTo(boxedVal->GetMethodTable()))
{
CopyValueClass(dest, boxedVal->GetData(), destMT, boxedVal->GetAppDomain());
fRet = TRUE;
}
else
{
fRet = FALSE;
}
}
else
{
*dest->HasValueAddr(destMT) = true;
CopyValueClass(dest->ValueAddr(destMT), boxedVal->UnBox(), boxedVal->GetMethodTable(), boxedVal->GetAppDomain());
fRet = TRUE;
}
GCPROTECT_END();
}
return fRet;
}
//===============================================================================
// Special Logic to unbox a boxed T as a nullable<T>
// Does not handle type equivalence (may conservatively return FALSE)
BOOL Nullable::UnBoxNoGC(void* destPtr, OBJECTREF boxedVal, MethodTable* destMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
Nullable* dest = (Nullable*) destPtr;
// We should only get here if we are unboxing a T as a Nullable<T>
_ASSERTE(IsNullableType(destMT));
// We better have a concrete instantiation, or our field offset asserts are not useful
_ASSERTE(!destMT->ContainsGenericVariables());
if (boxedVal == NULL)
{
// Logically we are doing *dest->HasValueAddr(destMT) = false;
// We zero out the whole structure becasue it may contain GC references
// and these need to be initialized to zero. (could optimize in the non-GC case)
InitValueClass(destPtr, destMT);
}
else
{
if (!IsNullableForTypeNoGC(destMT, boxedVal->GetMethodTable()))
{
// For safety's sake, also allow true nullables to be unboxed normally.
// This should not happen normally, but we want to be robust
if (destMT == boxedVal->GetMethodTable())
{
CopyValueClass(dest, boxedVal->GetData(), destMT, boxedVal->GetAppDomain());
return TRUE;
}
return FALSE;
}
*dest->HasValueAddr(destMT) = true;
CopyValueClass(dest->ValueAddr(destMT), boxedVal->UnBox(), boxedVal->GetMethodTable(), boxedVal->GetAppDomain());
}
return TRUE;
}
//===============================================================================
// Special Logic to unbox a boxed T as a nullable<T> into an argument
// specified by the argDest.
// Does not handle type equivalence (may conservatively return FALSE)
BOOL Nullable::UnBoxIntoArgNoGC(ArgDestination *argDest, OBJECTREF boxedVal, MethodTable* destMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
#if defined(UNIX_AMD64_ABI) && defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
if (argDest->IsStructPassedInRegs())
{
// We should only get here if we are unboxing a T as a Nullable<T>
_ASSERTE(IsNullableType(destMT));
// We better have a concrete instantiation, or our field offset asserts are not useful
_ASSERTE(!destMT->ContainsGenericVariables());
if (boxedVal == NULL)
{
// Logically we are doing *dest->HasValueAddr(destMT) = false;
// We zero out the whole structure becasue it may contain GC references
// and these need to be initialized to zero. (could optimize in the non-GC case)
InitValueClassArg(argDest, destMT);
}
else
{
if (!IsNullableForTypeNoGC(destMT, boxedVal->GetMethodTable()))
{
// For safety's sake, also allow true nullables to be unboxed normally.
// This should not happen normally, but we want to be robust
if (destMT == boxedVal->GetMethodTable())
{
CopyValueClassArg(argDest, boxedVal->GetData(), destMT, boxedVal->GetAppDomain(), 0);
return TRUE;
}
return FALSE;
}
Nullable* dest = (Nullable*)argDest->GetStructGenRegDestinationAddress();
*dest->HasValueAddr(destMT) = true;
int destOffset = (BYTE*)dest->ValueAddr(destMT) - (BYTE*)dest;
CopyValueClassArg(argDest, boxedVal->UnBox(), boxedVal->GetMethodTable(), boxedVal->GetAppDomain(), destOffset);
}
return TRUE;
}
#endif // UNIX_AMD64_ABI && FEATURE_UNIX_AMD64_STRUCT_PASSING
return UnBoxNoGC(argDest->GetDestinationAddress(), boxedVal, destMT);
}
//===============================================================================
// Special Logic to unbox a boxed T as a nullable<T>
// Does not do any type checks.
void Nullable::UnBoxNoCheck(void* destPtr, OBJECTREF boxedVal, MethodTable* destMT)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
Nullable* dest = (Nullable*) destPtr;
// We should only get here if we are unboxing a T as a Nullable<T>
_ASSERTE(IsNullableType(destMT));
// We better have a concrete instantiation, or our field offset asserts are not useful
_ASSERTE(!destMT->ContainsGenericVariables());
if (boxedVal == NULL)
{
// Logically we are doing *dest->HasValueAddr(destMT) = false;
// We zero out the whole structure becasue it may contain GC references
// and these need to be initialized to zero. (could optimize in the non-GC case)
InitValueClass(destPtr, destMT);
}
else
{
if (IsNullableType(boxedVal->GetMethodTable()))
{
// For safety's sake, also allow true nullables to be unboxed normally.
// This should not happen normally, but we want to be robust
CopyValueClass(dest, boxedVal->GetData(), destMT, boxedVal->GetAppDomain());
}
*dest->HasValueAddr(destMT) = true;
CopyValueClass(dest->ValueAddr(destMT), boxedVal->UnBox(), boxedVal->GetMethodTable(), boxedVal->GetAppDomain());
}
}
//===============================================================================
// a boxed Nullable<T> should either be null or a boxed T, but sometimes it is
// useful to have a 'true' boxed Nullable<T> (that is it has two fields). This
// function returns a 'normalized' version of this pointer.
OBJECTREF Nullable::NormalizeBox(OBJECTREF obj) {
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
}
CONTRACTL_END;
if (obj != NULL) {
MethodTable* retMT = obj->GetMethodTable();
if (Nullable::IsNullableType(retMT))
obj = Nullable::Box(obj->GetData(), retMT);
}
return obj;
}
void ThreadBaseObject::SetInternal(Thread *it)
{
WRAPPER_NO_CONTRACT;
// only allow a transition from NULL to non-NULL
_ASSERTE((m_InternalThread == NULL) && (it != NULL));
m_InternalThread = it;
// Now the native Thread will only be destroyed after the managed Thread is collected.
// Tell the GC that the managed Thread actually represents much more memory.
GCInterface::NewAddMemoryPressure(sizeof(Thread));
}
void ThreadBaseObject::ClearInternal()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_InternalThread != NULL);
m_InternalThread = NULL;
GCInterface::NewRemoveMemoryPressure(sizeof(Thread));
}
#endif // #ifndef DACCESS_COMPILE
StackTraceElement const & StackTraceArray::operator[](size_t index) const
{
WRAPPER_NO_CONTRACT;
return GetData()[index];
}
StackTraceElement & StackTraceArray::operator[](size_t index)
{
WRAPPER_NO_CONTRACT;
return GetData()[index];
}
#if !defined(DACCESS_COMPILE)
// Define the lock used to access stacktrace from an exception object
SpinLock g_StackTraceArrayLock;
void ExceptionObject::SetStackTrace(StackTraceArray const & stackTrace, PTRARRAYREF dynamicMethodArray)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
Thread *m_pThread = GetThread();
SpinLock::AcquireLock(&g_StackTraceArrayLock, SPINLOCK_THREAD_PARAM_ONLY_IN_SOME_BUILDS);
SetObjectReference((OBJECTREF*)&_stackTrace, (OBJECTREF)stackTrace.Get(), GetAppDomain());
SetObjectReference((OBJECTREF*)&_dynamicMethods, (OBJECTREF)dynamicMethodArray, GetAppDomain());
SpinLock::ReleaseLock(&g_StackTraceArrayLock, SPINLOCK_THREAD_PARAM_ONLY_IN_SOME_BUILDS);
}
void ExceptionObject::SetNullStackTrace()
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
Thread *m_pThread = GetThread();
SpinLock::AcquireLock(&g_StackTraceArrayLock, SPINLOCK_THREAD_PARAM_ONLY_IN_SOME_BUILDS);
I1ARRAYREF stackTraceArray = NULL;
PTRARRAYREF dynamicMethodArray = NULL;
SetObjectReference((OBJECTREF*)&_stackTrace, (OBJECTREF)stackTraceArray, GetAppDomain());
SetObjectReference((OBJECTREF*)&_dynamicMethods, (OBJECTREF)dynamicMethodArray, GetAppDomain());
SpinLock::ReleaseLock(&g_StackTraceArrayLock, SPINLOCK_THREAD_PARAM_ONLY_IN_SOME_BUILDS);
}
#endif // !defined(DACCESS_COMPILE)
void ExceptionObject::GetStackTrace(StackTraceArray & stackTrace, PTRARRAYREF * outDynamicMethodArray /*= NULL*/) const
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_COOPERATIVE;
SO_TOLERANT;
}
CONTRACTL_END;
#if !defined(DACCESS_COMPILE)
Thread *m_pThread = GetThread();
SpinLock::AcquireLock(&g_StackTraceArrayLock, SPINLOCK_THREAD_PARAM_ONLY_IN_SOME_BUILDS);
#endif // !defined(DACCESS_COMPILE)
StackTraceArray temp(_stackTrace);
stackTrace.Swap(temp);
if (outDynamicMethodArray != NULL)
{
*outDynamicMethodArray = _dynamicMethods;
}
#if !defined(DACCESS_COMPILE)
SpinLock::ReleaseLock(&g_StackTraceArrayLock, SPINLOCK_THREAD_PARAM_ONLY_IN_SOME_BUILDS);
#endif // !defined(DACCESS_COMPILE)
}
|