少年修仙传客户端基础资源
hch
2024-04-01 d01413b00ef631ac20347716b23818b0b811f65f
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
/**
 * \file
 * SGen features specific to Mono.
 *
 * Copyright (C) 2014 Xamarin Inc
 *
 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
 */
 
#include "config.h"
#ifdef HAVE_SGEN_GC
 
#include "sgen/sgen-gc.h"
#include "sgen/sgen-protocol.h"
#include "metadata/monitor.h"
#include "sgen/sgen-layout-stats.h"
#include "sgen/sgen-client.h"
#include "sgen/sgen-cardtable.h"
#include "sgen/sgen-pinning.h"
#include "sgen/sgen-workers.h"
#include "metadata/marshal.h"
#include "metadata/method-builder.h"
#include "metadata/abi-details.h"
#include "metadata/mono-gc.h"
#include "metadata/runtime.h"
#include "metadata/sgen-bridge-internals.h"
#include "metadata/gc-internals.h"
#include "metadata/handle.h"
#include "utils/mono-memory-model.h"
#include "utils/mono-logger-internals.h"
#include "utils/mono-threads-coop.h"
#include "utils/mono-threads.h"
#include "metadata/w32handle.h"
 
#ifdef HEAVY_STATISTICS
static guint64 stat_wbarrier_set_arrayref = 0;
static guint64 stat_wbarrier_value_copy = 0;
static guint64 stat_wbarrier_object_copy = 0;
 
static guint64 los_marked_cards;
static guint64 los_array_cards;
static guint64 los_array_remsets;
#endif
 
/* If set, mark stacks conservatively, even if precise marking is possible */
static gboolean conservative_stack_mark = FALSE;
/* If set, check that there are no references to the domain left at domain unload */
gboolean sgen_mono_xdomain_checks = FALSE;
 
/* Functions supplied by the runtime to be called by the GC */
static MonoGCCallbacks gc_callbacks;
 
#define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
 
#define OPDEF(a,b,c,d,e,f,g,h,i,j) \
    a = i,
 
enum {
#include "mono/cil/opcode.def"
    CEE_LAST
};
 
#undef OPDEF
 
/*
 * Write barriers
 */
 
static gboolean
ptr_on_stack (void *ptr)
{
    gpointer stack_start = &stack_start;
    SgenThreadInfo *info = mono_thread_info_current ();
 
    if (ptr >= stack_start && ptr < (gpointer)info->client_info.info.stack_end)
        return TRUE;
    return FALSE;
}
 
#ifdef SGEN_HEAVY_BINARY_PROTOCOL
#undef HANDLE_PTR
#define HANDLE_PTR(ptr,obj) do {                    \
        gpointer o = *(gpointer*)(ptr);                \
        if ((o)) {                        \
            gpointer d = ((char*)dest) + ((char*)(ptr) - (char*)(obj)); \
            binary_protocol_wbarrier (d, o, (gpointer) SGEN_LOAD_VTABLE (o)); \
        }                            \
    } while (0)
 
static void
scan_object_for_binary_protocol_copy_wbarrier (gpointer dest, char *start, mword desc)
{
#define SCAN_OBJECT_NOVTABLE
#include "sgen/sgen-scan-object.h"
}
#endif
 
void
mono_gc_wbarrier_value_copy (gpointer dest, gpointer src, int count, MonoClass *klass)
{
    HEAVY_STAT (++stat_wbarrier_value_copy);
    g_assert (klass->valuetype);
 
    SGEN_LOG (8, "Adding value remset at %p, count %d, descr %p for class %s (%p)", dest, count, (gpointer)klass->gc_descr, klass->name, klass);
 
    if (sgen_ptr_in_nursery (dest) || ptr_on_stack (dest) || !sgen_gc_descr_has_references ((mword)klass->gc_descr)) {
        size_t element_size = mono_class_value_size (klass, NULL);
        size_t size = count * element_size;
        mono_gc_memmove_atomic (dest, src, size);        
        return;
    }
 
#ifdef SGEN_HEAVY_BINARY_PROTOCOL
    if (binary_protocol_is_heavy_enabled ()) {
        size_t element_size = mono_class_value_size (klass, NULL);
        int i;
        for (i = 0; i < count; ++i) {
            scan_object_for_binary_protocol_copy_wbarrier ((char*)dest + i * element_size,
                    (char*)src + i * element_size - sizeof (MonoObject),
                    (mword) klass->gc_descr);
        }
    }
#endif
 
    sgen_get_remset ()->wbarrier_value_copy (dest, src, count, mono_class_value_size (klass, NULL));
}
 
/**
 * mono_gc_wbarrier_object_copy:
 *
 * Write barrier to call when \p obj is the result of a clone or copy of an object.
 */
void
mono_gc_wbarrier_object_copy (MonoObject* obj, MonoObject *src)
{
    int size;
 
    HEAVY_STAT (++stat_wbarrier_object_copy);
 
    SGEN_ASSERT (6, !ptr_on_stack (obj), "Why is this called for a non-reference type?");
    if (sgen_ptr_in_nursery (obj) || !SGEN_OBJECT_HAS_REFERENCES (src)) {
        size = mono_object_class (obj)->instance_size;
        mono_gc_memmove_aligned ((char*)obj + sizeof (MonoObject), (char*)src + sizeof (MonoObject),
                size - sizeof (MonoObject));
        return;    
    }
 
#ifdef SGEN_HEAVY_BINARY_PROTOCOL
    if (binary_protocol_is_heavy_enabled ())
        scan_object_for_binary_protocol_copy_wbarrier (obj, (char*)src, (mword) src->vtable->gc_descr);
#endif
 
    sgen_get_remset ()->wbarrier_object_copy (obj, src);
}
 
/**
 * mono_gc_wbarrier_set_arrayref:
 */
void
mono_gc_wbarrier_set_arrayref (MonoArray *arr, gpointer slot_ptr, MonoObject* value)
{
    HEAVY_STAT (++stat_wbarrier_set_arrayref);
    if (sgen_ptr_in_nursery (slot_ptr)) {
        *(void**)slot_ptr = value;
        return;
    }
    SGEN_LOG (8, "Adding remset at %p", slot_ptr);
    if (value)
        binary_protocol_wbarrier (slot_ptr, value, value->vtable);
 
    sgen_get_remset ()->wbarrier_set_field ((GCObject*)arr, slot_ptr, value);
}
 
/**
 * mono_gc_wbarrier_set_field:
 */
void
mono_gc_wbarrier_set_field (MonoObject *obj, gpointer field_ptr, MonoObject* value)
{
    mono_gc_wbarrier_set_arrayref ((MonoArray*)obj, field_ptr, value);
}
 
void
mono_gc_wbarrier_range_copy (gpointer _dest, gpointer _src, int size)
{
    sgen_wbarrier_range_copy (_dest, _src, size);
}
 
void*
mono_gc_get_range_copy_func (void)
{
    return sgen_get_remset ()->wbarrier_range_copy;
}
 
int
mono_gc_get_suspend_signal (void)
{
    return mono_threads_suspend_get_suspend_signal ();
}
 
int
mono_gc_get_restart_signal (void)
{
    return mono_threads_suspend_get_restart_signal ();
}
 
static MonoMethod *write_barrier_conc_method;
static MonoMethod *write_barrier_noconc_method;
 
gboolean
sgen_is_critical_method (MonoMethod *method)
{
    return sgen_is_managed_allocator (method);
}
 
gboolean
sgen_has_critical_method (void)
{
    return sgen_has_managed_allocator ();
}
 
gboolean
mono_gc_is_critical_method (MonoMethod *method)
{
    return sgen_is_critical_method (method);
}
 
#ifdef ENABLE_ILGEN
 
static void
emit_nursery_check (MonoMethodBuilder *mb, int *nursery_check_return_labels, gboolean is_concurrent)
{
    int shifted_nursery_start = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
 
    memset (nursery_check_return_labels, 0, sizeof (int) * 2);
    // if (ptr_in_nursery (ptr)) return;
    /*
     * Masking out the bits might be faster, but we would have to use 64 bit
     * immediates, which might be slower.
     */
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_LDPTR_NURSERY_START);
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_LDPTR_NURSERY_BITS);
    mono_mb_emit_byte (mb, CEE_SHR_UN);
    mono_mb_emit_stloc (mb, shifted_nursery_start);
 
    mono_mb_emit_ldarg (mb, 0);
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_LDPTR_NURSERY_BITS);
    mono_mb_emit_byte (mb, CEE_SHR_UN);
    mono_mb_emit_ldloc (mb, shifted_nursery_start);
    nursery_check_return_labels [0] = mono_mb_emit_branch (mb, CEE_BEQ);
 
    if (!is_concurrent) {
        // if (!ptr_in_nursery (*ptr)) return;
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_byte (mb, CEE_LDIND_I);
        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
        mono_mb_emit_byte (mb, CEE_MONO_LDPTR_NURSERY_BITS);
        mono_mb_emit_byte (mb, CEE_SHR_UN);
        mono_mb_emit_ldloc (mb, shifted_nursery_start);
        nursery_check_return_labels [1] = mono_mb_emit_branch (mb, CEE_BNE_UN);
    }
}
#endif
 
MonoMethod*
mono_gc_get_specific_write_barrier (gboolean is_concurrent)
{
    MonoMethod *res;
    MonoMethodBuilder *mb;
    MonoMethodSignature *sig;
    MonoMethod **write_barrier_method_addr;
    WrapperInfo *info;
#ifdef MANAGED_WBARRIER
    int i, nursery_check_labels [2];
#endif
 
    // FIXME: Maybe create a separate version for ctors (the branch would be
    // correctly predicted more times)
    if (is_concurrent)
        write_barrier_method_addr = &write_barrier_conc_method;
    else
        write_barrier_method_addr = &write_barrier_noconc_method;
 
    if (*write_barrier_method_addr)
        return *write_barrier_method_addr;
 
    /* Create the IL version of mono_gc_barrier_generic_store () */
    sig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
    sig->ret = &mono_defaults.void_class->byval_arg;
    sig->params [0] = &mono_defaults.int_class->byval_arg;
 
    if (is_concurrent)
        mb = mono_mb_new (mono_defaults.object_class, "wbarrier_conc", MONO_WRAPPER_WRITE_BARRIER);
    else
        mb = mono_mb_new (mono_defaults.object_class, "wbarrier_noconc", MONO_WRAPPER_WRITE_BARRIER);
 
#ifdef ENABLE_ILGEN
#ifdef MANAGED_WBARRIER
    emit_nursery_check (mb, nursery_check_labels, is_concurrent);
    /*
    addr = sgen_cardtable + ((address >> CARD_BITS) & CARD_MASK)
    *addr = 1;
 
    sgen_cardtable:
        LDC_PTR sgen_cardtable
 
    address >> CARD_BITS
        LDARG_0
        LDC_I4 CARD_BITS
        SHR_UN
    if (SGEN_HAVE_OVERLAPPING_CARDS) {
        LDC_PTR card_table_mask
        AND
    }
    AND
    ldc_i4_1
    stind_i1
    */
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_LDPTR_CARD_TABLE);
    mono_mb_emit_ldarg (mb, 0);
    mono_mb_emit_icon (mb, CARD_BITS);
    mono_mb_emit_byte (mb, CEE_SHR_UN);
    mono_mb_emit_byte (mb, CEE_CONV_I);
#ifdef SGEN_HAVE_OVERLAPPING_CARDS
#if SIZEOF_VOID_P == 8
    mono_mb_emit_icon8 (mb, CARD_MASK);
#else
    mono_mb_emit_icon (mb, CARD_MASK);
#endif
    mono_mb_emit_byte (mb, CEE_CONV_I);
    mono_mb_emit_byte (mb, CEE_AND);
#endif
    mono_mb_emit_byte (mb, CEE_ADD);
    mono_mb_emit_icon (mb, 1);
    mono_mb_emit_byte (mb, CEE_STIND_I1);
 
    // return;
    for (i = 0; i < 2; ++i) {
        if (nursery_check_labels [i])
            mono_mb_patch_branch (mb, nursery_check_labels [i]);
    }
    mono_mb_emit_byte (mb, CEE_RET);
#else
    mono_mb_emit_ldarg (mb, 0);
    mono_mb_emit_icall (mb, mono_gc_wbarrier_generic_nostore);
    mono_mb_emit_byte (mb, CEE_RET);
#endif
#endif
    res = mono_mb_create_method (mb, sig, 16);
    info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
    mono_marshal_set_wrapper_info (res, info);
    mono_mb_free (mb);
 
    LOCK_GC;
    if (*write_barrier_method_addr) {
        /* Already created */
        mono_free_method (res);
    } else {
        /* double-checked locking */
        mono_memory_barrier ();
        *write_barrier_method_addr = res;
    }
    UNLOCK_GC;
 
    return *write_barrier_method_addr;
}
 
MonoMethod*
mono_gc_get_write_barrier (void)
{
    return mono_gc_get_specific_write_barrier (major_collector.is_concurrent);
}
 
/*
 * Dummy filler objects
 */
 
/* Vtable of the objects used to fill out nursery fragments before a collection */
static GCVTable array_fill_vtable;
 
static GCVTable
get_array_fill_vtable (void)
{
    if (!array_fill_vtable) {
        static MonoClass klass;
        static char _vtable[sizeof(MonoVTable)+8];
        MonoVTable* vtable = (MonoVTable*) ALIGN_TO((mword)_vtable, 8);
        gsize bmap;
 
        MonoDomain *domain = mono_get_root_domain ();
        g_assert (domain);
 
        klass.element_class = mono_defaults.byte_class;
        klass.rank = 1;
        klass.instance_size = MONO_SIZEOF_MONO_ARRAY;
        klass.sizes.element_size = 1;
        klass.size_inited = 1;
        klass.name = "array_filler_type";
 
        vtable->klass = &klass;
        bmap = 0;
        vtable->gc_descr = mono_gc_make_descr_for_array (TRUE, &bmap, 0, 1);
        vtable->rank = 1;
 
        array_fill_vtable = vtable;
    }
    return array_fill_vtable;
}
 
gboolean
sgen_client_array_fill_range (char *start, size_t size)
{
    MonoArray *o;
 
    if (size < MONO_SIZEOF_MONO_ARRAY) {
        memset (start, 0, size);
        return FALSE;
    }
 
    o = (MonoArray*)start;
    o->obj.vtable = (MonoVTable*)get_array_fill_vtable ();
    /* Mark this as not a real object */
    o->obj.synchronisation = (MonoThreadsSync *)GINT_TO_POINTER (-1);
    o->bounds = NULL;
    o->max_length = (mono_array_size_t)(size - MONO_SIZEOF_MONO_ARRAY);
 
    return TRUE;
}
 
void
sgen_client_zero_array_fill_header (void *p, size_t size)
{
    if (size >= MONO_SIZEOF_MONO_ARRAY) {
        memset (p, 0, MONO_SIZEOF_MONO_ARRAY);
    } else {
        static guint8 zeros [MONO_SIZEOF_MONO_ARRAY];
 
        SGEN_ASSERT (0, !memcmp (p, zeros, size), "TLAB segment must be zeroed out.");
    }
}
 
MonoVTable *
mono_gc_get_vtable (MonoObject *obj)
{
    // See sgen/sgen-tagged-pointer.h.
    return SGEN_LOAD_VTABLE (obj);
}
 
/*
 * Finalization
 */
 
static MonoGCFinalizerCallbacks fin_callbacks;
 
guint
mono_gc_get_vtable_bits (MonoClass *klass)
{
    guint res = 0;
    /* FIXME move this to the bridge code */
    if (sgen_need_bridge_processing ()) {
        switch (sgen_bridge_class_kind (klass)) {
        case GC_BRIDGE_TRANSPARENT_BRIDGE_CLASS:
        case GC_BRIDGE_OPAQUE_BRIDGE_CLASS:
            res = SGEN_GC_BIT_BRIDGE_OBJECT;
            break;
        case GC_BRIDGE_OPAQUE_CLASS:
            res = SGEN_GC_BIT_BRIDGE_OPAQUE_OBJECT;
            break;
        case GC_BRIDGE_TRANSPARENT_CLASS:
            break;
        }
    }
    if (fin_callbacks.is_class_finalization_aware) {
        if (fin_callbacks.is_class_finalization_aware (klass))
            res |= SGEN_GC_BIT_FINALIZER_AWARE;
    }
    return res;
}
 
static gboolean
is_finalization_aware (MonoObject *obj)
{
    MonoVTable *vt = SGEN_LOAD_VTABLE (obj);
    return (vt->gc_bits & SGEN_GC_BIT_FINALIZER_AWARE) == SGEN_GC_BIT_FINALIZER_AWARE;
}
 
void
sgen_client_object_queued_for_finalization (GCObject *obj)
{
    if (fin_callbacks.object_queued_for_finalization && is_finalization_aware (obj))
        fin_callbacks.object_queued_for_finalization (obj);
 
#ifdef ENABLE_DTRACE
    if (G_UNLIKELY (MONO_GC_FINALIZE_ENQUEUE_ENABLED ())) {
        int gen = sgen_ptr_in_nursery (obj) ? GENERATION_NURSERY : GENERATION_OLD;
        GCVTable vt = SGEN_LOAD_VTABLE (obj);
        MONO_GC_FINALIZE_ENQUEUE ((mword)obj, sgen_safe_object_get_size (obj),
                sgen_client_vtable_get_namespace (vt), sgen_client_vtable_get_name (vt), gen,
                sgen_client_object_has_critical_finalizer (obj));
    }
#endif
}
 
void
mono_gc_register_finalizer_callbacks (MonoGCFinalizerCallbacks *callbacks)
{
    if (callbacks->version != MONO_GC_FINALIZER_EXTENSION_VERSION)
        g_error ("Invalid finalizer callback version. Expected %d but got %d\n", MONO_GC_FINALIZER_EXTENSION_VERSION, callbacks->version);
 
    fin_callbacks = *callbacks;
}
 
void
sgen_client_run_finalize (MonoObject *obj)
{
    mono_gc_run_finalize (obj, NULL);
}
 
/**
 * mono_gc_invoke_finalizers:
 */
int
mono_gc_invoke_finalizers (void)
{
    return sgen_gc_invoke_finalizers ();
}
 
/**
 * mono_gc_pending_finalizers:
 */
MonoBoolean
mono_gc_pending_finalizers (void)
{
    return sgen_have_pending_finalizers ();
}
 
void
sgen_client_finalize_notify (void)
{
    mono_gc_finalize_notify ();
}
 
void
mono_gc_register_for_finalization (MonoObject *obj, void *user_data)
{
    sgen_object_register_for_finalization (obj, user_data);
}
 
static gboolean
object_in_domain_predicate (MonoObject *obj, void *user_data)
{
    MonoDomain *domain = (MonoDomain *)user_data;
    if (mono_object_domain (obj) == domain) {
        SGEN_LOG (5, "Unregistering finalizer for object: %p (%s)", obj, sgen_client_vtable_get_name (SGEN_LOAD_VTABLE (obj)));
        return TRUE;
    }
    return FALSE;
}
 
/**
 * mono_gc_finalizers_for_domain:
 * \param domain the unloading appdomain
 * \param out_array output array
 * \param out_size size of output array
 * Enqueue for finalization all objects that belong to the unloading appdomain \p domain.
 * \p suspend is used for early termination of the enqueuing process.
 */
void
mono_gc_finalize_domain (MonoDomain *domain)
{
    sgen_finalize_if (object_in_domain_predicate, domain);
}
 
void
mono_gc_suspend_finalizers (void)
{
    sgen_set_suspend_finalizers ();
}
 
/*
 * Ephemerons
 */
 
typedef struct _EphemeronLinkNode EphemeronLinkNode;
 
struct _EphemeronLinkNode {
    EphemeronLinkNode *next;
    MonoArray *array;
};
 
typedef struct {
       GCObject *key;
       GCObject *value;
} Ephemeron;
 
static EphemeronLinkNode *ephemeron_list;
 
/* LOCKING: requires that the GC lock is held */
static MONO_PERMIT (need (sgen_gc_locked)) void
null_ephemerons_for_domain (MonoDomain *domain)
{
    EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
 
    while (current) {
        MonoObject *object = (MonoObject*)current->array;
 
        if (object)
            SGEN_ASSERT (0, object->vtable, "Can't have objects without vtables.");
 
        if (object && object->vtable->domain == domain) {
            EphemeronLinkNode *tmp = current;
 
            if (prev)
                prev->next = current->next;
            else
                ephemeron_list = current->next;
 
            current = current->next;
            sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
        } else {
            prev = current;
            current = current->next;
        }
    }
}
 
/* LOCKING: requires that the GC lock is held */
void
sgen_client_clear_unreachable_ephemerons (ScanCopyContext ctx)
{
    CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
    SgenGrayQueue *queue = ctx.queue;
    EphemeronLinkNode *current = ephemeron_list, *prev = NULL;
    Ephemeron *cur, *array_end;
    GCObject *tombstone;
 
    while (current) {
        MonoArray *array = current->array;
 
        if (!sgen_is_object_alive_for_current_gen ((GCObject*)array)) {
            EphemeronLinkNode *tmp = current;
 
            SGEN_LOG (5, "Dead Ephemeron array at %p", array);
 
            if (prev)
                prev->next = current->next;
            else
                ephemeron_list = current->next;
 
            current = current->next;
            sgen_free_internal (tmp, INTERNAL_MEM_EPHEMERON_LINK);
 
            continue;
        }
 
        copy_func ((GCObject**)&array, queue);
        current->array = array;
 
        SGEN_LOG (5, "Clearing unreachable entries for ephemeron array at %p", array);
 
        cur = mono_array_addr (array, Ephemeron, 0);
        array_end = cur + mono_array_length_fast (array);
        tombstone = SGEN_LOAD_VTABLE ((GCObject*)array)->domain->ephemeron_tombstone;
 
        for (; cur < array_end; ++cur) {
            GCObject *key = cur->key;
 
            if (!key || key == tombstone)
                continue;
 
            SGEN_LOG (5, "[%zd] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
                key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
                cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
 
            if (!sgen_is_object_alive_for_current_gen (key)) {
                cur->key = tombstone;
                cur->value = NULL;
                continue;
            }
        }
        prev = current;
        current = current->next;
    }
}
 
/*
LOCKING: requires that the GC lock is held
 
Limitations: We scan all ephemerons on every collection since the current design doesn't allow for a simple nursery/mature split.
*/
gboolean
sgen_client_mark_ephemerons (ScanCopyContext ctx)
{
    CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object;
    SgenGrayQueue *queue = ctx.queue;
    gboolean nothing_marked = TRUE;
    EphemeronLinkNode *current = ephemeron_list;
    Ephemeron *cur, *array_end;
    GCObject *tombstone;
 
    for (current = ephemeron_list; current; current = current->next) {
        MonoArray *array = current->array;
        SGEN_LOG (5, "Ephemeron array at %p", array);
 
        /*It has to be alive*/
        if (!sgen_is_object_alive_for_current_gen ((GCObject*)array)) {
            SGEN_LOG (5, "\tnot reachable");
            continue;
        }
 
        copy_func ((GCObject**)&array, queue);
 
        cur = mono_array_addr (array, Ephemeron, 0);
        array_end = cur + mono_array_length_fast (array);
        tombstone = SGEN_LOAD_VTABLE ((GCObject*)array)->domain->ephemeron_tombstone;
 
        for (; cur < array_end; ++cur) {
            GCObject *key = cur->key;
 
            if (!key || key == tombstone)
                continue;
 
            SGEN_LOG (5, "[%zd] key %p (%s) value %p (%s)", cur - mono_array_addr (array, Ephemeron, 0),
                key, sgen_is_object_alive_for_current_gen (key) ? "reachable" : "unreachable",
                cur->value, cur->value && sgen_is_object_alive_for_current_gen (cur->value) ? "reachable" : "unreachable");
 
            if (sgen_is_object_alive_for_current_gen (key)) {
                GCObject *value = cur->value;
 
                copy_func (&cur->key, queue);
                if (value) {
                    if (!sgen_is_object_alive_for_current_gen (value))
                        nothing_marked = FALSE;
                    copy_func (&cur->value, queue);
                }
            }
        }
    }
 
    SGEN_LOG (5, "Ephemeron run finished. Is it done %d", nothing_marked);
    return nothing_marked;
}
 
gboolean
mono_gc_ephemeron_array_add (MonoObject *obj)
{
    EphemeronLinkNode *node;
 
    LOCK_GC;
 
    node = (EphemeronLinkNode *)sgen_alloc_internal (INTERNAL_MEM_EPHEMERON_LINK);
    if (!node) {
        UNLOCK_GC;
        return FALSE;
    }
    node->array = (MonoArray*)obj;
    node->next = ephemeron_list;
    ephemeron_list = node;
 
    SGEN_LOG (5, "Registered ephemeron array %p", obj);
 
    UNLOCK_GC;
    return TRUE;
}
 
/*
 * Appdomain handling
 */
 
static gboolean
need_remove_object_for_domain (GCObject *start, MonoDomain *domain)
{
    if (mono_object_domain (start) == domain) {
        SGEN_LOG (4, "Need to cleanup object %p", start);
        binary_protocol_cleanup (start, (gpointer)SGEN_LOAD_VTABLE (start), sgen_safe_object_get_size ((GCObject*)start));
        return TRUE;
    }
    return FALSE;
}
 
static void
process_object_for_domain_clearing (GCObject *start, MonoDomain *domain)
{
    MonoVTable *vt = SGEN_LOAD_VTABLE (start);
    if (vt->klass == mono_defaults.internal_thread_class)
        g_assert (mono_object_domain (start) == mono_get_root_domain ());
    /* The object could be a proxy for an object in the domain
       we're deleting. */
#ifndef DISABLE_REMOTING
    if (mono_defaults.real_proxy_class->supertypes && mono_class_has_parent_fast (vt->klass, mono_defaults.real_proxy_class)) {
        MonoObject *server = ((MonoRealProxy*)start)->unwrapped_server;
 
        /* The server could already have been zeroed out, so
           we need to check for that, too. */
        if (server && (!SGEN_LOAD_VTABLE (server) || mono_object_domain (server) == domain)) {
            SGEN_LOG (4, "Cleaning up remote pointer in %p to object %p", start, server);
            ((MonoRealProxy*)start)->unwrapped_server = NULL;
        }
    }
#endif
}
 
static gboolean
clear_domain_process_object (GCObject *obj, MonoDomain *domain)
{
    gboolean remove;
 
    process_object_for_domain_clearing (obj, domain);
    remove = need_remove_object_for_domain (obj, domain);
 
    if (remove && obj->synchronisation) {
        guint32 dislink = mono_monitor_get_object_monitor_gchandle (obj);
        if (dislink)
            mono_gchandle_free (dislink);
    }
 
    return remove;
}
 
static void
clear_domain_process_minor_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
{
    if (clear_domain_process_object (obj, domain)) {
        CANARIFY_SIZE (size);
        memset (obj, 0, size);
    }
}
 
static void
clear_domain_process_major_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
{
    clear_domain_process_object (obj, domain);
}
 
static void
clear_domain_free_major_non_pinned_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
{
    if (need_remove_object_for_domain (obj, domain))
        major_collector.free_non_pinned_object (obj, size);
}
 
static void
clear_domain_free_major_pinned_object_callback (GCObject *obj, size_t size, MonoDomain *domain)
{
    if (need_remove_object_for_domain (obj, domain))
        major_collector.free_pinned_object (obj, size);
}
 
/*
 * When appdomains are unloaded we can easily remove objects that have finalizers,
 * but all the others could still be present in random places on the heap.
 * We need a sweep to get rid of them even though it's going to be costly
 * with big heaps.
 * The reason we need to remove them is because we access the vtable and class
 * structures to know the object size and the reference bitmap: once the domain is
 * unloaded the point to random memory.
 */
void
mono_gc_clear_domain (MonoDomain * domain)
{
    LOSObject *bigobj, *prev;
    int i;
 
    LOCK_GC;
 
    binary_protocol_domain_unload_begin (domain);
 
    sgen_stop_world (0);
 
    if (sgen_concurrent_collection_in_progress ())
        sgen_perform_collection (0, GENERATION_OLD, "clear domain", TRUE, FALSE);
    SGEN_ASSERT (0, !sgen_concurrent_collection_in_progress (), "We just ordered a synchronous collection.  Why are we collecting concurrently?");
 
    major_collector.finish_sweeping ();
 
    sgen_process_fin_stage_entries ();
 
    sgen_clear_nursery_fragments ();
 
    FOREACH_THREAD (info) {
        mono_handle_stack_free_domain ((HandleStack*)info->client_info.info.handle_stack, domain);
    } FOREACH_THREAD_END
 
    if (sgen_mono_xdomain_checks && domain != mono_get_root_domain ()) {
        sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_NORMAL);
        sgen_scan_for_registered_roots_in_domain (domain, ROOT_TYPE_WBARRIER);
        sgen_check_for_xdomain_refs ();
    }
 
    /*Ephemerons and dislinks must be processed before LOS since they might end up pointing
    to memory returned to the OS.*/
    null_ephemerons_for_domain (domain);
    sgen_null_links_for_domain (domain);
 
    for (i = GENERATION_NURSERY; i < GENERATION_MAX; ++i)
        sgen_remove_finalizers_if (object_in_domain_predicate, domain, i);
 
    sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data,
            (IterateObjectCallbackFunc)clear_domain_process_minor_object_callback, domain, FALSE, TRUE);
 
    /* We need two passes over major and large objects because
       freeing such objects might give their memory back to the OS
       (in the case of large objects) or obliterate its vtable
       (pinned objects with major-copying or pinned and non-pinned
       objects with major-mark&sweep), but we might need to
       dereference a pointer from an object to another object if
       the first object is a proxy. */
    major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, (IterateObjectCallbackFunc)clear_domain_process_major_object_callback, domain);
    for (bigobj = los_object_list; bigobj; bigobj = bigobj->next)
        clear_domain_process_object ((GCObject*)bigobj->data, domain);
 
    prev = NULL;
    for (bigobj = los_object_list; bigobj;) {
        if (need_remove_object_for_domain ((GCObject*)bigobj->data, domain)) {
            LOSObject *to_free = bigobj;
            if (prev)
                prev->next = bigobj->next;
            else
                los_object_list = bigobj->next;
            bigobj = bigobj->next;
            SGEN_LOG (4, "Freeing large object %p", bigobj->data);
            sgen_los_free_object (to_free);
            continue;
        }
        prev = bigobj;
        bigobj = bigobj->next;
    }
    major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_NON_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_non_pinned_object_callback, domain);
    major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_PINNED, (IterateObjectCallbackFunc)clear_domain_free_major_pinned_object_callback, domain);
 
    if (domain == mono_get_root_domain ()) {
        sgen_pin_stats_report ();
        sgen_object_layout_dump (stdout);
    }
 
    sgen_restart_world (0);
 
    binary_protocol_domain_unload_end (domain);
    binary_protocol_flush_buffers (FALSE);
 
    UNLOCK_GC;
}
 
/*
 * Allocation
 */
 
void*
mono_gc_alloc_obj (MonoVTable *vtable, size_t size)
{
    MonoObject *obj = sgen_alloc_obj (vtable, size);
 
    if (G_UNLIKELY (mono_profiler_allocations_enabled ()) && obj)
        MONO_PROFILER_RAISE (gc_allocation, (obj));
 
    return obj;
}
 
void*
mono_gc_alloc_pinned_obj (MonoVTable *vtable, size_t size)
{
    MonoObject *obj = sgen_alloc_obj_pinned (vtable, size);
 
    if (G_UNLIKELY (mono_profiler_allocations_enabled ()) && obj)
        MONO_PROFILER_RAISE (gc_allocation, (obj));
 
    return obj;
}
 
void*
mono_gc_alloc_mature (MonoVTable *vtable, size_t size)
{
    MonoObject *obj = sgen_alloc_obj_mature (vtable, size);
 
    if (G_UNLIKELY (mono_profiler_allocations_enabled ()) && obj)
        MONO_PROFILER_RAISE (gc_allocation, (obj));
 
    return obj;
}
 
/**
 * mono_gc_alloc_fixed:
 */
void*
mono_gc_alloc_fixed (size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg)
{
    /* FIXME: do a single allocation */
    void *res = g_calloc (1, size);
    if (!res)
        return NULL;
    if (!mono_gc_register_root ((char *)res, size, descr, source, key, msg)) {
        g_free (res);
        res = NULL;
    }
    return res;
}
 
/**
 * mono_gc_free_fixed:
 */
void
mono_gc_free_fixed (void* addr)
{
    mono_gc_deregister_root ((char *)addr);
    g_free (addr);
}
 
/*
 * Managed allocator
 */
 
static MonoMethod* alloc_method_cache [ATYPE_NUM];
static MonoMethod* slowpath_alloc_method_cache [ATYPE_NUM];
static MonoMethod* profiler_alloc_method_cache [ATYPE_NUM];
static gboolean use_managed_allocator = TRUE;
 
#ifdef MANAGED_ALLOCATION
// Cache the SgenThreadInfo pointer in a local 'var'.
#define EMIT_TLS_ACCESS_VAR(mb, var) \
    do { \
        var = mono_mb_add_local ((mb), &mono_defaults.int_class->byval_arg); \
        mono_mb_emit_byte ((mb), MONO_CUSTOM_PREFIX); \
        mono_mb_emit_byte ((mb), CEE_MONO_TLS); \
        mono_mb_emit_i4 ((mb), TLS_KEY_SGEN_THREAD_INFO); \
        mono_mb_emit_stloc ((mb), (var)); \
    } while (0)
 
#define EMIT_TLS_ACCESS_IN_CRITICAL_REGION_ADDR(mb, var) \
    do { \
        mono_mb_emit_ldloc ((mb), (var)); \
        mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenClientThreadInfo, in_critical_region)); \
        mono_mb_emit_byte ((mb), CEE_ADD); \
    } while (0)
 
#define EMIT_TLS_ACCESS_NEXT_ADDR(mb, var)    do {    \
    mono_mb_emit_ldloc ((mb), (var));        \
    mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenThreadInfo, tlab_next));    \
    mono_mb_emit_byte ((mb), CEE_ADD);        \
    } while (0)
 
#define EMIT_TLS_ACCESS_TEMP_END(mb, var)    do {    \
    mono_mb_emit_ldloc ((mb), (var));        \
    mono_mb_emit_icon ((mb), MONO_STRUCT_OFFSET (SgenThreadInfo, tlab_temp_end));    \
    mono_mb_emit_byte ((mb), CEE_ADD);        \
    mono_mb_emit_byte ((mb), CEE_LDIND_I);        \
    } while (0)
 
/* FIXME: Do this in the JIT, where specialized allocation sequences can be created
 * for each class. This is currently not easy to do, as it is hard to generate basic 
 * blocks + branches, but it is easy with the linear IL codebase.
 *
 * For this to work we'd need to solve the TLAB race, first.  Now we
 * require the allocator to be in a few known methods to make sure
 * that they are executed atomically via the restart mechanism.
 */
static MonoMethod*
create_allocator (int atype, ManagedAllocatorVariant variant)
{
    int p_var, size_var, real_size_var, thread_var G_GNUC_UNUSED;
    gboolean slowpath = variant == MANAGED_ALLOCATOR_SLOW_PATH;
    gboolean profiler = variant == MANAGED_ALLOCATOR_PROFILER;
    guint32 fastpath_branch, max_size_branch, no_oom_branch;
    MonoMethodBuilder *mb;
    MonoMethod *res;
    MonoMethodSignature *csig;
    static gboolean registered = FALSE;
    int tlab_next_addr_var, new_next_var;
    const char *name = NULL;
    WrapperInfo *info;
    int num_params, i;
 
    if (!registered) {
        mono_register_jit_icall (mono_gc_alloc_obj, "mono_gc_alloc_obj", mono_create_icall_signature ("object ptr int"), FALSE);
        mono_register_jit_icall (mono_gc_alloc_vector, "mono_gc_alloc_vector", mono_create_icall_signature ("object ptr int int"), FALSE);
        mono_register_jit_icall (mono_gc_alloc_string, "mono_gc_alloc_string", mono_create_icall_signature ("object ptr int int32"), FALSE);
        mono_register_jit_icall (mono_profiler_raise_gc_allocation, "mono_profiler_raise_gc_allocation", mono_create_icall_signature ("void object"), FALSE);
        registered = TRUE;
    }
 
    if (atype == ATYPE_SMALL) {
        name = slowpath ? "SlowAllocSmall" : (profiler ? "ProfilerAllocSmall" : "AllocSmall");
    } else if (atype == ATYPE_NORMAL) {
        name = slowpath ? "SlowAlloc" : (profiler ? "ProfilerAlloc" : "Alloc");
    } else if (atype == ATYPE_VECTOR) {
        name = slowpath ? "SlowAllocVector" : (profiler ? "ProfilerAllocVector" : "AllocVector");
    } else if (atype == ATYPE_STRING) {
        name = slowpath ? "SlowAllocString" : (profiler ? "ProfilerAllocString" : "AllocString");
    } else {
        g_assert_not_reached ();
    }
 
    if (atype == ATYPE_NORMAL)
        num_params = 1;
    else
        num_params = 2;
 
    csig = mono_metadata_signature_alloc (mono_defaults.corlib, num_params);
    if (atype == ATYPE_STRING) {
        csig->ret = &mono_defaults.string_class->byval_arg;
        csig->params [0] = &mono_defaults.int_class->byval_arg;
        csig->params [1] = &mono_defaults.int32_class->byval_arg;
    } else {
        csig->ret = &mono_defaults.object_class->byval_arg;
        for (i = 0; i < num_params; i++)
            csig->params [i] = &mono_defaults.int_class->byval_arg;
    }
 
    mb = mono_mb_new (mono_defaults.object_class, name, MONO_WRAPPER_ALLOC);
 
#ifdef ENABLE_ILGEN
    if (slowpath) {
        switch (atype) {
        case ATYPE_NORMAL:
        case ATYPE_SMALL:
            mono_mb_emit_ldarg (mb, 0);
            mono_mb_emit_icall (mb, ves_icall_object_new_specific);
            break;
        case ATYPE_VECTOR:
            mono_mb_emit_ldarg (mb, 0);
            mono_mb_emit_ldarg (mb, 1);
            mono_mb_emit_icall (mb, ves_icall_array_new_specific);
            break;
        case ATYPE_STRING:
            mono_mb_emit_ldarg (mb, 1);
            mono_mb_emit_icall (mb, ves_icall_string_alloc);
            break;
        default:
            g_assert_not_reached ();
        }
 
        goto done;
    }
 
    /*
     * Tls access might call foreign code or code without jinfo. This can
     * only happen if we are outside of the critical region.
     */
    EMIT_TLS_ACCESS_VAR (mb, thread_var);
 
    size_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
    if (atype == ATYPE_SMALL) {
        /* size_var = size_arg */
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_stloc (mb, size_var);
    } else if (atype == ATYPE_NORMAL) {
        /* size = vtable->klass->instance_size; */
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
        mono_mb_emit_byte (mb, CEE_ADD);
        mono_mb_emit_byte (mb, CEE_LDIND_I);
        mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, instance_size));
        mono_mb_emit_byte (mb, CEE_ADD);
        /* FIXME: assert instance_size stays a 4 byte integer */
        mono_mb_emit_byte (mb, CEE_LDIND_U4);
        mono_mb_emit_byte (mb, CEE_CONV_I);
        mono_mb_emit_stloc (mb, size_var);
    } else if (atype == ATYPE_VECTOR) {
        MonoExceptionClause *clause;
        int pos, pos_leave, pos_error;
        MonoClass *oom_exc_class;
        MonoMethod *ctor;
 
        /*
         * n > MONO_ARRAY_MAX_INDEX => OutOfMemoryException
         * n < 0                    => OverflowException
         *
         * We can do an unsigned comparison to catch both cases, then in the error
         * case compare signed to distinguish between them.
         */
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_icon (mb, MONO_ARRAY_MAX_INDEX);
        mono_mb_emit_byte (mb, CEE_CONV_U);
        pos = mono_mb_emit_short_branch (mb, CEE_BLE_UN_S);
 
        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
        mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_icon (mb, 0);
        pos_error = mono_mb_emit_short_branch (mb, CEE_BLT_S);
        mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
        mono_mb_patch_short_branch (mb, pos_error);
        mono_mb_emit_exception (mb, "OverflowException", NULL);
 
        mono_mb_patch_short_branch (mb, pos);
 
        clause = (MonoExceptionClause *)mono_image_alloc0 (mono_defaults.corlib, sizeof (MonoExceptionClause));
        clause->try_offset = mono_mb_get_label (mb);
 
        /* vtable->klass->sizes.element_size */
        mono_mb_emit_ldarg (mb, 0);
        mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoVTable, klass));
        mono_mb_emit_byte (mb, CEE_ADD);
        mono_mb_emit_byte (mb, CEE_LDIND_I);
        mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoClass, sizes));
        mono_mb_emit_byte (mb, CEE_ADD);
        mono_mb_emit_byte (mb, CEE_LDIND_U4);
        mono_mb_emit_byte (mb, CEE_CONV_I);
 
        /* * n */
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_byte (mb, CEE_MUL_OVF_UN);
        /* + sizeof (MonoArray) */
        mono_mb_emit_icon (mb, MONO_SIZEOF_MONO_ARRAY);
        mono_mb_emit_byte (mb, CEE_ADD_OVF_UN);
        mono_mb_emit_stloc (mb, size_var);
 
        pos_leave = mono_mb_emit_branch (mb, CEE_LEAVE);
 
        /* catch */
        clause->flags = MONO_EXCEPTION_CLAUSE_NONE;
        clause->try_len = mono_mb_get_pos (mb) - clause->try_offset;
        clause->data.catch_class = mono_class_load_from_name (mono_defaults.corlib,
                "System", "OverflowException");
        clause->handler_offset = mono_mb_get_label (mb);
 
        oom_exc_class = mono_class_load_from_name (mono_defaults.corlib,
                "System", "OutOfMemoryException");
        ctor = mono_class_get_method_from_name (oom_exc_class, ".ctor", 0);
        g_assert (ctor);
 
        mono_mb_emit_byte (mb, CEE_POP);
        mono_mb_emit_op (mb, CEE_NEWOBJ, ctor);
        mono_mb_emit_byte (mb, CEE_THROW);
 
        clause->handler_len = mono_mb_get_pos (mb) - clause->handler_offset;
        mono_mb_set_clauses (mb, 1, clause);
        mono_mb_patch_branch (mb, pos_leave);
        /* end catch */
    } else if (atype == ATYPE_STRING) {
        int pos;
 
        /*
         * a string allocator method takes the args: (vtable, len)
         *
         * bytes = offsetof (MonoString, chars) + ((len + 1) * 2)
         *
         * condition:
         *
         * bytes <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
         *
         * therefore:
         *
         * offsetof (MonoString, chars) + ((len + 1) * 2) <= INT32_MAX - (SGEN_ALLOC_ALIGN - 1)
         * len <= (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - offsetof (MonoString, chars)) / 2 - 1
         */
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_icon (mb, (INT32_MAX - (SGEN_ALLOC_ALIGN - 1) - MONO_STRUCT_OFFSET (MonoString, chars)) / 2 - 1);
        pos = mono_mb_emit_short_branch (mb, MONO_CEE_BLE_UN_S);
 
        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
        mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
        mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
        mono_mb_patch_short_branch (mb, pos);
 
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_icon (mb, 1);
        mono_mb_emit_byte (mb, MONO_CEE_SHL);
        //WE manually fold the above + 2 here
        mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoString, chars) + 2);
        mono_mb_emit_byte (mb, CEE_ADD);
        mono_mb_emit_stloc (mb, size_var);
    } else {
        g_assert_not_reached ();
    }
 
#ifdef MANAGED_ALLOCATOR_CAN_USE_CRITICAL_REGION
    EMIT_TLS_ACCESS_IN_CRITICAL_REGION_ADDR (mb, thread_var);
    mono_mb_emit_byte (mb, CEE_LDC_I4_1);
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_ATOMIC_STORE_I4);
    mono_mb_emit_i4 (mb, MONO_MEMORY_BARRIER_NONE);
#endif
 
    if (nursery_canaries_enabled ()) {
        real_size_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
        mono_mb_emit_ldloc (mb, size_var);
        mono_mb_emit_stloc(mb, real_size_var);
    }
    else
        real_size_var = size_var;
 
    /* size += ALLOC_ALIGN - 1; */
    mono_mb_emit_ldloc (mb, size_var);
    mono_mb_emit_icon (mb, SGEN_ALLOC_ALIGN - 1);
    mono_mb_emit_byte (mb, CEE_ADD);
    /* size &= ~(ALLOC_ALIGN - 1); */
    mono_mb_emit_icon (mb, ~(SGEN_ALLOC_ALIGN - 1));
    mono_mb_emit_byte (mb, CEE_AND);
    mono_mb_emit_stloc (mb, size_var);
 
    /* if (size > MAX_SMALL_OBJ_SIZE) goto slowpath */
    if (atype != ATYPE_SMALL) {
        mono_mb_emit_ldloc (mb, size_var);
        mono_mb_emit_icon (mb, SGEN_MAX_SMALL_OBJ_SIZE);
        max_size_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BGT_UN_S);
    }
 
    /*
     * We need to modify tlab_next, but the JIT only supports reading, so we read
     * another tls var holding its address instead.
     */
 
    /* tlab_next_addr (local) = tlab_next_addr (TLS var) */
    tlab_next_addr_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
    EMIT_TLS_ACCESS_NEXT_ADDR (mb, thread_var);
    mono_mb_emit_stloc (mb, tlab_next_addr_var);
 
    /* p = (void**)tlab_next; */
    p_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
    mono_mb_emit_ldloc (mb, tlab_next_addr_var);
    mono_mb_emit_byte (mb, CEE_LDIND_I);
    mono_mb_emit_stloc (mb, p_var);
    
    /* new_next = (char*)p + size; */
    new_next_var = mono_mb_add_local (mb, &mono_defaults.int_class->byval_arg);
    mono_mb_emit_ldloc (mb, p_var);
    mono_mb_emit_ldloc (mb, size_var);
    mono_mb_emit_byte (mb, CEE_CONV_I);
    mono_mb_emit_byte (mb, CEE_ADD);
 
    if (nursery_canaries_enabled ()) {
            mono_mb_emit_icon (mb, CANARY_SIZE);
            mono_mb_emit_byte (mb, CEE_ADD);
    }
    mono_mb_emit_stloc (mb, new_next_var);
 
    /* if (G_LIKELY (new_next < tlab_temp_end)) */
    mono_mb_emit_ldloc (mb, new_next_var);
    EMIT_TLS_ACCESS_TEMP_END (mb, thread_var);
    fastpath_branch = mono_mb_emit_short_branch (mb, MONO_CEE_BLT_UN_S);
 
    /* Slowpath */
    if (atype != ATYPE_SMALL)
        mono_mb_patch_short_branch (mb, max_size_branch);
 
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
    /*
     * We are no longer in a critical section. We need to do this before calling
     * to unmanaged land in order to avoid stw deadlocks since unmanaged code
     * might take locks.
     */
#ifdef MANAGED_ALLOCATOR_CAN_USE_CRITICAL_REGION
    EMIT_TLS_ACCESS_IN_CRITICAL_REGION_ADDR (mb, thread_var);
    mono_mb_emit_byte (mb, CEE_LDC_I4_0);
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_ATOMIC_STORE_I4);
    mono_mb_emit_i4 (mb, MONO_MEMORY_BARRIER_NONE);
#endif
 
    /* FIXME: mono_gc_alloc_obj takes a 'size_t' as an argument, not an int32 */
    mono_mb_emit_ldarg (mb, 0);
    mono_mb_emit_ldloc (mb, real_size_var);
    if (atype == ATYPE_NORMAL || atype == ATYPE_SMALL) {
        mono_mb_emit_icall (mb, mono_gc_alloc_obj);
    } else if (atype == ATYPE_VECTOR) {
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_icall (mb, mono_gc_alloc_vector);
    } else if (atype == ATYPE_STRING) {
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_icall (mb, mono_gc_alloc_string);
    } else {
        g_assert_not_reached ();
    }
 
    /* if (ret == NULL) throw OOM; */
    mono_mb_emit_byte (mb, CEE_DUP);
    no_oom_branch = mono_mb_emit_branch (mb, CEE_BRTRUE);
    mono_mb_emit_exception (mb, "OutOfMemoryException", NULL);
 
    mono_mb_patch_branch (mb, no_oom_branch);
    mono_mb_emit_byte (mb, CEE_RET);
 
    /* Fastpath */
    mono_mb_patch_short_branch (mb, fastpath_branch);
 
    /* FIXME: Memory barrier */
 
    /* tlab_next = new_next */
    mono_mb_emit_ldloc (mb, tlab_next_addr_var);
    mono_mb_emit_ldloc (mb, new_next_var);
    mono_mb_emit_byte (mb, CEE_STIND_I);
 
    /* *p = vtable; */
    mono_mb_emit_ldloc (mb, p_var);
    mono_mb_emit_ldarg (mb, 0);
    mono_mb_emit_byte (mb, CEE_STIND_I);
 
    /* mark object end with nursery word */
    if (nursery_canaries_enabled ()) {
            mono_mb_emit_ldloc (mb, p_var);
            mono_mb_emit_ldloc (mb, real_size_var);
            mono_mb_emit_byte (mb, MONO_CEE_ADD);
            mono_mb_emit_icon8 (mb, (mword) CANARY_STRING);
            mono_mb_emit_icon (mb, CANARY_SIZE);
            mono_mb_emit_byte (mb, MONO_CEE_PREFIX1);
            mono_mb_emit_byte (mb, CEE_CPBLK);
    }
 
    if (atype == ATYPE_VECTOR) {
        /* arr->max_length = max_length; */
        mono_mb_emit_ldloc (mb, p_var);
        mono_mb_emit_ldflda (mb, MONO_STRUCT_OFFSET (MonoArray, max_length));
        mono_mb_emit_ldarg (mb, 1);
#ifdef MONO_BIG_ARRAYS
        mono_mb_emit_byte (mb, CEE_STIND_I);
#else
        mono_mb_emit_byte (mb, CEE_STIND_I4);
#endif
    } else     if (atype == ATYPE_STRING) {
        /* need to set length and clear the last char */
        /* s->length = len; */
        mono_mb_emit_ldloc (mb, p_var);
        mono_mb_emit_icon (mb, MONO_STRUCT_OFFSET (MonoString, length));
        mono_mb_emit_byte (mb, MONO_CEE_ADD);
        mono_mb_emit_ldarg (mb, 1);
        mono_mb_emit_byte (mb, MONO_CEE_STIND_I4);
    }
 
#ifdef MANAGED_ALLOCATOR_CAN_USE_CRITICAL_REGION
    EMIT_TLS_ACCESS_IN_CRITICAL_REGION_ADDR (mb, thread_var);
    mono_mb_emit_byte (mb, CEE_LDC_I4_0);
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_ATOMIC_STORE_I4);
#else
    mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
    mono_mb_emit_byte (mb, CEE_MONO_MEMORY_BARRIER);
#endif
    /*
    We must make sure both vtable and max_length are globaly visible before returning to managed land.
    */
    mono_mb_emit_i4 (mb, MONO_MEMORY_BARRIER_REL);
 
    /* return p */
    mono_mb_emit_ldloc (mb, p_var);
 
 done:
 
    /*
     * It's important that we do this outside of the critical region as we
     * will be invoking arbitrary code.
     */
    if (profiler) {
        /*
         * if (G_UNLIKELY (*&mono_profiler_state.gc_allocation_count)) {
         *     mono_profiler_raise_gc_allocation (p);
         * }
         */
 
        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
        mono_mb_emit_byte (mb, CEE_MONO_LDPTR_PROFILER_ALLOCATION_COUNT);
        mono_mb_emit_byte (mb, CEE_LDIND_U4);
 
        int prof_br = mono_mb_emit_short_branch (mb, CEE_BRFALSE_S);
 
        mono_mb_emit_byte (mb, MONO_CUSTOM_PREFIX);
        mono_mb_emit_byte (mb, CEE_MONO_NOT_TAKEN);
        mono_mb_emit_byte (mb, CEE_DUP);
        mono_mb_emit_icall (mb, mono_profiler_raise_gc_allocation);
 
        mono_mb_patch_short_branch (mb, prof_br);
    }
 
    mono_mb_emit_byte (mb, CEE_RET);
#endif
 
    info = mono_wrapper_info_create (mb, WRAPPER_SUBTYPE_NONE);
    info->d.alloc.gc_name = "sgen";
    info->d.alloc.alloc_type = atype;
 
#ifdef ENABLE_ILGEN
    mb->init_locals = FALSE;
#endif
 
    res = mono_mb_create (mb, csig, 8, info);
    mono_mb_free (mb);
 
 
    return res;
}
#endif
 
int
mono_gc_get_aligned_size_for_allocator (int size)
{
    return SGEN_ALIGN_UP (size);
}
 
/*
 * Generate an allocator method implementing the fast path of mono_gc_alloc_obj ().
 * The signature of the called method is:
 *     object allocate (MonoVTable *vtable)
 */
MonoMethod*
mono_gc_get_managed_allocator (MonoClass *klass, gboolean for_box, gboolean known_instance_size)
{
#ifdef MANAGED_ALLOCATION
    ManagedAllocatorVariant variant = mono_profiler_allocations_enabled () ?
        MANAGED_ALLOCATOR_PROFILER : MANAGED_ALLOCATOR_REGULAR;
 
    if (collect_before_allocs)
        return NULL;
    if (klass->instance_size > tlab_size)
        return NULL;
    if (known_instance_size && ALIGN_TO (klass->instance_size, SGEN_ALLOC_ALIGN) >= SGEN_MAX_SMALL_OBJ_SIZE)
        return NULL;
    if (mono_class_has_finalizer (klass) || mono_class_is_marshalbyref (klass) || klass->has_weak_fields)
        return NULL;
    if (klass->rank)
        return NULL;
    if (klass->byval_arg.type == MONO_TYPE_STRING)
        return mono_gc_get_managed_allocator_by_type (ATYPE_STRING, variant);
    /* Generic classes have dynamic field and can go above MAX_SMALL_OBJ_SIZE. */
    if (known_instance_size)
        return mono_gc_get_managed_allocator_by_type (ATYPE_SMALL, variant);
    else
        return mono_gc_get_managed_allocator_by_type (ATYPE_NORMAL, variant);
#else
    return NULL;
#endif
}
 
MonoMethod*
mono_gc_get_managed_array_allocator (MonoClass *klass)
{
#ifdef MANAGED_ALLOCATION
    if (klass->rank != 1)
        return NULL;
    if (has_per_allocation_action)
        return NULL;
    g_assert (!mono_class_has_finalizer (klass) && !mono_class_is_marshalbyref (klass));
 
    return mono_gc_get_managed_allocator_by_type (ATYPE_VECTOR, mono_profiler_allocations_enabled () ?
        MANAGED_ALLOCATOR_PROFILER : MANAGED_ALLOCATOR_REGULAR);
#else
    return NULL;
#endif
}
 
void
sgen_set_use_managed_allocator (gboolean flag)
{
    use_managed_allocator = flag;
}
 
MonoMethod*
mono_gc_get_managed_allocator_by_type (int atype, ManagedAllocatorVariant variant)
{
#ifdef MANAGED_ALLOCATION
    MonoMethod *res;
    MonoMethod **cache;
 
    if (variant != MANAGED_ALLOCATOR_SLOW_PATH && !use_managed_allocator)
        return NULL;
 
    switch (variant) {
    case MANAGED_ALLOCATOR_REGULAR: cache = alloc_method_cache; break;
    case MANAGED_ALLOCATOR_SLOW_PATH: cache = slowpath_alloc_method_cache; break;
    case MANAGED_ALLOCATOR_PROFILER: cache = profiler_alloc_method_cache; break;
    default: g_assert_not_reached (); break;
    }
 
    res = cache [atype];
    if (res)
        return res;
 
    res = create_allocator (atype, variant);
    LOCK_GC;
    if (cache [atype]) {
        mono_free_method (res);
        res = cache [atype];
    } else {
        mono_memory_barrier ();
        cache [atype] = res;
    }
    UNLOCK_GC;
 
    return res;
#else
    return NULL;
#endif
}
 
guint32
mono_gc_get_managed_allocator_types (void)
{
    return ATYPE_NUM;
}
 
gboolean
sgen_is_managed_allocator (MonoMethod *method)
{
    int i;
 
    for (i = 0; i < ATYPE_NUM; ++i)
        if (method == alloc_method_cache [i] || method == slowpath_alloc_method_cache [i] || method == profiler_alloc_method_cache [i])
            return TRUE;
    return FALSE;
}
 
gboolean
sgen_has_managed_allocator (void)
{
    int i;
 
    for (i = 0; i < ATYPE_NUM; ++i)
        if (alloc_method_cache [i] || slowpath_alloc_method_cache [i] || profiler_alloc_method_cache [i])
            return TRUE;
    return FALSE;
}
 
#define ARRAY_OBJ_INDEX(ptr,array,elem_size) (((char*)(ptr) - ((char*)(array) + G_STRUCT_OFFSET (MonoArray, vector))) / (elem_size))
 
gboolean
sgen_client_cardtable_scan_object (GCObject *obj, guint8 *cards, ScanCopyContext ctx)
{
    MonoVTable *vt = SGEN_LOAD_VTABLE (obj);
    MonoClass *klass = vt->klass;
 
    SGEN_ASSERT (0, SGEN_VTABLE_HAS_REFERENCES (vt), "Why would we ever call this on reference-free objects?");
 
    if (vt->rank) {
        MonoArray *arr = (MonoArray*)obj;
        guint8 *card_data, *card_base;
        guint8 *card_data_end;
        char *obj_start = (char *)sgen_card_table_align_pointer (obj);
        mword bounds_size;
        mword obj_size = sgen_mono_array_size (vt, arr, &bounds_size, sgen_vtable_get_descriptor (vt));
        /* We don't want to scan the bounds entries at the end of multidimensional arrays */
        char *obj_end = (char*)obj + obj_size - bounds_size;
        size_t card_count;
        size_t extra_idx = 0;
 
        mword desc = (mword)klass->element_class->gc_descr;
        int elem_size = mono_array_element_size (klass);
 
#ifdef SGEN_HAVE_OVERLAPPING_CARDS
        guint8 *overflow_scan_end = NULL;
#endif
 
#ifdef SGEN_OBJECT_LAYOUT_STATISTICS
        if (klass->element_class->valuetype)
            sgen_object_layout_scanned_vtype_array ();
        else
            sgen_object_layout_scanned_ref_array ();
#endif
 
        if (cards)
            card_data = cards;
        else
            card_data = sgen_card_table_get_card_scan_address ((mword)obj);
 
        card_base = card_data;
        card_count = sgen_card_table_number_of_cards_in_range ((mword)obj, obj_size);
        card_data_end = card_data + card_count;
 
 
#ifdef SGEN_HAVE_OVERLAPPING_CARDS
        /*Check for overflow and if so, setup to scan in two steps*/
        if (!cards && card_data_end >= SGEN_SHADOW_CARDTABLE_END) {
            overflow_scan_end = sgen_shadow_cardtable + (card_data_end - SGEN_SHADOW_CARDTABLE_END);
            card_data_end = SGEN_SHADOW_CARDTABLE_END;
        }
 
LOOP_HEAD:
#endif
 
        card_data = sgen_find_next_card (card_data, card_data_end);
        for (; card_data < card_data_end; card_data = sgen_find_next_card (card_data + 1, card_data_end)) {
            size_t index;
            size_t idx = (card_data - card_base) + extra_idx;
            char *start = (char*)(obj_start + idx * CARD_SIZE_IN_BYTES);
            char *card_end = start + CARD_SIZE_IN_BYTES;
            char *first_elem, *elem;
 
            HEAVY_STAT (++los_marked_cards);
 
            if (!cards)
                sgen_card_table_prepare_card_for_scanning (card_data);
 
            card_end = MIN (card_end, obj_end);
 
            if (start <= (char*)arr->vector)
                index = 0;
            else
                index = ARRAY_OBJ_INDEX (start, obj, elem_size);
 
            elem = first_elem = (char*)mono_array_addr_with_size_fast ((MonoArray*)obj, elem_size, index);
            if (klass->element_class->valuetype) {
                ScanVTypeFunc scan_vtype_func = ctx.ops->scan_vtype;
 
                for (; elem < card_end; elem += elem_size)
                    scan_vtype_func (obj, elem, desc, ctx.queue BINARY_PROTOCOL_ARG (elem_size));
            } else {
                ScanPtrFieldFunc scan_ptr_field_func = ctx.ops->scan_ptr_field;
 
                HEAVY_STAT (++los_array_cards);
                for (; elem < card_end; elem += SIZEOF_VOID_P)
                    scan_ptr_field_func (obj, (GCObject**)elem, ctx.queue);
            }
 
            binary_protocol_card_scan (first_elem, elem - first_elem);
        }
 
#ifdef SGEN_HAVE_OVERLAPPING_CARDS
        if (overflow_scan_end) {
            extra_idx = card_data - card_base;
            card_base = card_data = sgen_shadow_cardtable;
            card_data_end = overflow_scan_end;
            overflow_scan_end = NULL;
            goto LOOP_HEAD;
        }
#endif
        return TRUE;
    }
 
    return FALSE;
}
 
/*
 * Array and string allocation
 */
 
void*
mono_gc_alloc_vector (MonoVTable *vtable, size_t size, uintptr_t max_length)
{
    MonoArray *arr;
    TLAB_ACCESS_INIT;
 
    if (!SGEN_CAN_ALIGN_UP (size))
        return NULL;
 
#ifndef DISABLE_CRITICAL_REGION
    ENTER_CRITICAL_REGION;
    arr = (MonoArray*)sgen_try_alloc_obj_nolock (vtable, size);
    if (arr) {
        /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
        arr->max_length = (mono_array_size_t)max_length;
        EXIT_CRITICAL_REGION;
        goto done;
    }
    EXIT_CRITICAL_REGION;
#endif
 
    LOCK_GC;
 
    arr = (MonoArray*)sgen_alloc_obj_nolock (vtable, size);
    if (G_UNLIKELY (!arr)) {
        UNLOCK_GC;
        return NULL;
    }
 
    arr->max_length = (mono_array_size_t)max_length;
 
    UNLOCK_GC;
 
 done:
    if (G_UNLIKELY (mono_profiler_allocations_enabled ()))
        MONO_PROFILER_RAISE (gc_allocation, (&arr->obj));
 
    SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Vector has incorrect size.");
    return arr;
}
 
void*
mono_gc_alloc_array (MonoVTable *vtable, size_t size, uintptr_t max_length, uintptr_t bounds_size)
{
    MonoArray *arr;
    MonoArrayBounds *bounds;
    TLAB_ACCESS_INIT;
 
    if (!SGEN_CAN_ALIGN_UP (size))
        return NULL;
 
#ifndef DISABLE_CRITICAL_REGION
    ENTER_CRITICAL_REGION;
    arr = (MonoArray*)sgen_try_alloc_obj_nolock (vtable, size);
    if (arr) {
        /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
        arr->max_length = (mono_array_size_t)max_length;
 
        bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
        arr->bounds = bounds;
        EXIT_CRITICAL_REGION;
        goto done;
    }
    EXIT_CRITICAL_REGION;
#endif
 
    LOCK_GC;
 
    arr = (MonoArray*)sgen_alloc_obj_nolock (vtable, size);
    if (G_UNLIKELY (!arr)) {
        UNLOCK_GC;
        return NULL;
    }
 
    arr->max_length = (mono_array_size_t)max_length;
 
    bounds = (MonoArrayBounds*)((char*)arr + size - bounds_size);
    arr->bounds = bounds;
 
    UNLOCK_GC;
 
 done:
    if (G_UNLIKELY (mono_profiler_allocations_enabled ()))
        MONO_PROFILER_RAISE (gc_allocation, (&arr->obj));
 
    SGEN_ASSERT (6, SGEN_ALIGN_UP (size) == SGEN_ALIGN_UP (sgen_client_par_object_get_size (vtable, (GCObject*)arr)), "Array has incorrect size.");
    return arr;
}
 
void*
mono_gc_alloc_string (MonoVTable *vtable, size_t size, gint32 len)
{
    MonoString *str;
    TLAB_ACCESS_INIT;
 
    if (!SGEN_CAN_ALIGN_UP (size))
        return NULL;
 
#ifndef DISABLE_CRITICAL_REGION
    ENTER_CRITICAL_REGION;
    str = (MonoString*)sgen_try_alloc_obj_nolock (vtable, size);
    if (str) {
        /*This doesn't require fencing since EXIT_CRITICAL_REGION already does it for us*/
        str->length = len;
        EXIT_CRITICAL_REGION;
        goto done;
    }
    EXIT_CRITICAL_REGION;
#endif
 
    LOCK_GC;
 
    str = (MonoString*)sgen_alloc_obj_nolock (vtable, size);
    if (G_UNLIKELY (!str)) {
        UNLOCK_GC;
        return NULL;
    }
 
    str->length = len;
 
    UNLOCK_GC;
 
 done:
    if (G_UNLIKELY (mono_profiler_allocations_enabled ()))
        MONO_PROFILER_RAISE (gc_allocation, (&str->object));
 
    return str;
}
 
/*
 * Strings
 */
 
void
mono_gc_set_string_length (MonoString *str, gint32 new_length)
{
    mono_unichar2 *new_end = str->chars + new_length;
 
    /* zero the discarded string. This null-delimits the string and allows
     * the space to be reclaimed by SGen. */
 
    if (nursery_canaries_enabled () && sgen_ptr_in_nursery (str)) {
        CHECK_CANARY_FOR_OBJECT ((GCObject*)str, TRUE);
        memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2) + CANARY_SIZE);
        memcpy (new_end + 1 , CANARY_STRING, CANARY_SIZE);
    } else {
        memset (new_end, 0, (str->length - new_length + 1) * sizeof (mono_unichar2));
    }
 
    str->length = new_length;
}
 
/*
 * Profiling
 */
 
#define GC_ROOT_NUM 32
#define SPECIAL_ADDRESS_FIN_QUEUE ((void*)1)
#define SPECIAL_ADDRESS_CRIT_FIN_QUEUE ((void*)2)
 
typedef struct {
    int count;        /* must be the first field */
    void *addresses [GC_ROOT_NUM];
    void *objects [GC_ROOT_NUM];
} GCRootReport;
 
static void
notify_gc_roots (GCRootReport *report)
{
    if (!report->count)
        return;
    MONO_PROFILER_RAISE (gc_roots, (report->count, (const mono_byte *const *)report->addresses, (MonoObject *const *) report->objects));
    report->count = 0;
}
 
static void
report_gc_root (GCRootReport *report, void *address, void *object)
{
    if (report->count == GC_ROOT_NUM)
        notify_gc_roots (report);
    report->addresses [report->count] = address;
    report->objects [report->count] = object;
    report->count++;
}
 
static void
single_arg_report_root (MonoObject **obj, void *gc_data)
{
    GCRootReport *report = gc_data;
    if (*obj)
        report_gc_root (report, obj, *obj);
}
 
static void
two_args_report_root (void *address, MonoObject *obj, void *gc_data)
{
    GCRootReport *report = gc_data;
    if (obj)
        report_gc_root (report, address, obj);
}
 
static void
precisely_report_roots_from (GCRootReport *report, void** start_root, void** end_root, mword desc)
{
    switch (desc & ROOT_DESC_TYPE_MASK) {
    case ROOT_DESC_BITMAP:
        desc >>= ROOT_DESC_TYPE_SHIFT;
        while (desc) {
            if ((desc & 1) && *start_root)
                report_gc_root (report, start_root, *start_root);
            desc >>= 1;
            start_root++;
        }
        return;
    case ROOT_DESC_COMPLEX: {
        gsize *bitmap_data = (gsize *)sgen_get_complex_descriptor_bitmap (desc);
        gsize bwords = (*bitmap_data) - 1;
        void **start_run = start_root;
        bitmap_data++;
        while (bwords-- > 0) {
            gsize bmap = *bitmap_data++;
            void **objptr = start_run;
            while (bmap) {
                if ((bmap & 1) && *objptr)
                    report_gc_root (report, objptr, *objptr);
                bmap >>= 1;
                ++objptr;
            }
            start_run += GC_BITS_PER_WORD;
        }
        break;
    }
    case ROOT_DESC_VECTOR: {
        void **p;
 
        for (p = start_root; p < end_root; p++) {
            if (*p)
                report_gc_root (report, p, *p);
        }
        break;
    }
    case ROOT_DESC_USER: {
        MonoGCRootMarkFunc marker = (MonoGCRootMarkFunc)sgen_get_user_descriptor_func (desc);
 
        if ((void*)marker == (void*)sgen_mark_normal_gc_handles)
            sgen_gc_handles_report_roots (two_args_report_root, report);
        else
            marker ((MonoObject**)start_root, single_arg_report_root, report);
        break;
    }
    case ROOT_DESC_RUN_LEN:
        g_assert_not_reached ();
    default:
        g_assert_not_reached ();
    }
}
 
static void
report_pinning_roots (GCRootReport *report, void **start, void **end)
{
    while (start < end) {
        mword addr = (mword)*start;
        addr &= ~(SGEN_ALLOC_ALIGN - 1);
        if (addr)
            report_gc_root (report, start, (void*)addr);
 
        start++;
    }
}
 
static SgenPointerQueue pinned_objects = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_MOVED_OBJECT);
static mword lower_bound, upper_bound;
 
static GCObject*
find_pinned_obj (char *addr)
{
    size_t idx = sgen_pointer_queue_search (&pinned_objects, addr);
 
    if (idx != pinned_objects.next_slot) {
        if (pinned_objects.data [idx] == addr)
            return pinned_objects.data [idx];
        if (idx == 0)
            return NULL;
    }
 
    GCObject *obj = pinned_objects.data [idx - 1];
    if (addr > (char*)obj && addr < ((char*)obj + sgen_safe_object_get_size (obj)))
        return obj;
    return NULL;
}
 
 
/*
 * We pass @root_report_address so register are properly accounted towards their thread
*/
static void
report_conservative_roots (GCRootReport *report, char *root_report_address, void **start, void **end)
{
    while (start < end) {
        mword addr = (mword)*start;
        addr &= ~(SGEN_ALLOC_ALIGN - 1);
 
        if (addr < lower_bound || addr > upper_bound) {
            ++start;
            continue;
        }
 
        GCObject *obj = find_pinned_obj ((char*)addr);
        if (obj)
            report_gc_root (report, root_report_address, obj);
        start++;
    }
}
 
typedef struct {
    gboolean precise;
    GCRootReport *report;
    SgenThreadInfo *info;
} ReportHandleStackRoot;
 
static void
report_handle_stack_root (gpointer *ptr, gpointer user_data)
{
    ReportHandleStackRoot *ud = user_data;
    GCRootReport *report = ud->report;
    gpointer addr = ud->info->client_info.info.handle_stack;
 
    // Note: We know that *ptr != NULL.
    if (ud->precise)
        report_gc_root (report, addr, *ptr);
    else
        report_conservative_roots (report, addr, ptr, ptr + 1);
}
 
static void
report_handle_stack_roots (GCRootReport *report, SgenThreadInfo *info, gboolean precise)
{
    ReportHandleStackRoot ud = {
        .precise = precise,
        .report = report,
        .info = info,
    };
 
    mono_handle_stack_scan ((HandleStack *) info->client_info.info.handle_stack, report_handle_stack_root, &ud, ud.precise, FALSE);
}
 
static void
report_stack_roots (void)
{
    GCRootReport report = {0};
    FOREACH_THREAD (info) {
        void *aligned_stack_start;
 
        if (info->client_info.skip) {
            continue;
        } else if (info->client_info.gc_disabled) {
            continue;
        } else if (!mono_thread_info_is_live (info)) {
            continue;
        } else if (!info->client_info.stack_start) {
            continue;
        }
 
        g_assert (info->client_info.stack_start);
        g_assert (info->client_info.info.stack_end);
 
        aligned_stack_start = (void*)(mword) ALIGN_TO ((mword)info->client_info.stack_start, SIZEOF_VOID_P);
#ifdef HOST_WIN32
        /* Windows uses a guard page before the committed stack memory pages to detect when the
           stack needs to be grown. If we suspend a thread just after a function prolog has
           decremented the stack pointer to point into the guard page but before the thread has
           been able to read or write to that page, starting the stack scan at aligned_stack_start
           will raise a STATUS_GUARD_PAGE_VIOLATION and the process will crash. This code uses
           VirtualQuery() to determine whether stack_start points into the guard page and then
           updates aligned_stack_start to point at the next non-guard page. */
        MEMORY_BASIC_INFORMATION mem_info;
        SIZE_T result = VirtualQuery (info->client_info.stack_start, &mem_info, sizeof(mem_info));
        g_assert (result != 0);
        if (mem_info.Protect & PAGE_GUARD) {
            aligned_stack_start = ((char*) mem_info.BaseAddress) + mem_info.RegionSize;
        }
#endif
 
        g_assert (info->client_info.suspend_done);
 
        report_conservative_roots (&report, aligned_stack_start, (void **)aligned_stack_start, (void **)info->client_info.info.stack_end);
        report_conservative_roots (&report, aligned_stack_start, (void**)&info->client_info.ctx, (void**)(&info->client_info.ctx + 1));
 
        report_handle_stack_roots (&report, info, FALSE);
        report_handle_stack_roots (&report, info, TRUE);
    } FOREACH_THREAD_END
 
    notify_gc_roots (&report);
}
 
static void
report_pin_queue (void)
{
    lower_bound = SIZE_MAX;
    upper_bound = 0;
 
    //sort the addresses
    sgen_pointer_queue_sort_uniq (&pinned_objects);
 
    for (int i = 0; i < pinned_objects.next_slot; ++i) {
        GCObject *obj = pinned_objects.data [i];
        ssize_t size = sgen_safe_object_get_size (obj);
 
        ssize_t addr = (ssize_t)obj;
        lower_bound = MIN (lower_bound, addr);
        upper_bound = MAX (upper_bound, addr + size);
    }
 
    report_stack_roots ();
    sgen_pointer_queue_clear (&pinned_objects);
}
 
static void
report_finalizer_roots_from_queue (SgenPointerQueue *queue, void* queue_address)
{
    GCRootReport report;
    size_t i;
 
    report.count = 0;
    for (i = 0; i < queue->next_slot; ++i) {
        void *obj = queue->data [i];
        if (!obj)
            continue;
        report_gc_root (&report, queue_address, obj);
    }
    notify_gc_roots (&report);
}
 
static void
report_registered_roots_by_type (int root_type)
{
    GCRootReport report = { 0 };
    void **start_root;
    RootRecord *root;
    report.count = 0;
    SGEN_HASH_TABLE_FOREACH (&roots_hash [root_type], void **, start_root, RootRecord *, root) {
        SGEN_LOG (6, "Profiler root scan %p-%p (desc: %p)", start_root, root->end_root, (void*)root->root_desc);
        if (root_type == ROOT_TYPE_PINNED)
            report_pinning_roots (&report, start_root, (void**)root->end_root);
        else
            precisely_report_roots_from (&report, start_root, (void**)root->end_root, root->root_desc);
    } SGEN_HASH_TABLE_FOREACH_END;
    notify_gc_roots (&report);
}
 
static void
report_registered_roots (void)
{
    for (int i = 0; i < ROOT_TYPE_NUM; ++i)
        report_registered_roots_by_type (i);
}
 
static void
sgen_report_all_roots (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
 
    report_registered_roots ();
    report_pin_queue ();
    report_finalizer_roots_from_queue (fin_ready_queue, SPECIAL_ADDRESS_FIN_QUEUE);
    report_finalizer_roots_from_queue (critical_fin_queue, SPECIAL_ADDRESS_CRIT_FIN_QUEUE);
}
 
void
sgen_client_pinning_start (void)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
 
    sgen_pointer_queue_clear (&pinned_objects);
}
 
void
sgen_client_pinning_end (void)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
}
 
void
sgen_client_nursery_objects_pinned (void **definitely_pinned, int count)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
 
    for (int i = 0; i < count; ++i)
        sgen_pointer_queue_add (&pinned_objects, definitely_pinned [i]);
}
 
void
sgen_client_pinned_los_object (GCObject *obj)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
 
    sgen_pointer_queue_add (&pinned_objects, obj);
}
 
void
sgen_client_pinned_cemented_object (GCObject *obj)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
 
    // TODO: How do we report this in a way that makes sense?
}
 
void
sgen_client_pinned_major_heap_object (GCObject *obj)
{
    if (!MONO_PROFILER_ENABLED (gc_roots))
        return;
 
    sgen_pointer_queue_add (&pinned_objects, obj);
}
 
void
sgen_client_collecting_minor_report_roots (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
{
    sgen_report_all_roots (fin_ready_queue, critical_fin_queue);
}
 
void
sgen_client_collecting_major_report_roots (SgenPointerQueue *fin_ready_queue, SgenPointerQueue *critical_fin_queue)
{
    sgen_report_all_roots (fin_ready_queue, critical_fin_queue);
}
 
#define MOVED_OBJECTS_NUM 64
static void *moved_objects [MOVED_OBJECTS_NUM];
static int moved_objects_idx = 0;
 
static SgenPointerQueue moved_objects_queue = SGEN_POINTER_QUEUE_INIT (INTERNAL_MEM_MOVED_OBJECT);
 
void
mono_sgen_register_moved_object (void *obj, void *destination)
{
    /*
     * This function can be called from SGen's worker threads. We want to try
     * and avoid exposing those threads to the profiler API, so queue up move
     * events and send them later when the main GC thread calls
     * mono_sgen_gc_event_moves ().
     *
     * TODO: Once SGen has multiple worker threads, we need to switch to a
     * lock-free data structure for the queue as multiple threads will be
     * adding to it at the same time.
     */
    if (sgen_workers_is_worker_thread (mono_native_thread_id_get ())) {
        sgen_pointer_queue_add (&moved_objects_queue, obj);
        sgen_pointer_queue_add (&moved_objects_queue, destination);
    } else {
        if (moved_objects_idx == MOVED_OBJECTS_NUM) {
            MONO_PROFILER_RAISE (gc_moves, ((MonoObject **) moved_objects, moved_objects_idx));
            moved_objects_idx = 0;
        }
 
        moved_objects [moved_objects_idx++] = obj;
        moved_objects [moved_objects_idx++] = destination;
    }
}
 
void
mono_sgen_gc_event_moves (void)
{
    while (!sgen_pointer_queue_is_empty (&moved_objects_queue)) {
        void *dst = sgen_pointer_queue_pop (&moved_objects_queue);
        void *src = sgen_pointer_queue_pop (&moved_objects_queue);
 
        mono_sgen_register_moved_object (src, dst);
    }
 
    if (moved_objects_idx) {
        MONO_PROFILER_RAISE (gc_moves, ((MonoObject **) moved_objects, moved_objects_idx));
        moved_objects_idx = 0;
    }
}
 
/*
 * Heap walking
 */
 
#define REFS_SIZE 128
typedef struct {
    void *data;
    MonoGCReferences callback;
    int flags;
    int count;
    int called;
    MonoObject *refs [REFS_SIZE];
    uintptr_t offsets [REFS_SIZE];
} HeapWalkInfo;
 
#undef HANDLE_PTR
#define HANDLE_PTR(ptr,obj)    do {    \
        if (*(ptr)) {    \
            if (hwi->count == REFS_SIZE) {    \
                hwi->callback ((MonoObject*)start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);    \
                hwi->count = 0;    \
                hwi->called = 1;    \
            }    \
            hwi->offsets [hwi->count] = (char*)(ptr)-(char*)start;    \
            hwi->refs [hwi->count++] = *(ptr);    \
        }    \
    } while (0)
 
static void
collect_references (HeapWalkInfo *hwi, GCObject *obj, size_t size)
{
    char *start = (char*)obj;
    mword desc = sgen_obj_get_descriptor (obj);
 
#include "sgen/sgen-scan-object.h"
}
 
static void
walk_references (GCObject *start, size_t size, void *data)
{
    HeapWalkInfo *hwi = (HeapWalkInfo *)data;
    hwi->called = 0;
    hwi->count = 0;
    collect_references (hwi, start, size);
    if (hwi->count || !hwi->called)
        hwi->callback (start, mono_object_class (start), hwi->called? 0: size, hwi->count, hwi->refs, hwi->offsets, hwi->data);
}
 
/**
 * mono_gc_walk_heap:
 * \param flags flags for future use
 * \param callback a function pointer called for each object in the heap
 * \param data a user data pointer that is passed to callback
 * This function can be used to iterate over all the live objects in the heap;
 * for each object, \p callback is invoked, providing info about the object's
 * location in memory, its class, its size and the objects it references.
 * For each referenced object its offset from the object address is
 * reported in the offsets array.
 * The object references may be buffered, so the callback may be invoked
 * multiple times for the same object: in all but the first call, the size
 * argument will be zero.
 * Note that this function can be only called in the \c MONO_GC_EVENT_PRE_START_WORLD
 * profiler event handler.
 * \returns a non-zero value if the GC doesn't support heap walking
 */
int
mono_gc_walk_heap (int flags, MonoGCReferences callback, void *data)
{
    HeapWalkInfo hwi;
 
    hwi.flags = flags;
    hwi.callback = callback;
    hwi.data = data;
 
    sgen_clear_nursery_fragments ();
    sgen_scan_area_with_callback (nursery_section->data, nursery_section->end_data, walk_references, &hwi, FALSE, TRUE);
 
    major_collector.iterate_objects (ITERATE_OBJECTS_SWEEP_ALL, walk_references, &hwi);
    sgen_los_iterate_objects (walk_references, &hwi);
 
    return 0;
}
 
/*
 * Threads
 */
 
void
mono_gc_set_gc_callbacks (MonoGCCallbacks *callbacks)
{
    gc_callbacks = *callbacks;
}
 
MonoGCCallbacks *
mono_gc_get_gc_callbacks ()
{
    return &gc_callbacks;
}
 
gpointer
mono_gc_thread_attach (SgenThreadInfo *info)
{
    return sgen_thread_attach (info);
}
 
void
sgen_client_thread_attach (SgenThreadInfo* info)
{
    mono_tls_set_sgen_thread_info (info);
 
    info->client_info.skip = 0;
 
    info->client_info.stack_start = NULL;
 
#ifdef SGEN_POSIX_STW
    info->client_info.stop_count = -1;
    info->client_info.signal = 0;
#endif
 
    memset (&info->client_info.ctx, 0, sizeof (MonoContext));
 
    if (mono_gc_get_gc_callbacks ()->thread_attach_func)
        info->client_info.runtime_data = mono_gc_get_gc_callbacks ()->thread_attach_func ();
 
    binary_protocol_thread_register ((gpointer)mono_thread_info_get_tid (info));
 
    SGEN_LOG (3, "registered thread %p (%p) stack end %p", info, (gpointer)mono_thread_info_get_tid (info), info->client_info.info.stack_end);
 
    info->client_info.info.handle_stack = mono_handle_stack_alloc ();
}
 
void
mono_gc_thread_detach (SgenThreadInfo *info)
{
}
 
void
mono_gc_thread_detach_with_lock (SgenThreadInfo *info)
{
    return sgen_thread_detach_with_lock (info);
}
 
void
sgen_client_thread_detach_with_lock (SgenThreadInfo *p)
{
    MonoNativeThreadId tid;
 
    mono_tls_set_sgen_thread_info (NULL);
 
    tid = mono_thread_info_get_tid (p);
 
    mono_threads_add_joinable_runtime_thread (&p->client_info.info);
 
    if (mono_gc_get_gc_callbacks ()->thread_detach_func) {
        mono_gc_get_gc_callbacks ()->thread_detach_func (p->client_info.runtime_data);
        p->client_info.runtime_data = NULL;
    }
 
    binary_protocol_thread_unregister ((gpointer)tid);
    SGEN_LOG (3, "unregister thread %p (%p)", p, (gpointer)tid);
 
    HandleStack *handles = (HandleStack*) p->client_info.info.handle_stack;
    p->client_info.info.handle_stack = NULL;
    mono_handle_stack_free (handles);
}
 
void
mono_gc_set_skip_thread (gboolean skip)
{
    SgenThreadInfo *info = mono_thread_info_current ();
 
    LOCK_GC;
    info->client_info.gc_disabled = skip;
    UNLOCK_GC;
 
    if (skip) {
        /* If we skip scanning a thread with a non-empty handle stack, we may move an
         * object but fail to update the reference in the handle.
         */
        HandleStack *stack = info->client_info.info.handle_stack;
        g_assert (stack == NULL || mono_handle_stack_is_empty (stack));
    }
}
 
gboolean
mono_gc_thread_in_critical_region (SgenThreadInfo *info)
{
    return info->client_info.in_critical_region;
}
 
/**
 * mono_gc_is_gc_thread:
 */
gboolean
mono_gc_is_gc_thread (void)
{
    gboolean result;
    LOCK_GC;
    result = mono_thread_info_current () != NULL;
    UNLOCK_GC;
    return result;
}
 
void
sgen_client_thread_register_worker (void)
{
    mono_thread_info_register_small_id ();
    mono_native_thread_set_name (mono_native_thread_id_get (), "SGen worker");
}
 
/* Variables holding start/end nursery so it won't have to be passed at every call */
static void *scan_area_arg_start, *scan_area_arg_end;
 
void
mono_gc_conservatively_scan_area (void *start, void *end)
{
    sgen_conservatively_pin_objects_from ((void **)start, (void **)end, scan_area_arg_start, scan_area_arg_end, PIN_TYPE_STACK);
}
 
void*
mono_gc_scan_object (void *obj, void *gc_data)
{
    ScanCopyContext *ctx = (ScanCopyContext *)gc_data;
    ctx->ops->copy_or_mark_object ((GCObject**)&obj, ctx->queue);
    return obj;
}
 
typedef struct {
    void **start_nursery;
    void **end_nursery;
} PinHandleStackInteriorPtrData;
 
/* Called when we're scanning the handle stack imprecisely and we encounter a pointer into the
   middle of an object.
 */
static void
pin_handle_stack_interior_ptrs (void **ptr_slot, void *user_data)
{
    PinHandleStackInteriorPtrData *ud = (PinHandleStackInteriorPtrData *)user_data;
    sgen_conservatively_pin_objects_from (ptr_slot, ptr_slot+1, ud->start_nursery, ud->end_nursery, PIN_TYPE_STACK);
}
 
 
/*
 * Mark from thread stacks and registers.
 */
void
sgen_client_scan_thread_data (void *start_nursery, void *end_nursery, gboolean precise, ScanCopyContext ctx)
{
    scan_area_arg_start = start_nursery;
    scan_area_arg_end = end_nursery;
#ifdef HOST_WASM
    //Under WASM we don't scan thread stacks and we can't trust the values we find there either.
    return;
#endif
 
    FOREACH_THREAD (info) {
        int skip_reason = 0;
        void *aligned_stack_start;
 
        if (info->client_info.skip) {
            SGEN_LOG (3, "Skipping dead thread %p, range: %p-%p, size: %zd", info, info->client_info.stack_start, info->client_info.info.stack_end, (char*)info->client_info.info.stack_end - (char*)info->client_info.stack_start);
            skip_reason = 1;
        } else if (info->client_info.gc_disabled) {
            SGEN_LOG (3, "GC disabled for thread %p, range: %p-%p, size: %zd", info, info->client_info.stack_start, info->client_info.info.stack_end, (char*)info->client_info.info.stack_end - (char*)info->client_info.stack_start);
            skip_reason = 2;
        } else if (!mono_thread_info_is_live (info)) {
            SGEN_LOG (3, "Skipping non-running thread %p, range: %p-%p, size: %zd (state %x)", info, info->client_info.stack_start, info->client_info.info.stack_end, (char*)info->client_info.info.stack_end - (char*)info->client_info.stack_start, info->client_info.info.thread_state);
            skip_reason = 3;
        } else if (!info->client_info.stack_start) {
            SGEN_LOG (3, "Skipping starting or detaching thread %p", info);
            skip_reason = 4;
        }
 
        binary_protocol_scan_stack ((gpointer)mono_thread_info_get_tid (info), info->client_info.stack_start, info->client_info.info.stack_end, skip_reason);
 
        if (skip_reason) {
            if (precise) {
                /* If we skip a thread with a non-empty handle stack and then it
                 * resumes running we may potentially move an object but fail to
                 * update the reference in the handle.
                 */
                HandleStack *stack = info->client_info.info.handle_stack;
                g_assert (stack == NULL || mono_handle_stack_is_empty (stack));
            }
            continue;
        }
 
        g_assert (info->client_info.stack_start);
        g_assert (info->client_info.info.stack_end);
 
        aligned_stack_start = (void*)(mword) ALIGN_TO ((mword)info->client_info.stack_start, SIZEOF_VOID_P);
#ifdef HOST_WIN32
        /* Windows uses a guard page before the committed stack memory pages to detect when the
           stack needs to be grown. If we suspend a thread just after a function prolog has
           decremented the stack pointer to point into the guard page but before the thread has
           been able to read or write to that page, starting the stack scan at aligned_stack_start
           will raise a STATUS_GUARD_PAGE_VIOLATION and the process will crash. This code uses
           VirtualQuery() to determine whether stack_start points into the guard page and then
           updates aligned_stack_start to point at the next non-guard page. */
        MEMORY_BASIC_INFORMATION mem_info;
        SIZE_T result = VirtualQuery(info->client_info.stack_start, &mem_info, sizeof(mem_info));
        g_assert (result != 0);
        if (mem_info.Protect & PAGE_GUARD) {
            aligned_stack_start = ((char*) mem_info.BaseAddress) + mem_info.RegionSize;
        }
#endif
 
        g_assert (info->client_info.suspend_done);
        SGEN_LOG (3, "Scanning thread %p, range: %p-%p, size: %zd, pinned=%zd", info, info->client_info.stack_start, info->client_info.info.stack_end, (char*)info->client_info.info.stack_end - (char*)info->client_info.stack_start, sgen_get_pinned_count ());
        if (mono_gc_get_gc_callbacks ()->thread_mark_func && !conservative_stack_mark) {
            mono_gc_get_gc_callbacks ()->thread_mark_func (info->client_info.runtime_data, (guint8 *)aligned_stack_start, (guint8 *)info->client_info.info.stack_end, precise, &ctx);
        } else if (!precise) {
            if (!conservative_stack_mark) {
                fprintf (stderr, "Precise stack mark not supported - disabling.\n");
                conservative_stack_mark = TRUE;
            }
            //FIXME we should eventually use the new stack_mark from coop
            sgen_conservatively_pin_objects_from ((void **)aligned_stack_start, (void **)info->client_info.info.stack_end, start_nursery, end_nursery, PIN_TYPE_STACK);
        }
 
        if (!precise) {
            sgen_conservatively_pin_objects_from ((void**)&info->client_info.ctx, (void**)(&info->client_info.ctx + 1),
                start_nursery, end_nursery, PIN_TYPE_STACK);
 
            {
                // This is used on Coop GC for platforms where we cannot get the data for individual registers.
                // We force a spill of all registers into the stack and pass a chunk of data into sgen.
                //FIXME under coop, for now, what we need to ensure is that we scan any extra memory from info->client_info.info.stack_end to stack_mark
                MonoThreadUnwindState *state = &info->client_info.info.thread_saved_state [SELF_SUSPEND_STATE_INDEX];
                if (state && state->gc_stackdata) {
                    sgen_conservatively_pin_objects_from ((void **)state->gc_stackdata, (void**)((char*)state->gc_stackdata + state->gc_stackdata_size),
                        start_nursery, end_nursery, PIN_TYPE_STACK);
                }
            }
        }
        if (info->client_info.info.handle_stack) {
            /*
              Make two passes over the handle stack.  On the imprecise pass, pin all
              objects where the handle points into the interior of the object. On the
              precise pass, copy or mark all the objects that have handles to the
              beginning of the object.
            */
            if (precise)
                mono_handle_stack_scan ((HandleStack*)info->client_info.info.handle_stack, (GcScanFunc)ctx.ops->copy_or_mark_object, ctx.queue, precise, TRUE);
            else {
                PinHandleStackInteriorPtrData ud = { .start_nursery = start_nursery,
                                     .end_nursery = end_nursery,
                };
                mono_handle_stack_scan ((HandleStack*)info->client_info.info.handle_stack, pin_handle_stack_interior_ptrs, &ud, precise, FALSE);
            }
        }
    } FOREACH_THREAD_END
}
 
/*
 * mono_gc_set_stack_end:
 *
 *   Set the end of the current threads stack to STACK_END. The stack space between 
 * STACK_END and the real end of the threads stack will not be scanned during collections.
 */
void
mono_gc_set_stack_end (void *stack_end)
{
    SgenThreadInfo *info;
 
    LOCK_GC;
    info = mono_thread_info_current ();
    if (info) {
        SGEN_ASSERT (0, stack_end < info->client_info.info.stack_end, "Can only lower stack end");
        info->client_info.info.stack_end = stack_end;
    }
    UNLOCK_GC;
}
 
/*
 * Roots
 */
 
int
mono_gc_register_root (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg)
{
    return sgen_register_root (start, size, descr, descr ? ROOT_TYPE_NORMAL : ROOT_TYPE_PINNED, source, key, msg);
}
 
int
mono_gc_register_root_wbarrier (char *start, size_t size, MonoGCDescriptor descr, MonoGCRootSource source, void *key, const char *msg)
{
    return sgen_register_root (start, size, descr, ROOT_TYPE_WBARRIER, source, key, msg);
}
 
void
mono_gc_deregister_root (char* addr)
{
    sgen_deregister_root (addr);
}
 
/*
 * PThreads
 */
 
#ifndef HOST_WIN32
int
mono_gc_pthread_create (pthread_t *new_thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
{
    int res;
 
    mono_threads_join_lock ();
    res = pthread_create (new_thread, attr, start_routine, arg);
    mono_threads_join_unlock ();
 
    return res;
}
#endif
 
/*
 * Miscellaneous
 */
 
void
sgen_client_total_allocated_heap_changed (size_t allocated_heap)
{
    MONO_PROFILER_RAISE (gc_resize, (allocated_heap));
 
    mono_runtime_resource_check_limit (MONO_RESOURCE_GC_HEAP, allocated_heap);
}
 
gboolean
mono_gc_user_markers_supported (void)
{
    return TRUE;
}
 
gboolean
mono_object_is_alive (MonoObject* o)
{
    return TRUE;
}
 
int
mono_gc_get_generation (MonoObject *obj)
{
    if (sgen_ptr_in_nursery (obj))
        return 0;
    return 1;
}
 
const char *
mono_gc_get_gc_name (void)
{
    return "sgen";
}
 
char*
mono_gc_get_description (void)
{
#ifdef HAVE_CONC_GC_AS_DEFAULT
    return g_strdup ("sgen (concurrent by default)");
#else
    return g_strdup ("sgen");
#endif
}
 
void
mono_gc_set_desktop_mode (void)
{
}
 
gboolean
mono_gc_is_moving (void)
{
    return TRUE;
}
 
gboolean
mono_gc_is_disabled (void)
{
    return FALSE;
}
 
#ifdef HOST_WIN32
BOOL APIENTRY mono_gc_dllmain (HMODULE module_handle, DWORD reason, LPVOID reserved)
{
    return TRUE;
}
#endif
 
int
mono_gc_max_generation (void)
{
    return 1;
}
 
gboolean
mono_gc_precise_stack_mark_enabled (void)
{
    return !conservative_stack_mark;
}
 
void
mono_gc_collect (int generation)
{
    sgen_gc_collect (generation);
}
 
int
mono_gc_collection_count (int generation)
{
    return sgen_gc_collection_count (generation);
}
 
int64_t
mono_gc_get_used_size (void)
{
    return (int64_t)sgen_gc_get_used_size ();
}
 
int64_t
mono_gc_get_heap_size (void)
{
    return (int64_t)sgen_gc_get_total_heap_allocation ();
}
 
int64_t
mono_gc_get_max_time_slice_ns()
{
    return 0;
}
 
MonoBoolean 
mono_gc_is_incremental()
{
    return FALSE;
}
 
void
mono_gc_set_incremental(MonoBoolean value)
{
}
 
void
mono_gc_set_max_time_slice_ns(int64_t maxTimeSlice)
{
}
 
MonoGCDescriptor
mono_gc_make_root_descr_user (MonoGCRootMarkFunc marker)
{
    return sgen_make_user_root_descriptor (marker);
}
 
MonoGCDescriptor
mono_gc_make_descr_for_string (gsize *bitmap, int numbits)
{
    return SGEN_DESC_STRING;
}
 
void
mono_gc_register_obj_with_weak_fields (void *obj)
{
    return sgen_register_obj_with_weak_fields (obj);
}
 
void*
mono_gc_get_nursery (int *shift_bits, size_t *size)
{
    *size = sgen_nursery_size;
    *shift_bits = sgen_nursery_bits;
    return sgen_get_nursery_start ();
}
 
int
mono_gc_get_los_limit (void)
{
    return SGEN_MAX_SMALL_OBJ_SIZE;
}
 
gpointer
sgen_client_default_metadata (void)
{
    return mono_domain_get ();
}
 
gpointer
sgen_client_metadata_for_object (GCObject *obj)
{
    return mono_object_domain (obj);
}
 
/**
 * mono_gchandle_new:
 * \param obj managed object to get a handle for
 * \param pinned whether the object should be pinned
 * This returns a handle that wraps the object, this is used to keep a
 * reference to a managed object from the unmanaged world and preventing the
 * object from being disposed.
 * 
 * If \p pinned is false the address of the object can not be obtained, if it is
 * true the address of the object can be obtained.  This will also pin the
 * object so it will not be possible by a moving garbage collector to move the
 * object. 
 * 
 * \returns a handle that can be used to access the object from unmanaged code.
 */
guint32
mono_gchandle_new (MonoObject *obj, gboolean pinned)
{
    return sgen_gchandle_new (obj, pinned);
}
 
/**
 * mono_gchandle_new_weakref:
 * \param obj managed object to get a handle for
 * \param track_resurrection Determines how long to track the object, if this is set to TRUE, the object is tracked after finalization, if FALSE, the object is only tracked up until the point of finalization.
 *
 * This returns a weak handle that wraps the object, this is used to
 * keep a reference to a managed object from the unmanaged world.
 * Unlike the \c mono_gchandle_new the object can be reclaimed by the
 * garbage collector.  In this case the value of the GCHandle will be
 * set to zero.
 * 
 * If \p track_resurrection is TRUE the object will be tracked through
 * finalization and if the object is resurrected during the execution
 * of the finalizer, then the returned weakref will continue to hold
 * a reference to the object.   If \p track_resurrection is FALSE, then
 * the weak reference's target will become NULL as soon as the object
 * is passed on to the finalizer.
 * 
 * \returns a handle that can be used to access the object from
 * unmanaged code.
 */
guint32
mono_gchandle_new_weakref (GCObject *obj, gboolean track_resurrection)
{
    return sgen_gchandle_new_weakref (obj, track_resurrection);
}
 
/**
 * mono_gchandle_is_in_domain:
 * \param gchandle a GCHandle's handle.
 * \param domain An application domain.
 * \returns TRUE if the object wrapped by the \p gchandle belongs to the specific \p domain.
 */
gboolean
mono_gchandle_is_in_domain (guint32 gchandle, MonoDomain *domain)
{
    MonoDomain *gchandle_domain = (MonoDomain *)sgen_gchandle_get_metadata (gchandle);
    return domain->domain_id == gchandle_domain->domain_id;
}
 
/**
 * mono_gchandle_free:
 * \param gchandle a GCHandle's handle.
 *
 * Frees the \p gchandle handle.  If there are no outstanding
 * references, the garbage collector can reclaim the memory of the
 * object wrapped. 
 */
void
mono_gchandle_free (guint32 gchandle)
{
    sgen_gchandle_free (gchandle);
}
 
/**
 * mono_gchandle_free_domain:
 * \param unloading domain that is unloading
 *
 * Function used internally to cleanup any GC handle for objects belonging
 * to the specified domain during appdomain unload.
 */
void
mono_gchandle_free_domain (MonoDomain *unloading)
{
}
 
/**
 * mono_gchandle_get_target:
 * \param gchandle a GCHandle's handle.
 *
 * The handle was previously created by calling \c mono_gchandle_new or
 * \c mono_gchandle_new_weakref. 
 *
 * \returns a pointer to the \c MonoObject* represented by the handle or
 * NULL for a collected object if using a weakref handle.
 */
MonoObject*
mono_gchandle_get_target (guint32 gchandle)
{
    return sgen_gchandle_get_target (gchandle);
}
 
static gpointer
null_link_if_in_domain (gpointer hidden, GCHandleType handle_type, int max_generation, gpointer user)
{
    MonoDomain *unloading_domain = (MonoDomain *)user;
    MonoDomain *obj_domain;
    gboolean is_weak = MONO_GC_HANDLE_TYPE_IS_WEAK (handle_type);
    if (MONO_GC_HANDLE_IS_OBJECT_POINTER (hidden)) {
        MonoObject *obj = (MonoObject *)MONO_GC_REVEAL_POINTER (hidden, is_weak);
        obj_domain = mono_object_domain (obj);
    } else {
        obj_domain = (MonoDomain *)MONO_GC_REVEAL_POINTER (hidden, is_weak);
    }
    if (unloading_domain->domain_id == obj_domain->domain_id)
        return NULL;
    return hidden;
}
 
void
sgen_null_links_for_domain (MonoDomain *domain)
{
    guint type;
    for (type = HANDLE_TYPE_MIN; type < HANDLE_TYPE_MAX; ++type)
        sgen_gchandle_iterate ((GCHandleType)type, GENERATION_OLD, null_link_if_in_domain, domain);
}
 
void
mono_gchandle_set_target (guint32 gchandle, MonoObject *obj)
{
    sgen_gchandle_set_target (gchandle, obj);
}
 
void
sgen_client_gchandle_created (int handle_type, GCObject *obj, guint32 handle)
{
#ifndef DISABLE_PERFCOUNTERS
    mono_atomic_inc_i32 (&mono_perfcounters->gc_num_handles);
#endif
 
    MONO_PROFILER_RAISE (gc_handle_created, (handle, handle_type, obj));
}
 
void
sgen_client_gchandle_destroyed (int handle_type, guint32 handle)
{
#ifndef DISABLE_PERFCOUNTERS
    mono_atomic_dec_i32 (&mono_perfcounters->gc_num_handles);
#endif
 
    MONO_PROFILER_RAISE (gc_handle_deleted, (handle, handle_type));
}
 
void
sgen_client_ensure_weak_gchandles_accessible (void)
{
    /*
     * During the second bridge processing step the world is
     * running again.  That step processes all weak links once
     * more to null those that refer to dead objects.  Before that
     * is completed, those links must not be followed, so we
     * conservatively wait for bridge processing when any weak
     * link is dereferenced.
     */
    /* FIXME: A GC can occur after this check fails, in which case we
     * should wait for bridge processing but would fail to do so.
     */
    if (G_UNLIKELY (bridge_processing_in_progress))
        mono_gc_wait_for_bridge_processing ();
}
 
void*
mono_gc_invoke_with_gc_lock (MonoGCLockedCallbackFunc func, void *data)
{
    void *result;
    LOCK_INTERRUPTION;
    result = func (data);
    UNLOCK_INTERRUPTION;
    return result;
}
 
void
mono_gc_register_altstack (gpointer stack, gint32 stack_size, gpointer altstack, gint32 altstack_size)
{
    // FIXME:
}
 
guint8*
mono_gc_get_card_table (int *shift_bits, gpointer *mask)
{
    return sgen_get_card_table_configuration (shift_bits, mask);
}
 
gboolean
mono_gc_card_table_nursery_check (void)
{
    return !sgen_get_major_collector ()->is_concurrent;
}
 
/* Negative value to remove */
void
mono_gc_add_memory_pressure (gint64 value)
{
    /* FIXME: Implement at some point? */
}
 
/*
 * Logging
 */
 
void
sgen_client_degraded_allocation (void)
{
    static gint32 last_major_gc_warned = -1;
    static gint32 num_degraded = 0;
 
    gint32 major_gc_count = mono_atomic_load_i32 (&gc_stats.major_gc_count);
    if (mono_atomic_load_i32 (&last_major_gc_warned) < major_gc_count) {
        gint32 num = mono_atomic_inc_i32 (&num_degraded);
        if (num == 1 || num == 3)
            mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Degraded allocation.  Consider increasing nursery-size if the warning persists.");
        else if (num == 10)
            mono_trace (G_LOG_LEVEL_INFO, MONO_TRACE_GC, "Warning: Repeated degraded allocation.  Consider increasing nursery-size.");
        mono_atomic_store_i32 (&last_major_gc_warned, major_gc_count);
    }
}
 
/*
 * Debugging
 */
 
const char*
sgen_client_description_for_internal_mem_type (int type)
{
    switch (type) {
    case INTERNAL_MEM_EPHEMERON_LINK: return "ephemeron-link";
    case INTERNAL_MEM_MOVED_OBJECT: return "moved-object";
    default:
        return NULL;
    }
}
 
void
sgen_client_pre_collection_checks (void)
{
    if (sgen_mono_xdomain_checks) {
        sgen_clear_nursery_fragments ();
        sgen_check_for_xdomain_refs ();
    }
}
 
gboolean
sgen_client_vtable_is_inited (MonoVTable *vt)
{
    return vt->klass->inited;
}
 
const char*
sgen_client_vtable_get_namespace (MonoVTable *vt)
{
    return vt->klass->name_space;
}
 
const char*
sgen_client_vtable_get_name (MonoVTable *vt)
{
    return vt->klass->name;
}
 
/*
 * Initialization
 */
 
void
sgen_client_init (void)
{
    mono_thread_callbacks_init ();
    mono_thread_info_init (sizeof (SgenThreadInfo));
 
    ///* Keep this the default for now */
    /* Precise marking is broken on all supported targets. Disable until fixed. */
    conservative_stack_mark = TRUE;
 
    sgen_register_fixed_internal_mem_type (INTERNAL_MEM_EPHEMERON_LINK, sizeof (EphemeronLinkNode));
 
    mono_sgen_init_stw ();
 
    mono_tls_init_gc_keys ();
 
    mono_thread_info_attach ();
}
 
gboolean
sgen_client_handle_gc_param (const char *opt)
{
    if (g_str_has_prefix (opt, "stack-mark=")) {
        opt = strchr (opt, '=') + 1;
        if (!strcmp (opt, "precise")) {
            conservative_stack_mark = FALSE;
        } else if (!strcmp (opt, "conservative")) {
            conservative_stack_mark = TRUE;
        } else {
            sgen_env_var_error (MONO_GC_PARAMS_NAME, conservative_stack_mark ? "Using `conservative`." : "Using `precise`.",
                    "Invalid value `%s` for `stack-mark` option, possible values are: `precise`, `conservative`.", opt);
        }
    } else if (g_str_has_prefix (opt, "bridge-implementation=")) {
        opt = strchr (opt, '=') + 1;
        sgen_set_bridge_implementation (opt);
    } else if (g_str_has_prefix (opt, "toggleref-test")) {
        /* FIXME: This should probably in MONO_GC_DEBUG */
        sgen_register_test_toggleref_callback ();
    } else if (!sgen_bridge_handle_gc_param (opt)) {
        return FALSE;
    }
    return TRUE;
}
 
void
sgen_client_print_gc_params_usage (void)
{
    fprintf (stderr, "  stack-mark=MARK-METHOD (where MARK-METHOD is 'precise' or 'conservative')\n");
}
 
gboolean
sgen_client_handle_gc_debug (const char *opt)
{
    if (!strcmp (opt, "xdomain-checks")) {
        sgen_mono_xdomain_checks = TRUE;
    } else if (!strcmp (opt, "do-not-finalize")) {
        mono_do_not_finalize = TRUE;
    } else if (g_str_has_prefix (opt, "do-not-finalize=")) {
        opt = strchr (opt, '=') + 1;
        mono_do_not_finalize = TRUE;
        mono_do_not_finalize_class_names = g_strsplit (opt, ",", 0);
    } else if (!strcmp (opt, "log-finalizers")) {
        log_finalizers = TRUE;
    } else if (!strcmp (opt, "no-managed-allocator")) {
        sgen_set_use_managed_allocator (FALSE);
    } else if (!sgen_bridge_handle_gc_debug (opt)) {
        return FALSE;
    }
    return TRUE;
}
 
void
sgen_client_print_gc_debug_usage (void)
{
    fprintf (stderr, "  xdomain-checks\n");
    fprintf (stderr, "  do-not-finalize\n");
    fprintf (stderr, "  log-finalizers\n");
    fprintf (stderr, "  no-managed-allocator\n");
    sgen_bridge_print_gc_debug_usage ();
}
 
 
gpointer
sgen_client_get_provenance (void)
{
#ifdef SGEN_OBJECT_PROVENANCE
    MonoGCCallbacks *cb = mono_gc_get_gc_callbacks ();
    gpointer (*get_provenance_func) (void);
    if (!cb)
        return NULL;
    get_provenance_func = cb->get_provenance_func;
    if (get_provenance_func)
        return get_provenance_func ();
    return NULL;
#else
    return NULL;
#endif
}
 
void
sgen_client_describe_invalid_pointer (GCObject *ptr)
{
    sgen_bridge_describe_pointer (ptr);
}
 
static gboolean gc_inited;
 
/**
 * mono_gc_base_init:
 */
void
mono_gc_base_init (void)
{
    if (gc_inited)
        return;
 
    mono_counters_init ();
 
#ifndef HOST_WIN32
    mono_w32handle_init ();
#endif
 
#ifdef HEAVY_STATISTICS
    mono_counters_register ("los marked cards", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_marked_cards);
    mono_counters_register ("los array cards scanned ", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_cards);
    mono_counters_register ("los array remsets", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &los_array_remsets);
 
    mono_counters_register ("WBarrier set arrayref", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_set_arrayref);
    mono_counters_register ("WBarrier value copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_value_copy);
    mono_counters_register ("WBarrier object copy", MONO_COUNTER_GC | MONO_COUNTER_ULONG, &stat_wbarrier_object_copy);
#endif
 
    sgen_gc_init ();
 
    gc_inited = TRUE;
}
 
void
mono_gc_base_cleanup (void)
{
    sgen_thread_pool_shutdown ();
 
    // We should have consumed any outstanding moves.
    g_assert (sgen_pointer_queue_is_empty (&moved_objects_queue));
}
 
gboolean
mono_gc_is_null (void)
{
    return FALSE;
}
 
gsize *
sgen_client_get_weak_bitmap (MonoVTable *vt, int *nbits)
{
    MonoClass *klass = vt->klass;
 
    return mono_class_get_weak_bitmap (klass, nbits);
}
 
void
sgen_client_binary_protocol_collection_begin (int minor_gc_count, int generation)
{
    static gboolean pseudo_roots_registered;
 
    MONO_GC_BEGIN (generation);
 
    MONO_PROFILER_RAISE (gc_event, (MONO_GC_EVENT_START, generation));
 
    if (!pseudo_roots_registered) {
        pseudo_roots_registered = TRUE;
        MONO_PROFILER_RAISE (gc_root_register, (SPECIAL_ADDRESS_FIN_QUEUE, 1, MONO_ROOT_SOURCE_FINALIZER_QUEUE, NULL, "Finalizer Queue"));
        MONO_PROFILER_RAISE (gc_root_register, (SPECIAL_ADDRESS_CRIT_FIN_QUEUE, 1, MONO_ROOT_SOURCE_FINALIZER_QUEUE, NULL, "Finalizer Queue (Critical)"));
    }
 
#ifndef DISABLE_PERFCOUNTERS
    if (generation == GENERATION_NURSERY)
        mono_atomic_inc_i32 (&mono_perfcounters->gc_collections0);
    else
        mono_atomic_inc_i32 (&mono_perfcounters->gc_collections1);
#endif
}
 
void
sgen_client_binary_protocol_collection_end (int minor_gc_count, int generation, long long num_objects_scanned, long long num_unique_objects_scanned)
{
    MONO_GC_END (generation);
 
    MONO_PROFILER_RAISE (gc_event, (MONO_GC_EVENT_END, generation));
}
 
#ifdef HOST_WASM
void
sgen_client_schedule_background_job (void (*cb)(void))
{
    mono_threads_schedule_background_job (cb);
}
 
#endif
 
#endif