summaryrefslogtreecommitdiff
path: root/src/vm/syncblk.cpp
blob: eba84e92376edf400d448f4588ee2afd321d0408 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// SYNCBLK.CPP
//

//
// Definition of a SyncBlock and the SyncBlockCache which manages it
//


#include "common.h"

#include "vars.hpp"
#include "util.hpp"
#include "class.h"
#include "object.h"
#include "threads.h"
#include "excep.h"
#include "threads.h"
#include "syncblk.h"
#include "interoputil.h"
#include "encee.h"
#include "perfcounters.h"
#include "eventtrace.h"
#include "dllimportcallback.h"
#include "comcallablewrapper.h"
#include "eeconfig.h"
#include "corhost.h"
#include "comdelegate.h"
#include "finalizerthread.h"

#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#endif // FEATURE_COMINTEROP

// Allocate 4K worth. Typically enough
#define MAXSYNCBLOCK (0x1000-sizeof(void*))/sizeof(SyncBlock)
#define SYNC_TABLE_INITIAL_SIZE 250

//#define DUMP_SB

class  SyncBlockArray
{
  public:
    SyncBlockArray *m_Next;
    BYTE            m_Blocks[MAXSYNCBLOCK * sizeof (SyncBlock)];
};

// For in-place constructor
BYTE g_SyncBlockCacheInstance[sizeof(SyncBlockCache)];

SPTR_IMPL (SyncBlockCache, SyncBlockCache, s_pSyncBlockCache);

#ifndef DACCESS_COMPILE



void SyncBlock::OnADUnload()
{
    WRAPPER_NO_CONTRACT;
#ifdef EnC_SUPPORTED
    if (m_pEnCInfo)
    {
        m_pEnCInfo->Cleanup();
        m_pEnCInfo = NULL;
    }
#endif
}

#ifndef FEATURE_PAL
// static
SLIST_HEADER InteropSyncBlockInfo::s_InteropInfoStandbyList;
#endif // !FEATURE_PAL

InteropSyncBlockInfo::~InteropSyncBlockInfo()
{
    CONTRACTL
    {
        NOTHROW;
        DESTRUCTOR_CHECK;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    FreeUMEntryThunkOrInterceptStub();
}

#ifndef FEATURE_PAL
// Deletes all items in code:s_InteropInfoStandbyList.
void InteropSyncBlockInfo::FlushStandbyList()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END;

    PSLIST_ENTRY pEntry = InterlockedFlushSList(&InteropSyncBlockInfo::s_InteropInfoStandbyList);
    while (pEntry)
    {
        PSLIST_ENTRY pNextEntry = pEntry->Next;

        // make sure to use the global delete since the destructor has already run
        ::delete (void *)pEntry;
        pEntry = pNextEntry;
    }
}
#endif // !FEATURE_PAL

void InteropSyncBlockInfo::FreeUMEntryThunkOrInterceptStub()
{
    CONTRACTL
    {
        NOTHROW;
        DESTRUCTOR_CHECK;
        GC_TRIGGERS;
        MODE_ANY;
    }
    CONTRACTL_END

    if (!g_fEEShutDown)
    {
        void *pUMEntryThunk = GetUMEntryThunk();
        if (pUMEntryThunk != NULL)
        {
            COMDelegate::RemoveEntryFromFPtrHash((UPTR)pUMEntryThunk);
            UMEntryThunk::FreeUMEntryThunk((UMEntryThunk *)pUMEntryThunk);
        }
        else
        {
#if defined(_TARGET_X86_)
            Stub *pInterceptStub = GetInterceptStub();

            if (pInterceptStub != NULL)
            {
                // There may be multiple chained stubs, i.e. host hook stub calling MDA stack
                // imbalance stub, and the following DecRef will free all of them.
                pInterceptStub->DecRef();
            }
#else // _TARGET_X86_
            // Intercept stubs are currently not used on other platforms.
            _ASSERTE(GetInterceptStub() == NULL);
#endif // _TARGET_X86_
        }
    }
    m_pUMEntryThunkOrInterceptStub = NULL;
}

#ifdef FEATURE_COMINTEROP
// Returns either NULL or an RCW on which AcquireLock has been called.
RCW* InteropSyncBlockInfo::GetRCWAndIncrementUseCount()
{
    LIMITED_METHOD_CONTRACT;

    DWORD dwSwitchCount = 0;
    while (true)
    {
        RCW *pRCW = VolatileLoad(&m_pRCW);
        if ((size_t)pRCW <= 0x1)
        {
            // the RCW never existed or has been released
            return NULL;
        }

        if (((size_t)pRCW & 0x1) == 0x0)
        {
            // it looks like we have a chance, try to acquire the lock
            RCW *pLockedRCW = (RCW *)((size_t)pRCW | 0x1);
            if (InterlockedCompareExchangeT(&m_pRCW, pLockedRCW, pRCW) == pRCW)
            {
                // we have the lock on the m_pRCW field, now we can safely "use" the RCW
                pRCW->IncrementUseCount();

                // release the m_pRCW lock
                VolatileStore(&m_pRCW, pRCW);

                // and return the RCW
                return pRCW;
            }
        }

        // somebody else holds the lock, retry
        __SwitchToThread(0, ++dwSwitchCount);
    }
}

// Sets the m_pRCW field in a thread-safe manner, pRCW can be NULL.
void InteropSyncBlockInfo::SetRawRCW(RCW* pRCW)
{
    LIMITED_METHOD_CONTRACT;

    if (pRCW != NULL)
    {
        // we never set two different RCWs on a single object
        _ASSERTE(m_pRCW == NULL);
        m_pRCW = pRCW;
    }
    else
    {
        DWORD dwSwitchCount = 0;
        while (true)
        {
            RCW *pOldRCW = VolatileLoad(&m_pRCW);

            if ((size_t)pOldRCW <= 0x1)
            {
                // the RCW never existed or has been released
                VolatileStore(&m_pRCW, (RCW *)0x1);
                return;
            }

            if (((size_t)pOldRCW & 0x1) == 0x0)
            {
                // it looks like we have a chance, set the RCW to 0x1
                if (InterlockedCompareExchangeT(&m_pRCW, (RCW *)0x1, pOldRCW) == pOldRCW)
                {
                    // we made it
                    return;
                }
            }

            // somebody else holds the lock, retry
            __SwitchToThread(0, ++dwSwitchCount);
        }
    }
}
#endif // FEATURE_COMINTEROP

void UMEntryThunk::OnADUnload()
{
    LIMITED_METHOD_CONTRACT;
    m_pObjectHandle = NULL;
}

#endif // !DACCESS_COMPILE

PTR_SyncTableEntry SyncTableEntry::GetSyncTableEntry()
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;

    return (PTR_SyncTableEntry)g_pSyncTable;
}

#ifndef DACCESS_COMPILE

SyncTableEntry*& SyncTableEntry::GetSyncTableEntryByRef()
{
    LIMITED_METHOD_CONTRACT;
    return g_pSyncTable;
}

/* static */
SyncBlockCache*& SyncBlockCache::GetSyncBlockCache()
{
    LIMITED_METHOD_CONTRACT;

    return s_pSyncBlockCache;
}


//----------------------------------------------------------------------------
//
//   ThreadQueue Implementation
//
//----------------------------------------------------------------------------
#endif //!DACCESS_COMPILE

// Given a link in the chain, get the Thread that it represents
/* static */
inline PTR_WaitEventLink ThreadQueue::WaitEventLinkForLink(PTR_SLink pLink)
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;
    return (PTR_WaitEventLink) (((PTR_BYTE) pLink) - offsetof(WaitEventLink, m_LinkSB));
}

#ifndef DACCESS_COMPILE

// Unlink the head of the Q.  We are always in the SyncBlock's critical
// section.
/* static */
inline WaitEventLink *ThreadQueue::DequeueThread(SyncBlock *psb)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        CAN_TAKE_LOCK;
    }
    CONTRACTL_END;

    // Be careful, the debugger inspects the queue from out of process and just looks at the memory...
    // it must be valid even if the lock is held. Be careful if you change the way the queue is updated.
    SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());

    WaitEventLink      *ret = NULL;
    SLink       *pLink = psb->m_Link.m_pNext;

    if (pLink)
    {
        psb->m_Link.m_pNext = pLink->m_pNext;
#ifdef _DEBUG
        pLink->m_pNext = (SLink *)POISONC;
#endif
        ret = WaitEventLinkForLink(pLink);
        _ASSERTE(ret->m_WaitSB == psb);
        COUNTER_ONLY(GetPerfCounters().m_LocksAndThreads.cQueueLength--);
    }
    return ret;
}

// Enqueue is the slow one.  We have to find the end of the Q since we don't
// want to burn storage for this in the SyncBlock.
/* static */
inline void ThreadQueue::EnqueueThread(WaitEventLink *pWaitEventLink, SyncBlock *psb)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        CAN_TAKE_LOCK;
    }
    CONTRACTL_END;

    _ASSERTE (pWaitEventLink->m_LinkSB.m_pNext == NULL);

    // Be careful, the debugger inspects the queue from out of process and just looks at the memory...
    // it must be valid even if the lock is held. Be careful if you change the way the queue is updated.
    SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());

    COUNTER_ONLY(GetPerfCounters().m_LocksAndThreads.cQueueLength++);

    SLink       *pPrior = &psb->m_Link;

    while (pPrior->m_pNext)
    {
        // We shouldn't already be in the waiting list!
        _ASSERTE(pPrior->m_pNext != &pWaitEventLink->m_LinkSB);

        pPrior = pPrior->m_pNext;
    }
    pPrior->m_pNext = &pWaitEventLink->m_LinkSB;
}


// Wade through the SyncBlock's list of waiting threads and remove the
// specified thread.
/* static */
BOOL ThreadQueue::RemoveThread (Thread *pThread, SyncBlock *psb)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    BOOL res = FALSE;

    // Be careful, the debugger inspects the queue from out of process and just looks at the memory...
    // it must be valid even if the lock is held. Be careful if you change the way the queue is updated.
    SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());

    SLink       *pPrior = &psb->m_Link;
    SLink       *pLink;
    WaitEventLink *pWaitEventLink;

    while ((pLink = pPrior->m_pNext) != NULL)
    {
        pWaitEventLink = WaitEventLinkForLink(pLink);
        if (pWaitEventLink->m_Thread == pThread)
        {
            pPrior->m_pNext = pLink->m_pNext;
#ifdef _DEBUG
            pLink->m_pNext = (SLink *)POISONC;
#endif
            _ASSERTE(pWaitEventLink->m_WaitSB == psb);
            COUNTER_ONLY(GetPerfCounters().m_LocksAndThreads.cQueueLength--);
            res = TRUE;
            break;
        }
        pPrior = pLink;
    }
    return res;
}

#endif //!DACCESS_COMPILE

#ifdef DACCESS_COMPILE
// Enumerates the threads in the queue from front to back by calling
// pCallbackFunction on each one
/* static */
void ThreadQueue::EnumerateThreads(SyncBlock *psb, FP_TQ_THREAD_ENUMERATION_CALLBACK pCallbackFunction, void* pUserData)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
    SUPPORTS_DAC;

    PTR_SLink pLink = psb->m_Link.m_pNext;
    PTR_WaitEventLink pWaitEventLink;

    while (pLink != NULL)
    {
        pWaitEventLink = WaitEventLinkForLink(pLink);

        pCallbackFunction(pWaitEventLink->m_Thread, pUserData);
        pLink = pLink->m_pNext;
    }
}
#endif //DACCESS_COMPILE

#ifndef DACCESS_COMPILE

// ***************************************************************************
//
//              Ephemeral Bitmap Helper
//
// ***************************************************************************

#define card_size 32

#define card_word_width 32

size_t CardIndex (size_t card)
{
    LIMITED_METHOD_CONTRACT;
    return card_size * card;
}

size_t CardOf (size_t idx)
{
    LIMITED_METHOD_CONTRACT;
    return idx / card_size;
}

size_t CardWord (size_t card)
{
    LIMITED_METHOD_CONTRACT;
    return card / card_word_width;
}
inline
unsigned CardBit (size_t card)
{
    LIMITED_METHOD_CONTRACT;
    return (unsigned)(card % card_word_width);
}

inline
void SyncBlockCache::SetCard (size_t card)
{
    WRAPPER_NO_CONTRACT;
    m_EphemeralBitmap [CardWord (card)] =
        (m_EphemeralBitmap [CardWord (card)] | (1 << CardBit (card)));
}

inline
void SyncBlockCache::ClearCard (size_t card)
{
    WRAPPER_NO_CONTRACT;
    m_EphemeralBitmap [CardWord (card)] =
        (m_EphemeralBitmap [CardWord (card)] & ~(1 << CardBit (card)));
}

inline
BOOL  SyncBlockCache::CardSetP (size_t card)
{
    WRAPPER_NO_CONTRACT;
    return ( m_EphemeralBitmap [ CardWord (card) ] & (1 << CardBit (card)));
}

inline
void SyncBlockCache::CardTableSetBit (size_t idx)
{
    WRAPPER_NO_CONTRACT;
    SetCard (CardOf (idx));
}


size_t BitMapSize (size_t cacheSize)
{
    LIMITED_METHOD_CONTRACT;

    return (cacheSize + card_size * card_word_width - 1)/ (card_size * card_word_width);
}

// ***************************************************************************
//
//              SyncBlockCache class implementation
//
// ***************************************************************************

SyncBlockCache::SyncBlockCache()
    : m_pCleanupBlockList(NULL),
      m_FreeBlockList(NULL),

      // NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
      // If you remove this flag, we will switch to preemptive mode when entering
      // g_criticalSection, which means all functions that enter it will become
      // GC_TRIGGERS.  (This includes all uses of LockHolder around SyncBlockCache::GetSyncBlockCache().
      // So be sure to update the contracts if you remove this flag.
      m_CacheLock(CrstSyncBlockCache, (CrstFlags) (CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD)),

      m_FreeCount(0),
      m_ActiveCount(0),
      m_SyncBlocks(0),
      m_FreeSyncBlock(0),
      m_FreeSyncTableIndex(1),
      m_FreeSyncTableList(0),
      m_SyncTableSize(SYNC_TABLE_INITIAL_SIZE),
      m_OldSyncTables(0),
      m_bSyncBlockCleanupInProgress(FALSE),
      m_EphemeralBitmap(0)
{
    CONTRACTL
    {
        CONSTRUCTOR_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;
}


// This method is NO longer called.
SyncBlockCache::~SyncBlockCache()
{
    CONTRACTL
    {
        DESTRUCTOR_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Clear the list the fast way.
    m_FreeBlockList = NULL;
    //<TODO>@todo we can clear this fast too I guess</TODO>
    m_pCleanupBlockList = NULL;

    // destruct all arrays
    while (m_SyncBlocks)
    {
        SyncBlockArray *next = m_SyncBlocks->m_Next;
        delete m_SyncBlocks;
        m_SyncBlocks = next;
    }

    // Also, now is a good time to clean up all the old tables which we discarded
    // when we overflowed them.
    SyncTableEntry* arr;
    while ((arr = m_OldSyncTables) != 0)
    {
        m_OldSyncTables = (SyncTableEntry*)arr[0].m_Object.Load();
        delete arr;
    }
}


// When the GC determines that an object is dead the low bit of the 
// m_Object field of SyncTableEntry is set, however it is not 
// cleaned up because we cant do the COM interop cleanup at GC time.
// It is put on a cleanup list and at a later time (typically during
// finalization, this list is cleaned up. 
// 
void SyncBlockCache::CleanupSyncBlocks()
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_MODE_COOPERATIVE;

    _ASSERTE(GetThread() == FinalizerThread::GetFinalizerThread());

    // Set the flag indicating sync block cleanup is in progress.
    // IMPORTANT: This must be set before the sync block cleanup bit is reset on the thread.
    m_bSyncBlockCleanupInProgress = TRUE;

    struct Param
    {
        SyncBlockCache *pThis;
        SyncBlock* psb;
#ifdef FEATURE_COMINTEROP
        RCW* pRCW;
#endif
    } param;
    param.pThis = this;
    param.psb = NULL;
#ifdef FEATURE_COMINTEROP
    param.pRCW = NULL;
#endif

    EE_TRY_FOR_FINALLY(Param *, pParam, &param)
    {
        // reset the flag
        FinalizerThread::GetFinalizerThread()->ResetSyncBlockCleanup();

        // walk the cleanup list and cleanup 'em up
        while ((pParam->psb = pParam->pThis->GetNextCleanupSyncBlock()) != NULL)
        {
#ifdef FEATURE_COMINTEROP
            InteropSyncBlockInfo* pInteropInfo = pParam->psb->GetInteropInfoNoCreate();
            if (pInteropInfo)
            {
                pParam->pRCW = pInteropInfo->GetRawRCW();
                if (pParam->pRCW)
                {
                    // We should have initialized the cleanup list with the
                    // first RCW cache we created
                    _ASSERTE(g_pRCWCleanupList != NULL);

                    g_pRCWCleanupList->AddWrapper(pParam->pRCW);

                    pParam->pRCW = NULL;
                    pInteropInfo->SetRawRCW(NULL);
                }
            }
#endif // FEATURE_COMINTEROP

            // Delete the sync block.
            pParam->pThis->DeleteSyncBlock(pParam->psb);
            pParam->psb = NULL;

            // pulse GC mode to allow GC to perform its work
            if (FinalizerThread::GetFinalizerThread()->CatchAtSafePointOpportunistic())
            {
                FinalizerThread::GetFinalizerThread()->PulseGCMode();
            }
        }
        
#ifdef FEATURE_COMINTEROP
        // Now clean up the rcw's sorted by context
        if (g_pRCWCleanupList != NULL)
            g_pRCWCleanupList->CleanupAllWrappers();
#endif // FEATURE_COMINTEROP
    }
    EE_FINALLY
    {
        // We are finished cleaning up the sync blocks.
        m_bSyncBlockCleanupInProgress = FALSE;

#ifdef FEATURE_COMINTEROP
        if (param.pRCW)
            param.pRCW->Cleanup();
#endif        

        if (param.psb)
            DeleteSyncBlock(param.psb);
    } EE_END_FINALLY;
}

// When a appdomain is unloading, we need to insure that any pointers to
// it from sync blocks (eg from COM Callable Wrappers) are properly 
// updated so that they fail gracefully if another call is made from
// them.  This is what this routine does.  
// 
VOID SyncBlockCache::CleanupSyncBlocksInAppDomain(AppDomain *pDomain)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

#ifndef DACCESS_COMPILE
    _ASSERTE(IsFinalizerThread());
    
    ADIndex index = pDomain->GetIndex();

    ADID id = pDomain->GetId();

    // Make sure we dont race with anybody updating the table
    DWORD maxIndex;

    {        
        // Taking this lock here avoids races whre m_FreeSyncTableIndex is being updated.
        // (a volatile read would have been enough however).  
        SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());
        maxIndex = m_FreeSyncTableIndex;
    }
    BOOL bModifiedCleanupList=FALSE;
    STRESS_LOG1(LF_APPDOMAIN, LL_INFO100, "To cleanup - %d sync blocks", maxIndex);
    DWORD nb;
    for (nb = 1; nb < maxIndex; nb++)
    {
        // This is a check for syncblocks that were already cleaned up.
        if ((size_t)SyncTableEntry::GetSyncTableEntry()[nb].m_Object.Load() & 1)
        {
            continue;
        }

        // If the syncblock pointer is invalid, nothing more we can do.
        SyncBlock *pSyncBlock = SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock;
        if (!pSyncBlock)
        {
            continue;
        }
        
        // If we happen to have a CCW living in the AppDomain being cleaned, then we need to neuter it.
        //  We do this check early because we have to neuter CCWs for agile objects as well.
        //  Neutering the object simply means we disconnect the object from the CCW so it can no longer
        //  be used.  When its ref-count falls to zero, it gets cleaned up.
        STRESS_LOG1(LF_APPDOMAIN, LL_INFO1000000, "SyncBlock %p.", pSyncBlock);                    
        InteropSyncBlockInfo* pInteropInfo = pSyncBlock->GetInteropInfoNoCreate();
        if (pInteropInfo)
        {
#ifdef FEATURE_COMINTEROP
            ComCallWrapper* pWrap = pInteropInfo->GetCCW();
            if (pWrap)
            {
                SimpleComCallWrapper* pSimpleWrapper = pWrap->GetSimpleWrapper();
                _ASSERTE(pSimpleWrapper);
                    
                if (pSimpleWrapper->GetDomainID() == id)
                {
                    pSimpleWrapper->Neuter();
                }
            }          
#endif // FEATURE_COMINTEROP

            UMEntryThunk* umThunk=(UMEntryThunk*)pInteropInfo->GetUMEntryThunk();
                
            if (umThunk && umThunk->GetDomainId()==id)
            {
                umThunk->OnADUnload();
                STRESS_LOG1(LF_APPDOMAIN, LL_INFO100, "Thunk %x unloaded", umThunk);
            }       

#ifdef FEATURE_COMINTEROP
            {
                // we need to take RCWCache lock to avoid the race with another thread which is 
                // removing the RCW from cache, decoupling it from the object, and deleting the RCW.
                RCWCache* pCache = pDomain->GetRCWCache();
                _ASSERTE(pCache);
                RCWCache::LockHolder lh(pCache);
                RCW* pRCW = pInteropInfo->GetRawRCW();
                if (pRCW && pRCW->GetDomain()==pDomain)
                {
                    // We should have initialized the cleanup list with the
                    // first RCW cache we created
                    _ASSERTE(g_pRCWCleanupList != NULL);

                    g_pRCWCleanupList->AddWrapper(pRCW);

                    pCache->RemoveWrapper(pRCW);
                    pInteropInfo->SetRawRCW(NULL);
                    bModifiedCleanupList=TRUE;
                }
            }                         
#endif // FEATURE_COMINTEROP
        }

        // NOTE: this will only notify the sync block if it is non-agile and living in the unloading domain.
        //  Agile objects that are still alive will not get notification!
        if (pSyncBlock->GetAppDomainIndex() == index)
        {
            pSyncBlock->OnADUnload();
        }
    }
    STRESS_LOG1(LF_APPDOMAIN, LL_INFO100, "AD cleanup - %d sync blocks done", nb);
    // Make sure nobody decreased m_FreeSyncTableIndex behind our back (we would read
    // off table limits)
    _ASSERTE(maxIndex <= m_FreeSyncTableIndex);

    if (bModifiedCleanupList)
        GetThread()->SetSyncBlockCleanup();

    while (GetThread()->RequireSyncBlockCleanup()) //we also might have something in the cleanup list
        CleanupSyncBlocks();
    
#ifdef _DEBUG
      {            
            SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());
            DWORD maxIndex = m_FreeSyncTableIndex;
        for (DWORD nb = 1; nb < maxIndex; nb++)
        {
            if ((size_t)SyncTableEntry::GetSyncTableEntry()[nb].m_Object.Load() & 1)
            {
                continue;
            }

            // If the syncblock pointer is invalid, nothing more we can do.
            SyncBlock *pSyncBlock = SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock;
            if (!pSyncBlock)
            {
                continue;
            }            
            InteropSyncBlockInfo* pInteropInfo = pSyncBlock->GetInteropInfoNoCreate();
            if (pInteropInfo)
            {
                UMEntryThunk* umThunk=(UMEntryThunk*)pInteropInfo->GetUMEntryThunk();
                
                if (umThunk && umThunk->GetDomainId()==id)
                {
                    _ASSERTE(!umThunk->GetObjectHandle());
                }
            }
            
        }
    }
#endif
    
#endif
}


// create the sync block cache
/* static */
void SyncBlockCache::Attach()
{
    LIMITED_METHOD_CONTRACT;
}

// destroy the sync block cache
// This method is NO longer called.
#if 0
void SyncBlockCache::DoDetach()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    Object *pObj;
    ObjHeader  *pHeader;


    // Ensure that all the critical sections are released.  This is particularly
    // important in DEBUG, because all critical sections are threaded onto a global
    // list which would otherwise be corrupted.
    for (DWORD i=0; i<m_FreeSyncTableIndex; i++)
        if (((size_t)SyncTableEntry::GetSyncTableEntry()[i].m_Object & 1) == 0)
            if (SyncTableEntry::GetSyncTableEntry()[i].m_SyncBlock)
            {
                // <TODO>@TODO -- If threads are executing during this detach, they will
                // fail in various ways:
                //
                // 1) They will race between us tearing these data structures down
                //    as they navigate through them.
                //
                // 2) They will unexpectedly see the syncblock destroyed, even though
                //    they hold the synchronization lock, or have been exposed out
                //    to COM, etc.
                //
                // 3) The instance's hash code may change during the shutdown.
                //
                // The correct solution involves suspending the threads earlier, but
                // changing our suspension code so that it allows pumping if we are
                // in a shutdown case.
                //
                // </TODO>

                // Make sure this gets updated because the finalizer thread & others
                // will continue to run for a short while more during our shutdown.
                pObj = SyncTableEntry::GetSyncTableEntry()[i].m_Object;
                pHeader = pObj->GetHeader();

                {
                    ENTER_SPIN_LOCK(pHeader);
                    ADIndex appDomainIndex = pHeader->GetAppDomainIndex();
                    if (! appDomainIndex.m_dwIndex)
                    {
                        SyncBlock* syncBlock = pObj->PassiveGetSyncBlock();
                        if (syncBlock)
                            appDomainIndex = syncBlock->GetAppDomainIndex();
                    }

                    pHeader->ResetIndex();

        if (appDomainIndex.m_dwIndex)
                    {
                        pHeader->SetIndex(appDomainIndex.m_dwIndex<<SBLK_APPDOMAIN_SHIFT);
                    }
                    LEAVE_SPIN_LOCK(pHeader);
                }

                SyncTableEntry::GetSyncTableEntry()[i].m_Object = (Object *)(m_FreeSyncTableList | 1);
                m_FreeSyncTableList = i << 1;

                DeleteSyncBlock(SyncTableEntry::GetSyncTableEntry()[i].m_SyncBlock);
            }
}
#endif

// destroy the sync block cache
/* static */
// This method is NO longer called.
#if 0
void SyncBlockCache::Detach()
{
    SyncBlockCache::GetSyncBlockCache()->DoDetach();
}
#endif


// create the sync block cache
/* static */
void SyncBlockCache::Start()
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    DWORD* bm = new DWORD [BitMapSize(SYNC_TABLE_INITIAL_SIZE+1)];

    memset (bm, 0, BitMapSize (SYNC_TABLE_INITIAL_SIZE+1)*sizeof(DWORD));

    SyncTableEntry::GetSyncTableEntryByRef() = new SyncTableEntry[SYNC_TABLE_INITIAL_SIZE+1];
#ifdef _DEBUG
    for (int i=0; i<SYNC_TABLE_INITIAL_SIZE+1; i++) {
        SyncTableEntry::GetSyncTableEntry()[i].m_SyncBlock = NULL;
    }
#endif    

    SyncTableEntry::GetSyncTableEntry()[0].m_SyncBlock = 0;
    SyncBlockCache::GetSyncBlockCache() = new (&g_SyncBlockCacheInstance) SyncBlockCache;

    SyncBlockCache::GetSyncBlockCache()->m_EphemeralBitmap = bm;

#ifndef FEATURE_PAL
    InitializeSListHead(&InteropSyncBlockInfo::s_InteropInfoStandbyList);
#endif // !FEATURE_PAL
}


// destroy the sync block cache
/* static */
void SyncBlockCache::Stop()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // cache must be destroyed first, since it can traverse the table to find all the
    // sync blocks which are live and thus must have their critical sections destroyed.
    if (SyncBlockCache::GetSyncBlockCache())
    {
        delete SyncBlockCache::GetSyncBlockCache();
        SyncBlockCache::GetSyncBlockCache() = 0;
    }

    if (SyncTableEntry::GetSyncTableEntry())
    {
        delete SyncTableEntry::GetSyncTableEntry();
        SyncTableEntry::GetSyncTableEntryByRef() = 0;
    }
}


void    SyncBlockCache::InsertCleanupSyncBlock(SyncBlock* psb)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // free up the threads that are waiting before we use the link
    // for other purposes
    if (psb->m_Link.m_pNext != NULL)
    {
        while (ThreadQueue::DequeueThread(psb) != NULL)
            continue;
    }

#ifdef FEATURE_COMINTEROP
    if (psb->m_pInteropInfo)
    {
        // called during GC
        // so do only minorcleanup
        MinorCleanupSyncBlockComData(psb->m_pInteropInfo);
    }
#endif // FEATURE_COMINTEROP

    // This method will be called only by the GC thread
    //<TODO>@todo add an assert for the above statement</TODO>
    // we don't need to lock here
    //EnterCacheLock();

    psb->m_Link.m_pNext = m_pCleanupBlockList;
    m_pCleanupBlockList = &psb->m_Link;

    // we don't need a lock here
    //LeaveCacheLock();
}

SyncBlock* SyncBlockCache::GetNextCleanupSyncBlock()
{
    LIMITED_METHOD_CONTRACT;

    // we don't need a lock here,
    // as this is called only on the finalizer thread currently

    SyncBlock       *psb = NULL;
    if (m_pCleanupBlockList)
    {
        // get the actual sync block pointer
        psb = (SyncBlock *) (((BYTE *) m_pCleanupBlockList) - offsetof(SyncBlock, m_Link));
        m_pCleanupBlockList = m_pCleanupBlockList->m_pNext;
    }
    return psb;
}


// returns and removes the next free syncblock from the list
// the cache lock must be entered to call this
SyncBlock *SyncBlockCache::GetNextFreeSyncBlock()
{
    CONTRACTL
    {
        INJECT_FAULT(COMPlusThrowOM());
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

#ifdef _DEBUG  // Instrumentation for OOM fault injection testing
    delete new char;
#endif

    SyncBlock       *psb;
    SLink           *plst = m_FreeBlockList;

    m_ActiveCount++;

    if (plst)
    {
        m_FreeBlockList = m_FreeBlockList->m_pNext;

        // shouldn't be 0
        m_FreeCount--;

        // get the actual sync block pointer
        psb = (SyncBlock *) (((BYTE *) plst) - offsetof(SyncBlock, m_Link));

        return psb;
    }
    else
    {
        if ((m_SyncBlocks == NULL) || (m_FreeSyncBlock >= MAXSYNCBLOCK))
        {
#ifdef DUMP_SB
//            LogSpewAlways("Allocating new syncblock array\n");
//            DumpSyncBlockCache();
#endif
            SyncBlockArray* newsyncblocks = new(SyncBlockArray);
            if (!newsyncblocks)
                COMPlusThrowOM ();

            newsyncblocks->m_Next = m_SyncBlocks;
            m_SyncBlocks = newsyncblocks;
            m_FreeSyncBlock = 0;
        }
        return &(((SyncBlock*)m_SyncBlocks->m_Blocks)[m_FreeSyncBlock++]);
    }

}

void SyncBlockCache::Grow()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    STRESS_LOG0(LF_SYNC, LL_INFO10000, "SyncBlockCache::NewSyncBlockSlot growing SyncBlockCache \n");
        
    NewArrayHolder<SyncTableEntry> newSyncTable (NULL);
    NewArrayHolder<DWORD>          newBitMap    (NULL);
    DWORD *                        oldBitMap;

    // Compute the size of the new synctable. Normally, we double it - unless
    // doing so would create slots with indices too high to fit within the
    // mask. If so, we create a synctable up to the mask limit. If we're
    // already at the mask limit, then caller is out of luck.
    DWORD newSyncTableSize;
    if (m_SyncTableSize <= (MASK_SYNCBLOCKINDEX >> 1))
    {
        newSyncTableSize = m_SyncTableSize * 2;
    }
    else
    {
        newSyncTableSize = MASK_SYNCBLOCKINDEX;
    }

    if (!(newSyncTableSize > m_SyncTableSize)) // Make sure we actually found room to grow!
    {
        COMPlusThrowOM();
    }

    newSyncTable = new SyncTableEntry[newSyncTableSize];
    newBitMap = new DWORD[BitMapSize (newSyncTableSize)];


    {
        //! From here on, we assume that we will succeed and start doing global side-effects.
        //! Any operation that could fail must occur before this point.
        CANNOTTHROWCOMPLUSEXCEPTION();
        FAULT_FORBID();

        newSyncTable.SuppressRelease();
        newBitMap.SuppressRelease();


        // We chain old table because we can't delete
        // them before all the threads are stoppped
        // (next GC)
        SyncTableEntry::GetSyncTableEntry() [0].m_Object = (Object *)m_OldSyncTables;
        m_OldSyncTables = SyncTableEntry::GetSyncTableEntry();

        memset (newSyncTable, 0, newSyncTableSize*sizeof (SyncTableEntry));
        memset (newBitMap, 0, BitMapSize (newSyncTableSize)*sizeof (DWORD));
        CopyMemory (newSyncTable, SyncTableEntry::GetSyncTableEntry(),
                    m_SyncTableSize*sizeof (SyncTableEntry));

        CopyMemory (newBitMap, m_EphemeralBitmap,
                    BitMapSize (m_SyncTableSize)*sizeof (DWORD));

        oldBitMap = m_EphemeralBitmap;
        m_EphemeralBitmap = newBitMap;
        delete[] oldBitMap;

        _ASSERTE((m_SyncTableSize & MASK_SYNCBLOCKINDEX) == m_SyncTableSize);
        // note: we do not care if another thread does not see the new size
        // however we really do not want it to see the new size without seeing the new array
        //@TODO do we still leak here if two threads come here at the same time ?
        FastInterlockExchangePointer(&SyncTableEntry::GetSyncTableEntryByRef(), newSyncTable.GetValue());

        m_FreeSyncTableIndex++;

        m_SyncTableSize = newSyncTableSize;

#ifdef _DEBUG
        static int dumpSBOnResize = -1;

        if (dumpSBOnResize == -1)
            dumpSBOnResize = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpOnResize);

        if (dumpSBOnResize)
        {
            LogSpewAlways("SyncBlockCache resized\n");
            DumpSyncBlockCache();
        }
#endif
    }
}

DWORD SyncBlockCache::NewSyncBlockSlot(Object *obj)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;
    _ASSERTE(m_CacheLock.OwnedByCurrentThread()); // GetSyncBlock takes the lock, make sure no one else does.  

    DWORD indexNewEntry;
    if (m_FreeSyncTableList)
    {
        indexNewEntry = (DWORD)(m_FreeSyncTableList >> 1);
        _ASSERTE ((size_t)SyncTableEntry::GetSyncTableEntry()[indexNewEntry].m_Object.Load() & 1);
        m_FreeSyncTableList = (size_t)SyncTableEntry::GetSyncTableEntry()[indexNewEntry].m_Object.Load() & ~1;
    }
    else if ((indexNewEntry = (DWORD)(m_FreeSyncTableIndex)) >= m_SyncTableSize)
    {
        // This is kept out of line to keep stuff like the C++ EH prolog (needed for holders) off 
        // of the common path.
        Grow();
    }
    else
    {
#ifdef _DEBUG
        static int dumpSBOnNewIndex = -1;

        if (dumpSBOnNewIndex == -1)
            dumpSBOnNewIndex = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpOnNewIndex);

        if (dumpSBOnNewIndex)
        {
            LogSpewAlways("SyncBlockCache index incremented\n");
            DumpSyncBlockCache();
        }
#endif
        m_FreeSyncTableIndex ++;
    }


    CardTableSetBit (indexNewEntry);

    // In debug builds the m_SyncBlock at indexNewEntry should already be null, since we should 
    // start out with a null table and always null it out on delete. 
    _ASSERTE(SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_SyncBlock == NULL);
    SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_SyncBlock = NULL;
    SyncTableEntry::GetSyncTableEntry() [indexNewEntry].m_Object = obj;

    _ASSERTE(indexNewEntry != 0);

    return indexNewEntry;
}


// free a used sync block, only called from CleanupSyncBlocks.  
void SyncBlockCache::DeleteSyncBlock(SyncBlock *psb)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    // clean up comdata
    if (psb->m_pInteropInfo)
    {
#ifdef FEATURE_COMINTEROP
        CleanupSyncBlockComData(psb->m_pInteropInfo);
#endif // FEATURE_COMINTEROP

#ifndef FEATURE_PAL
        if (g_fEEShutDown)
        {
            delete psb->m_pInteropInfo;
        }
        else
        {
            psb->m_pInteropInfo->~InteropSyncBlockInfo();
            InterlockedPushEntrySList(&InteropSyncBlockInfo::s_InteropInfoStandbyList, (PSLIST_ENTRY)psb->m_pInteropInfo);
        }
#else // !FEATURE_PAL
        delete psb->m_pInteropInfo;
#endif // !FEATURE_PAL
    }

#ifdef EnC_SUPPORTED
    // clean up EnC info
    if (psb->m_pEnCInfo)
        psb->m_pEnCInfo->Cleanup();
#endif // EnC_SUPPORTED

    // Destruct the SyncBlock, but don't reclaim its memory.  (Overridden
    // operator delete).
    delete psb;

    //synchronizer with the consumers,
    // <TODO>@todo we don't really need a lock here, we can come up
    // with some simple algo to avoid taking a lock </TODO>
    {
        SyncBlockCache::LockHolder lh(this);

        DeleteSyncBlockMemory(psb);
    }
}


// returns the sync block memory to the free pool but does not destruct sync block (must own cache lock already)
void    SyncBlockCache::DeleteSyncBlockMemory(SyncBlock *psb)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        FORBID_FAULT;
    }
    CONTRACTL_END

    m_ActiveCount--;
    m_FreeCount++;

    psb->m_Link.m_pNext = m_FreeBlockList;
    m_FreeBlockList = &psb->m_Link;

}

// free a used sync block
void SyncBlockCache::GCDeleteSyncBlock(SyncBlock *psb)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Destruct the SyncBlock, but don't reclaim its memory.  (Overridden
    // operator delete).
    delete psb;

    m_ActiveCount--;
    m_FreeCount++;

    psb->m_Link.m_pNext = m_FreeBlockList;
    m_FreeBlockList = &psb->m_Link;
}

void SyncBlockCache::GCWeakPtrScan(HANDLESCANPROC scanProc, uintptr_t lp1, uintptr_t lp2)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;


    // First delete the obsolete arrays since we have exclusive access
    BOOL fSetSyncBlockCleanup = FALSE;

    SyncTableEntry* arr;
    while ((arr = m_OldSyncTables) != NULL)
    {
        m_OldSyncTables = (SyncTableEntry*)arr[0].m_Object.Load();
        delete arr;
    }

#ifdef DUMP_SB
    LogSpewAlways("GCWeakPtrScan starting\n");
#endif

#ifdef VERIFY_HEAP
   if (g_pConfig->GetHeapVerifyLevel()& EEConfig::HEAPVERIFY_SYNCBLK)
       STRESS_LOG0 (LF_GC | LF_SYNC, LL_INFO100, "GCWeakPtrScan starting\n");
#endif

   if (GCHeapUtilities::GetGCHeap()->GetCondemnedGeneration() < GCHeapUtilities::GetGCHeap()->GetMaxGeneration())
   {
#ifdef VERIFY_HEAP
        //for VSW 294550: we saw stale obeject reference in SyncBlkCache, so we want to make sure the card 
        //table logic above works correctly so that every ephemeral entry is promoted. 
        //For verification, we make a copy of the sync table in relocation phase and promote it use the 
        //slow approach and compare the result with the original one
        DWORD freeSyncTalbeIndexCopy = m_FreeSyncTableIndex;
        SyncTableEntry * syncTableShadow = NULL;
        if ((g_pConfig->GetHeapVerifyLevel()& EEConfig::HEAPVERIFY_SYNCBLK) && !((ScanContext*)lp1)->promotion)
        {
            syncTableShadow = new(nothrow) SyncTableEntry [m_FreeSyncTableIndex];
            if (syncTableShadow)
            {
                memcpy (syncTableShadow, SyncTableEntry::GetSyncTableEntry(), m_FreeSyncTableIndex * sizeof (SyncTableEntry));                
            }
        }
#endif //VERIFY_HEAP

        //scan the bitmap
        size_t dw = 0;
        while (1)
        {
            while (dw < BitMapSize (m_SyncTableSize) && (m_EphemeralBitmap[dw]==0))
            {
                dw++;
            }
            if (dw < BitMapSize (m_SyncTableSize))
            {
                //found one
                for (int i = 0; i < card_word_width; i++)
                {
                    size_t card = i+dw*card_word_width;
                    if (CardSetP (card))
                    {
                        BOOL clear_card = TRUE;
                        for (int idx = 0; idx < card_size; idx++)
                        {
                            size_t nb = CardIndex (card) + idx;
                            if (( nb < m_FreeSyncTableIndex) && (nb > 0))
                            {
                                Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object;
                                if (o && !((size_t)o & 1))
                                {
                                    if (GCHeapUtilities::GetGCHeap()->IsEphemeral (o))
                                    {
                                        clear_card = FALSE;

                                        GCWeakPtrScanElement ((int)nb, scanProc,
                                                              lp1, lp2, fSetSyncBlockCleanup);
                                    }
                                }
                            }
                        }
                        if (clear_card)
                            ClearCard (card);
                    }
                }
                dw++;
            }
            else
                break;
        }
        
#ifdef VERIFY_HEAP
        //for VSW 294550: we saw stale obeject reference in SyncBlkCache, so we want to make sure the card 
        //table logic above works correctly so that every ephemeral entry is promoted. To verify, we make a 
        //copy of the sync table and promote it use the slow approach and compare the result with the real one
        if (g_pConfig->GetHeapVerifyLevel()& EEConfig::HEAPVERIFY_SYNCBLK)
        {
            if (syncTableShadow)
            {
                for (DWORD nb = 1; nb < m_FreeSyncTableIndex; nb++)
                {
                    Object **keyv = (Object **) &syncTableShadow[nb].m_Object;

                    if (((size_t) *keyv & 1) == 0)
                    {
                        (*scanProc) (keyv, NULL, lp1, lp2);
                        SyncBlock   *pSB = syncTableShadow[nb].m_SyncBlock;
                        if (*keyv != 0 && (!pSB || !pSB->IsIDisposable()))
                        {
                            if (syncTableShadow[nb].m_Object != SyncTableEntry::GetSyncTableEntry()[nb].m_Object)
                                DebugBreak ();
                        }
                    }
                } 
                delete []syncTableShadow;
                syncTableShadow = NULL;
            }
            if (freeSyncTalbeIndexCopy != m_FreeSyncTableIndex)
                DebugBreak ();
        }
#endif //VERIFY_HEAP

    }
    else
    {
        for (DWORD nb = 1; nb < m_FreeSyncTableIndex; nb++)
        {
            GCWeakPtrScanElement (nb, scanProc, lp1, lp2, fSetSyncBlockCleanup);
        }


    }

    if (fSetSyncBlockCleanup)
    {
        // mark the finalizer thread saying requires cleanup
        FinalizerThread::GetFinalizerThread()->SetSyncBlockCleanup();
        FinalizerThread::EnableFinalization();
    }

#if defined(VERIFY_HEAP)
    if (g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_GC)
    {
        if (((ScanContext*)lp1)->promotion)
        {

            for (int nb = 1; nb < (int)m_FreeSyncTableIndex; nb++)
            {
                Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object;
                if (((size_t)o & 1) == 0)
                {
                    o->Validate();
                }
            }
        }
    }
#endif // VERIFY_HEAP
}

/* Scan the weak pointers in the SyncBlockEntry and report them to the GC.  If the
   reference is dead, then return TRUE */

BOOL SyncBlockCache::GCWeakPtrScanElement (int nb, HANDLESCANPROC scanProc, LPARAM lp1, LPARAM lp2,
                                           BOOL& cleanup)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    Object **keyv = (Object **) &SyncTableEntry::GetSyncTableEntry()[nb].m_Object;

#ifdef DUMP_SB
    struct Param
    {
        Object **keyv;
        char *name;
    } param;
    param.keyv = keyv;

    PAL_TRY(Param *, pParam, &param) {
        if (! *pParam->keyv)
            pParam->name = "null";
        else if ((size_t) *pParam->keyv & 1)
            pParam->name = "free";
        else {
            pParam->name = (*pParam->keyv)->GetClass()->GetDebugClassName();
            if (strlen(pParam->name) == 0)
                pParam->name = "<INVALID>";
        }
    } PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) {
        param.name = "<INVALID>";
    }
    PAL_ENDTRY
    LogSpewAlways("[%4.4d]: %8.8x, %s\n", nb, *keyv, param.name);
#endif

    if (((size_t) *keyv & 1) == 0)
    {
#ifdef VERIFY_HEAP
        if (g_pConfig->GetHeapVerifyLevel () & EEConfig::HEAPVERIFY_SYNCBLK)
        {
            STRESS_LOG3 (LF_GC | LF_SYNC, LL_INFO100000, "scanning syncblk[%d, %p, %p]\n", nb, (size_t)SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock, (size_t)*keyv);
        }
#endif

        (*scanProc) (keyv, NULL, lp1, lp2);
        SyncBlock   *pSB = SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock;
        if ((*keyv == 0 ) || (pSB && pSB->IsIDisposable()))
        {
#ifdef VERIFY_HEAP
            if (g_pConfig->GetHeapVerifyLevel () & EEConfig::HEAPVERIFY_SYNCBLK)
            {
                STRESS_LOG3 (LF_GC | LF_SYNC, LL_INFO100000, "freeing syncblk[%d, %p, %p]\n", nb, (size_t)pSB, (size_t)*keyv);
            }
#endif

            if (*keyv)
            {
                _ASSERTE (pSB);
                GCDeleteSyncBlock(pSB);
                //clean the object syncblock header
                ((Object*)(*keyv))->GetHeader()->GCResetIndex();
            }
            else if (pSB)
            {

                cleanup = TRUE;
                // insert block into cleanup list
                InsertCleanupSyncBlock (SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock);
#ifdef DUMP_SB
                LogSpewAlways("       Cleaning up block at %4.4d\n", nb);
#endif
            }

            // delete the entry
#ifdef DUMP_SB
            LogSpewAlways("       Deleting block at %4.4d\n", nb);
#endif
            SyncTableEntry::GetSyncTableEntry()[nb].m_Object = (Object *)(m_FreeSyncTableList | 1);
            m_FreeSyncTableList = nb << 1;
            SyncTableEntry::GetSyncTableEntry()[nb].m_SyncBlock = NULL;
            return TRUE;
        }
        else
        {
#ifdef DUMP_SB
            LogSpewAlways("       Keeping block at %4.4d with oref %8.8x\n", nb, *keyv);
#endif
        }
    }
    return FALSE;
}

void SyncBlockCache::GCDone(BOOL demoting, int max_gen)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    if (demoting && 
        (GCHeapUtilities::GetGCHeap()->GetCondemnedGeneration() == 
         GCHeapUtilities::GetGCHeap()->GetMaxGeneration()))
    {
        //scan the bitmap
        size_t dw = 0;
        while (1)
        {
            while (dw < BitMapSize (m_SyncTableSize) && 
                   (m_EphemeralBitmap[dw]==(DWORD)~0))
            {
                dw++;
            }
            if (dw < BitMapSize (m_SyncTableSize))
            {
                //found one
                for (int i = 0; i < card_word_width; i++)
                {
                    size_t card = i+dw*card_word_width;
                    if (!CardSetP (card))
                    {
                        for (int idx = 0; idx < card_size; idx++)
                        {
                            size_t nb = CardIndex (card) + idx;
                            if (( nb < m_FreeSyncTableIndex) && (nb > 0))
                            {
                                Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object;
                                if (o && !((size_t)o & 1))
                                {
                                    if (GCHeapUtilities::GetGCHeap()->WhichGeneration (o) < (unsigned int)max_gen)
                                    {
                                        SetCard (card);
                                        break;

                                    }
                                }
                            }
                        }
                    }
                }
                dw++;
            }
            else
                break;
        }
    }
}


#if defined (VERIFY_HEAP)

#ifndef _DEBUG
#ifdef _ASSERTE
#undef _ASSERTE
#endif
#define _ASSERTE(c) if (!(c)) DebugBreak()
#endif

void SyncBlockCache::VerifySyncTableEntry()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    for (DWORD nb = 1; nb < m_FreeSyncTableIndex; nb++)
    {
        Object* o = SyncTableEntry::GetSyncTableEntry()[nb].m_Object;
        // if the slot was just allocated, the object may still be null
        if (o && (((size_t)o & 1) == 0)) 
        {
            //there is no need to verify next object's header because this is called
            //from verify_heap, which will verify every object anyway
            o->Validate(TRUE, FALSE);

            //
            // This loop is just a heuristic to try to catch errors, but it is not 100%.
            // To prevent false positives, we weaken our assert below to exclude the case
            // where the index is still NULL, but we've reached the end of our loop.
            //
            static const DWORD max_iterations = 100;
            DWORD loop = 0;
            
            for (; loop < max_iterations; loop++)
            {
                // The syncblock index may be updating by another thread.
                if (o->GetHeader()->GetHeaderSyncBlockIndex() != 0)
                {
                    break;
                }
                __SwitchToThread(0, CALLER_LIMITS_SPINNING);
            }
            
            DWORD idx = o->GetHeader()->GetHeaderSyncBlockIndex();
            _ASSERTE(idx == nb || ((0 == idx) && (loop == max_iterations)));
            _ASSERTE(!GCHeapUtilities::GetGCHeap()->IsEphemeral(o) || CardSetP(CardOf(nb)));
        }
    }
}

#ifndef _DEBUG
#undef _ASSERTE
#define _ASSERTE(expr) ((void)0)
#endif   // _DEBUG

#endif // VERIFY_HEAP

#ifdef _DEBUG

void DumpSyncBlockCache()
{
    STATIC_CONTRACT_NOTHROW;

    SyncBlockCache *pCache = SyncBlockCache::GetSyncBlockCache();

    LogSpewAlways("Dumping SyncBlockCache size %d\n", pCache->m_FreeSyncTableIndex);

    static int dumpSBStyle = -1;
    if (dumpSBStyle == -1)
        dumpSBStyle = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_SBDumpStyle);
    if (dumpSBStyle == 0)
        return;

    BOOL isString = FALSE;
    DWORD objectCount = 0;
    DWORD slotCount = 0;

    for (DWORD nb = 1; nb < pCache->m_FreeSyncTableIndex; nb++)
    {
        isString = FALSE;
        char buffer[1024], buffer2[1024];
        LPCUTF8 descrip = "null";
        SyncTableEntry *pEntry = &SyncTableEntry::GetSyncTableEntry()[nb];
        Object *oref = (Object *) pEntry->m_Object;
        if (((size_t) oref & 1) != 0)
        {
            descrip = "free";
            oref = 0;
        }
        else
        {
            ++slotCount;
            if (oref)
            {
                ++objectCount;

                struct Param
                {
                    LPCUTF8 descrip;
                    Object *oref;
                    char *buffer2;
                    UINT cch2;
                    BOOL isString;
                } param;
                param.descrip = descrip;
                param.oref = oref;
                param.buffer2 = buffer2;
                param.cch2 = COUNTOF(buffer2);
                param.isString = isString;

                PAL_TRY(Param *, pParam, &param)
                {
                    pParam->descrip = pParam->oref->GetMethodTable()->GetDebugClassName();
                    if (strlen(pParam->descrip) == 0)
                        pParam->descrip = "<INVALID>";
                    else if (pParam->oref->GetMethodTable() == g_pStringClass)
                    {
                        sprintf_s(pParam->buffer2, pParam->cch2, "%s (%S)", pParam->descrip, ObjectToSTRINGREF((StringObject*)pParam->oref)->GetBuffer());
                        pParam->descrip = pParam->buffer2;
                        pParam->isString = TRUE;
                    }
                }
                PAL_EXCEPT(EXCEPTION_EXECUTE_HANDLER) {
                    param.descrip = "<INVALID>";
                }
                PAL_ENDTRY

                descrip = param.descrip;
                isString = param.isString;
            }
            ADIndex idx;
            if (oref)
                idx = pEntry->m_Object->GetHeader()->GetRawAppDomainIndex();
            if (! idx.m_dwIndex && pEntry->m_SyncBlock)
                idx = pEntry->m_SyncBlock->GetAppDomainIndex();
            if (idx.m_dwIndex && ! SystemDomain::System()->TestGetAppDomainAtIndex(idx))
            {
                sprintf_s(buffer, COUNTOF(buffer), "** unloaded (%3.3x) %s", idx.m_dwIndex, descrip);
                descrip = buffer;
            }
            else
            {
                sprintf_s(buffer, COUNTOF(buffer), "(AD %3.3x) %s", idx.m_dwIndex, descrip);
                descrip = buffer;
            }
        }
        if (dumpSBStyle < 2)
            LogSpewAlways("[%4.4d]: %8.8x %s\n", nb, oref, descrip);
        else if (dumpSBStyle == 2 && ! isString)
            LogSpewAlways("[%4.4d]: %s\n", nb, descrip);
    }
    LogSpewAlways("Done dumping SyncBlockCache used slots: %d, objects: %d\n", slotCount, objectCount);
}
#endif

// ***************************************************************************
//
//              ObjHeader class implementation
//
// ***************************************************************************

#if defined(ENABLE_CONTRACTS_IMPL)
// The LOCK_TAKEN/RELEASED macros need a "pointer" to the lock object to do
// comparisons between takes & releases (and to provide debugging info to the
// developer).  Ask the syncblock for its lock contract pointer, if the
// syncblock exists.  Otherwise, use the MethodTable* from the Object.  That's not great,
// as it's not unique, so we might miss unbalanced lock takes/releases from
// different objects of the same type.  However, our hands are tied, and we can't
// do much better.
void * ObjHeader::GetPtrForLockContract()
{
    if (GetHeaderSyncBlockIndex() == 0)
    {
        return (void *) GetBaseObject()->GetMethodTable();
    }

    return PassiveGetSyncBlock()->GetPtrForLockContract();
}
#endif // defined(ENABLE_CONTRACTS_IMPL)

// this enters the monitor of an object
void ObjHeader::EnterObjMonitor()
{
    WRAPPER_NO_CONTRACT;
    GetSyncBlock()->EnterMonitor();
}

// Non-blocking version of above
BOOL ObjHeader::TryEnterObjMonitor(INT32 timeOut)
{
    WRAPPER_NO_CONTRACT;
    return GetSyncBlock()->TryEnterMonitor(timeOut);
}

AwareLock::EnterHelperResult ObjHeader::EnterObjMonitorHelperSpin(Thread* pCurThread)
{
    CONTRACTL{
        SO_TOLERANT;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    } CONTRACTL_END;

    // Note: EnterObjMonitorHelper must be called before this function (see below)

    if (g_SystemInfo.dwNumberOfProcessors == 1)
    {
        return AwareLock::EnterHelperResult_Contention;
    }

    YieldProcessorNormalizationInfo normalizationInfo;
    const DWORD spinCount = g_SpinConstants.dwMonitorSpinCount;
    for (DWORD spinIteration = 0; spinIteration < spinCount; ++spinIteration)
    {
        AwareLock::SpinWait(normalizationInfo, spinIteration);

        LONG oldValue = m_SyncBlockValue.LoadWithoutBarrier();

        // Since spinning has begun, chances are good that the monitor has already switched to AwareLock mode, so check for that
        // case first
        if (oldValue & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
        {
            // If we have a hash code already, we need to create a sync block
            if (oldValue & BIT_SBLK_IS_HASHCODE)
            {
                return AwareLock::EnterHelperResult_UseSlowPath;
            }

            SyncBlock *syncBlock = g_pSyncTable[oldValue & MASK_SYNCBLOCKINDEX].m_SyncBlock;
            _ASSERTE(syncBlock != NULL);
            AwareLock *awareLock = &syncBlock->m_Monitor;

            AwareLock::EnterHelperResult result = awareLock->TryEnterBeforeSpinLoopHelper(pCurThread);
            if (result != AwareLock::EnterHelperResult_Contention)
            {
                return result;
            }

            ++spinIteration;
            if (spinIteration < spinCount)
            {
                while (true)
                {
                    AwareLock::SpinWait(normalizationInfo, spinIteration);

                    ++spinIteration;
                    if (spinIteration >= spinCount)
                    {
                        // The last lock attempt for this spin will be done after the loop
                        break;
                    }

                    result = awareLock->TryEnterInsideSpinLoopHelper(pCurThread);
                    if (result == AwareLock::EnterHelperResult_Entered)
                    {
                        return AwareLock::EnterHelperResult_Entered;
                    }
                    if (result == AwareLock::EnterHelperResult_UseSlowPath)
                    {
                        break;
                    }
                }
            }

            if (awareLock->TryEnterAfterSpinLoopHelper(pCurThread))
            {
                return AwareLock::EnterHelperResult_Entered;
            }
            break;
        }

        DWORD tid = pCurThread->GetThreadId();
        if ((oldValue & (BIT_SBLK_SPIN_LOCK +
            SBLK_MASK_LOCK_THREADID +
            SBLK_MASK_LOCK_RECLEVEL)) == 0)
        {
            if (tid > SBLK_MASK_LOCK_THREADID)
            {
                return AwareLock::EnterHelperResult_UseSlowPath;
            }

            LONG newValue = oldValue | tid;
            if (InterlockedCompareExchangeAcquire((LONG*)&m_SyncBlockValue, newValue, oldValue) == oldValue)
            {
                pCurThread->IncLockCount();
                return AwareLock::EnterHelperResult_Entered;
            }

            continue;
        }

        // EnterObjMonitorHelper handles the thin lock recursion case. If it's not that case, it won't become that case. If
        // EnterObjMonitorHelper failed to increment the recursion level, it will go down the slow path and won't come here. So,
        // no need to check the recursion case here.
        _ASSERTE(
            // The header is transitioning - treat this as if the lock was taken
            oldValue & BIT_SBLK_SPIN_LOCK ||
            // Here we know we have the "thin lock" layout, but the lock is not free.
            // It can't be the recursion case though, because the call to EnterObjMonitorHelper prior to this would have taken
            // the slow path in the recursive case.
            tid != (DWORD)(oldValue & SBLK_MASK_LOCK_THREADID));
    }

    return AwareLock::EnterHelperResult_Contention;
}

BOOL ObjHeader::LeaveObjMonitor()
{
    CONTRACTL
    {
        NOTHROW;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    //this function switch to preemp mode so we need to protect the object in some path
    OBJECTREF thisObj = ObjectToOBJECTREF (GetBaseObject ());

    DWORD dwSwitchCount = 0;

    for (;;)
    {
        AwareLock::LeaveHelperAction action = thisObj->GetHeader ()->LeaveObjMonitorHelper(GetThread());

        switch(action)
        {
        case AwareLock::LeaveHelperAction_None:
            // We are done
            return TRUE;
        case AwareLock::LeaveHelperAction_Signal:
            {
                // Signal the event
                SyncBlock *psb = thisObj->GetHeader ()->PassiveGetSyncBlock();
                if (psb != NULL)
                    psb->QuickGetMonitor()->Signal();
            }
            return TRUE;
        case AwareLock::LeaveHelperAction_Yield:
            YieldProcessor();
            continue;
        case AwareLock::LeaveHelperAction_Contention:
            // Some thread is updating the syncblock value.
            {
                //protect the object before switching mode
                GCPROTECT_BEGIN (thisObj);
                GCX_PREEMP();
                __SwitchToThread(0, ++dwSwitchCount);
                GCPROTECT_END ();
            }
            continue;
        default:
            // Must be an error otherwise - ignore it
            _ASSERTE(action == AwareLock::LeaveHelperAction_Error);
            return FALSE;
        }
    }
}

// The only difference between LeaveObjMonitor and LeaveObjMonitorAtException is switch 
// to preemptive mode around __SwitchToThread
BOOL ObjHeader::LeaveObjMonitorAtException()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    DWORD dwSwitchCount = 0;

    for (;;)
    {
        AwareLock::LeaveHelperAction action = LeaveObjMonitorHelper(GetThread());

        switch(action)
        {
        case AwareLock::LeaveHelperAction_None:
            // We are done
            return TRUE;
        case AwareLock::LeaveHelperAction_Signal:
            {
                // Signal the event
                SyncBlock *psb = PassiveGetSyncBlock();
                if (psb != NULL)
                    psb->QuickGetMonitor()->Signal();
            }
            return TRUE;
        case AwareLock::LeaveHelperAction_Yield:
            YieldProcessor();
            continue;
        case AwareLock::LeaveHelperAction_Contention:
            // Some thread is updating the syncblock value.
            //
            // We never toggle GC mode while holding the spinlock (BeginNoTriggerGC/EndNoTriggerGC 
            // in EnterSpinLock/ReleaseSpinLock ensures it). Thus we do not need to switch to preemptive
            // while waiting on the spinlock.
            //
            {
                __SwitchToThread(0, ++dwSwitchCount);
            }
            continue;
        default:
            // Must be an error otherwise - ignore it
            _ASSERTE(action == AwareLock::LeaveHelperAction_Error);
            return FALSE;
        }
    }
}

#endif //!DACCESS_COMPILE

// Returns TRUE if the lock is owned and FALSE otherwise
// threadId is set to the ID (Thread::GetThreadId()) of the thread which owns the lock
// acquisitionCount is set to the number of times the lock needs to be released before
// it is unowned
BOOL ObjHeader::GetThreadOwningMonitorLock(DWORD *pThreadId, DWORD *pAcquisitionCount)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
#ifndef DACCESS_COMPILE
        if (!IsGCSpecialThread ()) {MODE_COOPERATIVE;} else {MODE_ANY;}
#endif
    }
    CONTRACTL_END;
    SUPPORTS_DAC;


    DWORD bits = GetBits();

    if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
    {
        if (bits & BIT_SBLK_IS_HASHCODE)
        {
            //
            // This thread does not own the lock.
            //
            *pThreadId = 0;
            *pAcquisitionCount = 0;
            return FALSE;
        }
        else
        {
            //
            // We have a syncblk
            //
            DWORD index = bits & MASK_SYNCBLOCKINDEX;
            SyncBlock* psb = g_pSyncTable[(int)index].m_SyncBlock;

            _ASSERTE(psb->GetMonitor() != NULL);
            Thread* pThread = psb->GetMonitor()->GetHoldingThread();
            if(pThread == NULL)
            {
                *pThreadId = 0;
                *pAcquisitionCount = 0;
                return FALSE;
            }
            else
            {
                *pThreadId = pThread->GetThreadId();
                *pAcquisitionCount = psb->GetMonitor()->GetRecursionLevel();
                return TRUE;
            }
        }
    }
    else
    {
        //
        // We have a thinlock
        //

        DWORD lockThreadId, recursionLevel;
        lockThreadId = bits & SBLK_MASK_LOCK_THREADID;
        recursionLevel = (bits & SBLK_MASK_LOCK_RECLEVEL) >> SBLK_RECLEVEL_SHIFT;
        //if thread ID is 0, recursionLevel got to be zero
        //but thread ID doesn't have to be valid because the lock could be orphanend
        _ASSERTE (lockThreadId != 0 || recursionLevel == 0 );

        *pThreadId = lockThreadId;
        if(lockThreadId != 0)
        {
            // in the header, the recursionLevel of 0 means the lock is owned once
            // (this differs from m_Recursion in the AwareLock)
            *pAcquisitionCount = recursionLevel + 1;
            return TRUE;
        }
        else
        {
            *pAcquisitionCount = 0;
            return FALSE;
        }
    }
}

#ifndef DACCESS_COMPILE

#ifdef MP_LOCKS
DEBUG_NOINLINE void ObjHeader::EnterSpinLock()
{
    // NOTE: This function cannot have a dynamic contract.  If it does, the contract's
    // destructor will reset the CLR debug state to what it was before entering the
    // function, which will undo the BeginNoTriggerGC() call below.
    SCAN_SCOPE_BEGIN;
    STATIC_CONTRACT_GC_NOTRIGGER;

#ifdef _DEBUG
    int i = 0;
#endif

    DWORD dwSwitchCount = 0;

    while (TRUE)
    {
#ifdef _DEBUG
#ifdef _WIN64
        // Give 64bit more time because there isn't a remoting fast path now, and we've hit this assert
        // needlessly in CLRSTRESS. 
        if (i++ > 30000)
#else            
        if (i++ > 10000)
#endif // _WIN64            
            _ASSERTE(!"ObjHeader::EnterLock timed out");
#endif
        // get the value so that it doesn't get changed under us.
        LONG curValue = m_SyncBlockValue.LoadWithoutBarrier();

        // check if lock taken
        if (! (curValue & BIT_SBLK_SPIN_LOCK))
        {
            // try to take the lock
            LONG newValue = curValue | BIT_SBLK_SPIN_LOCK;
            LONG result = FastInterlockCompareExchange((LONG*)&m_SyncBlockValue, newValue, curValue);
            if (result == curValue)
                break;
        }
        if  (g_SystemInfo.dwNumberOfProcessors > 1)
        {
            for (int spinCount = 0; spinCount < BIT_SBLK_SPIN_COUNT; spinCount++)
            {
                if  (! (m_SyncBlockValue & BIT_SBLK_SPIN_LOCK))
                    break;
                YieldProcessor();               // indicate to the processor that we are spining
            }
            if  (m_SyncBlockValue & BIT_SBLK_SPIN_LOCK)
                __SwitchToThread(0, ++dwSwitchCount);
        }
        else
            __SwitchToThread(0, ++dwSwitchCount);
    }

    INCONTRACT(Thread* pThread = GetThread());
    INCONTRACT(if (pThread != NULL) pThread->BeginNoTriggerGC(__FILE__, __LINE__));
}
#else
DEBUG_NOINLINE void ObjHeader::EnterSpinLock()
{
    SCAN_SCOPE_BEGIN;
    STATIC_CONTRACT_GC_NOTRIGGER;

#ifdef _DEBUG
    int i = 0;
#endif

    DWORD dwSwitchCount = 0;

    while (TRUE)
    {
#ifdef _DEBUG
        if (i++ > 10000)
            _ASSERTE(!"ObjHeader::EnterLock timed out");
#endif
        // get the value so that it doesn't get changed under us.
        LONG curValue = m_SyncBlockValue.LoadWithoutBarrier();

        // check if lock taken
        if (! (curValue & BIT_SBLK_SPIN_LOCK))
        {
            // try to take the lock
            LONG newValue = curValue | BIT_SBLK_SPIN_LOCK;
            LONG result = FastInterlockCompareExchange((LONG*)&m_SyncBlockValue, newValue, curValue);
            if (result == curValue)
                break;
        }
        __SwitchToThread(0, ++dwSwitchCount);
    }

    INCONTRACT(Thread* pThread = GetThread());
    INCONTRACT(if (pThread != NULL) pThread->BeginNoTriggerGC(__FILE__, __LINE__));
}
#endif //MP_LOCKS

DEBUG_NOINLINE void ObjHeader::ReleaseSpinLock()
{
    SCAN_SCOPE_END;
    LIMITED_METHOD_CONTRACT;

    INCONTRACT(Thread* pThread = GetThread());
    INCONTRACT(if (pThread != NULL) pThread->EndNoTriggerGC());

    FastInterlockAnd(&m_SyncBlockValue, ~BIT_SBLK_SPIN_LOCK);
}

#endif //!DACCESS_COMPILE

ADIndex ObjHeader::GetRawAppDomainIndex()
{
    LIMITED_METHOD_CONTRACT;
    SUPPORTS_DAC;

    // pull the value out before checking it to avoid race condition
    DWORD value = m_SyncBlockValue.LoadWithoutBarrier();
    if ((value & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0)
        return ADIndex((value >> SBLK_APPDOMAIN_SHIFT) & SBLK_MASK_APPDOMAININDEX);
    return ADIndex(0);
}

ADIndex ObjHeader::GetAppDomainIndex()
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_SO_TOLERANT;
    STATIC_CONTRACT_SUPPORTS_DAC;

    ADIndex indx = GetRawAppDomainIndex();
    if (indx.m_dwIndex)
        return indx;
    SyncBlock* syncBlock = PassiveGetSyncBlock();
    if (! syncBlock)
        return ADIndex(0);

    return syncBlock->GetAppDomainIndex();
}

#ifndef DACCESS_COMPILE

void ObjHeader::SetAppDomainIndex(ADIndex indx)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    //
    // This should only be called during the header initialization,
    // so don't worry about races.
    //

    BOOL done = FALSE;

#ifdef _DEBUG
    static int forceSB = -1;

    if (forceSB == -1)
        forceSB = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_ADForceSB);

    if (forceSB)
        // force a synblock so we get one for every object.
        GetSyncBlock();
#endif

    if (GetHeaderSyncBlockIndex() == 0 && indx.m_dwIndex < SBLK_MASK_APPDOMAININDEX)
    {
        ENTER_SPIN_LOCK(this);
        //Try one more time
        if (GetHeaderSyncBlockIndex() == 0)
        {
            _ASSERTE(GetRawAppDomainIndex().m_dwIndex == 0);
            // can store it in the object header
            FastInterlockOr(&m_SyncBlockValue, indx.m_dwIndex << SBLK_APPDOMAIN_SHIFT);
            done = TRUE;
        }
        LEAVE_SPIN_LOCK(this);
    }

    if (!done)
    {
        // must create a syncblock entry and store the appdomain indx there
        SyncBlock *psb = GetSyncBlock();
        _ASSERTE(psb);
        psb->SetAppDomainIndex(indx);
    }
}

void ObjHeader::ResetAppDomainIndex(ADIndex indx)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    //
    // This should only be called during the header initialization,
    // so don't worry about races.
    //

    BOOL done = FALSE;

    if (GetHeaderSyncBlockIndex() == 0 && indx.m_dwIndex < SBLK_MASK_APPDOMAININDEX)
    {
        ENTER_SPIN_LOCK(this);
        //Try one more time
        if (GetHeaderSyncBlockIndex() == 0)
        {
            // can store it in the object header
            while (TRUE)
            {
                DWORD oldValue = m_SyncBlockValue.LoadWithoutBarrier();
                DWORD newValue = (oldValue & (~(SBLK_MASK_APPDOMAININDEX << SBLK_APPDOMAIN_SHIFT))) |
                    (indx.m_dwIndex << SBLK_APPDOMAIN_SHIFT);
                if (FastInterlockCompareExchange((LONG*)&m_SyncBlockValue,
                                                 newValue,
                                                 oldValue) == (LONG)oldValue)
                {
                    break;
                }
            }
            done = TRUE;
        }
        LEAVE_SPIN_LOCK(this);
    }

    if (!done)
    {
        // must create a syncblock entry and store the appdomain indx there
        SyncBlock *psb = GetSyncBlock();
        _ASSERTE(psb);
        psb->SetAppDomainIndex(indx);
    }
}

void ObjHeader::ResetAppDomainIndexNoFailure(ADIndex indx)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(indx.m_dwIndex < SBLK_MASK_APPDOMAININDEX);
    }
    CONTRACTL_END;

    ENTER_SPIN_LOCK(this);
    if (GetHeaderSyncBlockIndex() == 0)
    {
        // can store it in the object header
        while (TRUE)
        {
            DWORD oldValue = m_SyncBlockValue.LoadWithoutBarrier();
            DWORD newValue = (oldValue & (~(SBLK_MASK_APPDOMAININDEX << SBLK_APPDOMAIN_SHIFT))) |
                (indx.m_dwIndex << SBLK_APPDOMAIN_SHIFT);
            if (FastInterlockCompareExchange((LONG*)&m_SyncBlockValue,
                                             newValue,
                                             oldValue) == (LONG)oldValue)
            {
                break;
            }
        }
    }
    else
    {
        SyncBlock *psb = PassiveGetSyncBlock();
        _ASSERTE(psb);
        psb->SetAppDomainIndex(indx);
    }
    LEAVE_SPIN_LOCK(this);
}

DWORD ObjHeader::GetSyncBlockIndex()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    DWORD   indx;

    if ((indx = GetHeaderSyncBlockIndex()) == 0)
    {
        BOOL fMustCreateSyncBlock = FALSE;

        if (GetAppDomainIndex().m_dwIndex)
        {
            // if have an appdomain set then must create a sync block to store it
            fMustCreateSyncBlock = TRUE;
        }
        else
        {
            //Need to get it from the cache
            SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());

            //Try one more time
            if (GetHeaderSyncBlockIndex() == 0)
            {
                ENTER_SPIN_LOCK(this);
                // Now the header will be stable - check whether hashcode, appdomain index or lock information is stored in it.
                DWORD bits = GetBits();
                if (((bits & (BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE)) == (BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | BIT_SBLK_IS_HASHCODE)) ||
                    ((bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0 &&
                     (bits & ((SBLK_MASK_APPDOMAININDEX<<SBLK_APPDOMAIN_SHIFT)|SBLK_MASK_LOCK_RECLEVEL|SBLK_MASK_LOCK_THREADID)) != 0))
                {
                    // Need a sync block to store this info
                    fMustCreateSyncBlock = TRUE;
                }
                else
                {
                    SetIndex(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | SyncBlockCache::GetSyncBlockCache()->NewSyncBlockSlot(GetBaseObject()));
                }
                LEAVE_SPIN_LOCK(this);
            }
            // SyncBlockCache::LockHolder goes out of scope here
        }

        if (fMustCreateSyncBlock)
            GetSyncBlock();

        if ((indx = GetHeaderSyncBlockIndex()) == 0)
            COMPlusThrowOM();
    }

    return indx;
}

#if defined (VERIFY_HEAP)

BOOL ObjHeader::Validate (BOOL bVerifySyncBlkIndex)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_SO_TOLERANT;
    STATIC_CONTRACT_MODE_COOPERATIVE;
    
    DWORD bits = GetBits ();
    Object * obj = GetBaseObject ();
    BOOL bVerifyMore = g_pConfig->GetHeapVerifyLevel() & EEConfig::HEAPVERIFY_SYNCBLK;
    //the highest 2 bits have reloaded meaning
    //for string objects:
    //         BIT_SBLK_STRING_HAS_NO_HIGH_CHARS   0x80000000
    //         BIT_SBLK_STRING_HIGH_CHARS_KNOWN    0x40000000
    //         BIT_SBLK_STRING_HAS_SPECIAL_SORT    0xC0000000
    //for other objects:
    //         BIT_SBLK_AGILE_IN_PROGRESS          0x80000000
    //         BIT_SBLK_FINALIZER_RUN              0x40000000
    if (bits & BIT_SBLK_STRING_HIGH_CHAR_MASK)
    {
        if (obj->GetGCSafeMethodTable () == g_pStringClass)
        {
            if (bVerifyMore)
            {
                ASSERT_AND_CHECK (((StringObject *)obj)->ValidateHighChars());
            }
        }
        else
        {
            //BIT_SBLK_AGILE_IN_PROGRESS is set only in debug build
            ASSERT_AND_CHECK (!(bits & BIT_SBLK_AGILE_IN_PROGRESS));
            if (bits & BIT_SBLK_FINALIZER_RUN)
            {
                ASSERT_AND_CHECK (obj->GetGCSafeMethodTable ()->HasFinalizer ());
            }
        }
    }

    //BIT_SBLK_GC_RESERVE (0x20000000) is only set during GC. But for frozen object, we don't clean the bit
    if (bits & BIT_SBLK_GC_RESERVE)
    {
        if (!GCHeapUtilities::IsGCInProgress () && !GCHeapUtilities::GetGCHeap()->IsConcurrentGCInProgress ())
        {
#ifdef FEATURE_BASICFREEZE
            ASSERT_AND_CHECK (GCHeapUtilities::GetGCHeap()->IsInFrozenSegment(obj));
#else //FEATURE_BASICFREEZE
            _ASSERTE(!"Reserve bit not cleared");
            return FALSE;
#endif //FEATURE_BASICFREEZE
        }
    }

    //Don't know how to verify BIT_SBLK_SPIN_LOCK (0x10000000)
    
    //BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX (0x08000000)
    if (bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX)
    {
        //if BIT_SBLK_IS_HASHCODE (0x04000000) is not set, 
        //rest of the DWORD is SyncBlk Index
        if (!(bits & BIT_SBLK_IS_HASHCODE))
        {
            if (bVerifySyncBlkIndex  && GCHeapUtilities::GetGCHeap()->RuntimeStructuresValid ())
            {
                DWORD sbIndex = bits & MASK_SYNCBLOCKINDEX;
                ASSERT_AND_CHECK(SyncTableEntry::GetSyncTableEntry()[sbIndex].m_Object == obj);             
            }
        }
        else
        {
            //  rest of the DWORD is a hash code and we don't have much to validate it
        }
    }
    else
    {
        //if BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX is clear, rest of DWORD is thin lock thread ID, 
        //thin lock recursion level and appdomain index
        DWORD lockThreadId = bits & SBLK_MASK_LOCK_THREADID;
        DWORD recursionLevel = (bits & SBLK_MASK_LOCK_RECLEVEL) >> SBLK_RECLEVEL_SHIFT;
        //if thread ID is 0, recursionLeve got to be zero
        //but thread ID doesn't have to be valid because the lock could be orphanend
        ASSERT_AND_CHECK (lockThreadId != 0 || recursionLevel == 0 );     

        DWORD adIndex  = (bits >> SBLK_APPDOMAIN_SHIFT) & SBLK_MASK_APPDOMAININDEX;
        if (adIndex!= 0)
        {
#ifndef _DEBUG            
            //in non debug build, only objects of domain neutral type have appdomain index in header
            ASSERT_AND_CHECK (obj->GetGCSafeMethodTable()->IsDomainNeutral());
#endif //!_DEBUG
            //todo: validate the AD index. 
            //The trick here is agile objects could have a invalid AD index. Ideally we should call 
            //Object::GetAppDomain to do all the agile validation but it has side effects like mark the object to 
            //be agile and it only does the check if g_pConfig->AppDomainLeaks() is on
        }
    }
    
    return TRUE;
}

#endif //VERIFY_HEAP

// This holder takes care of the SyncBlock memory cleanup if an OOM occurs inside a call to NewSyncBlockSlot.
//
// Warning: Assumes you already own the cache lock.
//          Assumes nothing allocated inside the SyncBlock (only releases the memory, does not destruct.)
//
// This holder really just meets GetSyncBlock()'s special needs. It's not a general purpose holder.


// Do not inline this call. (fyuan)
// SyncBlockMemoryHolder is normally a check for empty pointer and return. Inlining VoidDeleteSyncBlockMemory adds expensive exception handling.
void VoidDeleteSyncBlockMemory(SyncBlock* psb)
{
    LIMITED_METHOD_CONTRACT;
    SyncBlockCache::GetSyncBlockCache()->DeleteSyncBlockMemory(psb);
}

typedef Wrapper<SyncBlock*, DoNothing<SyncBlock*>, VoidDeleteSyncBlockMemory, NULL> SyncBlockMemoryHolder;


// get the sync block for an existing object
SyncBlock *ObjHeader::GetSyncBlock()
{
    CONTRACT(SyncBlock *)
    {
        INSTANCE_CHECK;
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
        POSTCONDITION(CheckPointer(RETVAL));
    }
    CONTRACT_END;

    PTR_SyncBlock syncBlock = GetBaseObject()->PassiveGetSyncBlock();
    DWORD      indx = 0;
    BOOL indexHeld = FALSE;

    if (syncBlock)
    {
#ifdef _DEBUG 
        // Has our backpointer been correctly updated through every GC?
        PTR_SyncTableEntry pEntries(SyncTableEntry::GetSyncTableEntry());
        _ASSERTE(pEntries[GetHeaderSyncBlockIndex()].m_Object == GetBaseObject());
#endif // _DEBUG
        RETURN syncBlock;
    }

    //Need to get it from the cache
    {
        SyncBlockCache::LockHolder lh(SyncBlockCache::GetSyncBlockCache());

        //Try one more time
        syncBlock = GetBaseObject()->PassiveGetSyncBlock();
        if (syncBlock)
            RETURN syncBlock;


        SyncBlockMemoryHolder syncBlockMemoryHolder(SyncBlockCache::GetSyncBlockCache()->GetNextFreeSyncBlock());
        syncBlock = syncBlockMemoryHolder;

        if ((indx = GetHeaderSyncBlockIndex()) == 0)
        {
            indx = SyncBlockCache::GetSyncBlockCache()->NewSyncBlockSlot(GetBaseObject());
        }
        else
        {
            //We already have an index, we need to hold the syncblock
            indexHeld = TRUE;
        }

        {
            //! NewSyncBlockSlot has side-effects that we don't have backout for - thus, that must be the last
            //! failable operation called.
            CANNOTTHROWCOMPLUSEXCEPTION();
            FAULT_FORBID();


            syncBlockMemoryHolder.SuppressRelease();

            new (syncBlock) SyncBlock(indx);

            {
                // after this point, nobody can update the index in the header to give an AD index
                ENTER_SPIN_LOCK(this);

                {
                    // If there's an appdomain index stored in the header, transfer it to the syncblock

                    ADIndex dwAppDomainIndex = GetAppDomainIndex();
                    if (dwAppDomainIndex.m_dwIndex)
                        syncBlock->SetAppDomainIndex(dwAppDomainIndex);

                    // If the thin lock in the header is in use, transfer the information to the syncblock
                    DWORD bits = GetBits();
                    if ((bits & BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX) == 0)
                    {
                        DWORD lockThreadId = bits & SBLK_MASK_LOCK_THREADID;
                        DWORD recursionLevel = (bits & SBLK_MASK_LOCK_RECLEVEL) >> SBLK_RECLEVEL_SHIFT;
                        if (lockThreadId != 0 || recursionLevel != 0)
                        {
                            // recursionLevel can't be non-zero if thread id is 0
                            _ASSERTE(lockThreadId != 0);

                            Thread *pThread = g_pThinLockThreadIdDispenser->IdToThreadWithValidation(lockThreadId);

                            if (pThread == NULL)
                            {
                                // The lock is orphaned.
                                pThread = (Thread*) -1;
                            }
                            syncBlock->InitState(recursionLevel + 1, pThread);
                        }
                    }
                    else if ((bits & BIT_SBLK_IS_HASHCODE) != 0)
                    {
                        DWORD hashCode = bits & MASK_HASHCODE;

                        syncBlock->SetHashCode(hashCode);
                    }
                }

                SyncTableEntry::GetSyncTableEntry() [indx].m_SyncBlock = syncBlock;

                // in order to avoid a race where some thread tries to get the AD index and we've already nuked it,
                // make sure the syncblock etc is all setup with the AD index prior to replacing the index
                // in the header
                if (GetHeaderSyncBlockIndex() == 0)
                {
                    // We have transferred the AppDomain into the syncblock above.
                    SetIndex(BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX | indx);
                }

                //If we had already an index, hold the syncblock
                //for the lifetime of the object.
                if (indexHeld)
                    syncBlock->SetPrecious();

                LEAVE_SPIN_LOCK(this);
            }
            // SyncBlockCache::LockHolder goes out of scope here
        }
    }

    RETURN syncBlock;
}

BOOL ObjHeader::Wait(INT32 timeOut, BOOL exitContext)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    //  The following code may cause GC, so we must fetch the sync block from
    //  the object now in case it moves.
    SyncBlock *pSB = GetBaseObject()->GetSyncBlock();

    // GetSyncBlock throws on failure
    _ASSERTE(pSB != NULL);

    // make sure we own the crst
    if (!pSB->DoesCurrentThreadOwnMonitor())
        COMPlusThrow(kSynchronizationLockException);

#ifdef _DEBUG
    Thread *pThread = GetThread();
    DWORD curLockCount = pThread->m_dwLockCount;
#endif

    BOOL result = pSB->Wait(timeOut,exitContext);

    _ASSERTE (curLockCount == pThread->m_dwLockCount);

    return result;
}

void ObjHeader::Pulse()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    //  The following code may cause GC, so we must fetch the sync block from
    //  the object now in case it moves.
    SyncBlock *pSB = GetBaseObject()->GetSyncBlock();

    // GetSyncBlock throws on failure
    _ASSERTE(pSB != NULL);

    // make sure we own the crst
    if (!pSB->DoesCurrentThreadOwnMonitor())
        COMPlusThrow(kSynchronizationLockException);

    pSB->Pulse();
}

void ObjHeader::PulseAll()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    //  The following code may cause GC, so we must fetch the sync block from
    //  the object now in case it moves.
    SyncBlock *pSB = GetBaseObject()->GetSyncBlock();

    // GetSyncBlock throws on failure
    _ASSERTE(pSB != NULL);

    // make sure we own the crst
    if (!pSB->DoesCurrentThreadOwnMonitor())
        COMPlusThrow(kSynchronizationLockException);

    pSB->PulseAll();
}


// ***************************************************************************
//
//              AwareLock class implementation (GC-aware locking)
//
// ***************************************************************************

void AwareLock::AllocLockSemEvent()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    // Before we switch from cooperative, ensure that this syncblock won't disappear
    // under us.  For something as expensive as an event, do it permanently rather
    // than transiently.
    SetPrecious();

    GCX_PREEMP();

    // No need to take a lock - CLREvent::CreateMonitorEvent is thread safe
    m_SemEvent.CreateMonitorEvent((SIZE_T)this);
}

void AwareLock::Enter()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    Thread *pCurThread = GetThread();
    LockState state = m_lockState.VolatileLoadWithoutBarrier();
    if (!state.IsLocked() || m_HoldingThread != pCurThread)
    {
        if (m_lockState.InterlockedTryLock_Or_RegisterWaiter(this, state))
        {
            // We get here if we successfully acquired the mutex.
            m_HoldingThread = pCurThread;
            m_Recursion = 1;
            pCurThread->IncLockCount();

#if defined(_DEBUG) && defined(TRACK_SYNC)
            // The best place to grab this is from the ECall frame
            Frame   *pFrame = pCurThread->GetFrame();
            int      caller = (pFrame && pFrame != FRAME_TOP
                                ? (int)pFrame->GetReturnAddress()
                                : -1);
            pCurThread->m_pTrackSync->EnterSync(caller, this);
#endif
            return;
        }

        // Lock was not acquired and the waiter was registered

        // Didn't manage to get the mutex, must wait.
        // The precondition for EnterEpilog is that the count of waiters be bumped
        // to account for this thread, which was done above.
        EnterEpilog(pCurThread);
        return;
    }

    // Got the mutex via recursive locking on the same thread.
    _ASSERTE(m_Recursion >= 1);
    m_Recursion++;

#if defined(_DEBUG) && defined(TRACK_SYNC)
    // The best place to grab this is from the ECall frame
    Frame   *pFrame = pCurThread->GetFrame();
    int      caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1);
    pCurThread->m_pTrackSync->EnterSync(caller, this);
#endif
}

BOOL AwareLock::TryEnter(INT32 timeOut)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        if (timeOut == 0) {MODE_ANY;} else {MODE_COOPERATIVE;}
        INJECT_FAULT(COMPlusThrowOM(););
    }
    CONTRACTL_END;

    Thread  *pCurThread = GetThread();
    TESTHOOKCALL(AppDomainCanBeUnloaded(pCurThread->GetDomain()->GetId().m_dwId, FALSE));

    if (pCurThread->IsAbortRequested())
    {
        pCurThread->HandleThreadAbort();
    }

    LockState state = m_lockState.VolatileLoadWithoutBarrier();
    if (!state.IsLocked() || m_HoldingThread != pCurThread)
    {
        if (timeOut == 0
                ? m_lockState.InterlockedTryLock(state)
                : m_lockState.InterlockedTryLock_Or_RegisterWaiter(this, state))
        {
            // We get here if we successfully acquired the mutex.
            m_HoldingThread = pCurThread;
            m_Recursion = 1;
            pCurThread->IncLockCount();

#if defined(_DEBUG) && defined(TRACK_SYNC)
            // The best place to grab this is from the ECall frame
            Frame   *pFrame = pCurThread->GetFrame();
            int      caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1);
            pCurThread->m_pTrackSync->EnterSync(caller, this);
#endif
            return true;
        }

        // Lock was not acquired and the waiter was registered if the timeout is nonzero

        // Didn't manage to get the mutex, return failure if no timeout, else wait
        // for at most timeout milliseconds for the mutex.
        if (timeOut == 0)
        {
            return false;
        }

        // The precondition for EnterEpilog is that the count of waiters be bumped
        // to account for this thread, which was done above
        return EnterEpilog(pCurThread, timeOut);
    }

    // Got the mutex via recursive locking on the same thread.
    _ASSERTE(m_Recursion >= 1);
    m_Recursion++;
#if defined(_DEBUG) && defined(TRACK_SYNC)
    // The best place to grab this is from the ECall frame
    Frame   *pFrame = pCurThread->GetFrame();
    int      caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1);
    pCurThread->m_pTrackSync->EnterSync(caller, this);
#endif
    return true;
}

BOOL AwareLock::EnterEpilog(Thread* pCurThread, INT32 timeOut)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_MODE_COOPERATIVE;
    STATIC_CONTRACT_GC_TRIGGERS;

    // While we are in this frame the thread is considered blocked on the
    // critical section of the monitor lock according to the debugger
    DebugBlockingItem blockingMonitorInfo;
    blockingMonitorInfo.dwTimeout = timeOut;
    blockingMonitorInfo.pMonitor = this;
    blockingMonitorInfo.pAppDomain = SystemDomain::GetCurrentDomain();
    blockingMonitorInfo.type = DebugBlock_MonitorCriticalSection;
    DebugBlockingItemHolder holder(pCurThread, &blockingMonitorInfo);

    // We need a separate helper because it uses SEH and the holder has a
    // destructor
    return EnterEpilogHelper(pCurThread, timeOut);
}

#ifdef _DEBUG
#define _LOGCONTENTION
#endif // _DEBUG

#ifdef  _LOGCONTENTION
inline void LogContention()
{
    WRAPPER_NO_CONTRACT;
#ifdef LOGGING
    if (LoggingOn(LF_SYNC, LL_INFO100))
    {
        LogSpewAlways("Contention: Stack Trace Begin\n");
        void LogStackTrace();
        LogStackTrace();
        LogSpewAlways("Contention: Stack Trace End\n");
    }
#endif
}
#else
#define LogContention()
#endif

BOOL AwareLock::EnterEpilogHelper(Thread* pCurThread, INT32 timeOut)
{
    STATIC_CONTRACT_THROWS;
    STATIC_CONTRACT_MODE_COOPERATIVE;
    STATIC_CONTRACT_GC_TRIGGERS;

    // IMPORTANT!!!
    // The caller has already registered a waiter. This function needs to unregister the waiter on all paths (exception paths
    // included). On runtimes where thread-abort is supported, a thread-abort also needs to unregister the waiter. There may be
    // a possibility for preemptive GC toggles below to handle a thread-abort, that should be taken into consideration when
    // porting this code back to .NET Framework.

    // Require all callers to be in cooperative mode.  If they have switched to preemptive
    // mode temporarily before calling here, then they are responsible for protecting
    // the object associated with this lock.
    _ASSERTE(pCurThread->PreemptiveGCDisabled());

    COUNTER_ONLY(GetPerfCounters().m_LocksAndThreads.cContention++);

    // Fire a contention start event for a managed contention
    FireEtwContentionStart_V1(ETW::ContentionLog::ContentionStructs::ManagedContention, GetClrInstanceId());

    LogContention();

    OBJECTREF obj = GetOwningObject();

    // We cannot allow the AwareLock to be cleaned up underneath us by the GC.
    IncrementTransientPrecious();

    DWORD ret;
    GCPROTECT_BEGIN(obj);
    {
        if (!m_SemEvent.IsMonitorEventAllocated())
        {
            AllocLockSemEvent();
        }
        _ASSERTE(m_SemEvent.IsMonitorEventAllocated());

        pCurThread->EnablePreemptiveGC();

        for (;;)
        {
            // We might be interrupted during the wait (Thread.Interrupt), so we need an
            // exception handler round the call.
            struct Param
            {
                AwareLock *pThis;
                INT32 timeOut;
                DWORD ret;
            } param;
            param.pThis = this;
            param.timeOut = timeOut;

            // Measure the time we wait so that, in the case where we wake up
            // and fail to acquire the mutex, we can adjust remaining timeout
            // accordingly.
            ULONGLONG start = CLRGetTickCount64();

            EE_TRY_FOR_FINALLY(Param *, pParam, &param)
            {
                pParam->ret = pParam->pThis->m_SemEvent.Wait(pParam->timeOut, TRUE);
                _ASSERTE((pParam->ret == WAIT_OBJECT_0) || (pParam->ret == WAIT_TIMEOUT));
            }
            EE_FINALLY
            {
                if (GOT_EXCEPTION())
                {
                    // It is likely the case that An APC threw an exception, for instance Thread.Interrupt(). The wait subsystem
                    // guarantees that if a signal to the event being waited upon is observed by the woken thread, that thread's
                    // wait will return WAIT_OBJECT_0. So in any race between m_SemEvent being signaled and the wait throwing an
                    // exception, a thread that is woken by an exception would not observe the signal, and the signal would wake
                    // another thread as necessary.

                    // We must decrement the waiter count.
                    m_lockState.InterlockedUnregisterWaiter();
                }
            } EE_END_FINALLY;

            ret = param.ret;
            if (ret != WAIT_OBJECT_0)
            {
                // We timed out, decrement waiter count.
                m_lockState.InterlockedUnregisterWaiter();
                break;
            }

            // Spin a bit while trying to acquire the lock. This has a few benefits:
            // - Spinning helps to reduce waiter starvation. Since other non-waiter threads can take the lock while there are
            //   waiters (see LockState::InterlockedTryLock()), once a waiter wakes it will be able to better compete
            //   with other spinners for the lock.
            // - If there is another thread that is repeatedly acquiring and releasing the lock, spinning before waiting again
            //   helps to prevent a waiter from repeatedly context-switching in and out
            // - Further in the same situation above, waking up and waiting shortly thereafter deprioritizes this waiter because
            //   events release waiters in FIFO order. Spinning a bit helps a waiter to retain its priority at least for one
            //   spin duration before it gets deprioritized behind all other waiters.
            if (g_SystemInfo.dwNumberOfProcessors > 1)
            {
                bool acquiredLock = false;
                YieldProcessorNormalizationInfo normalizationInfo;
                const DWORD spinCount = g_SpinConstants.dwMonitorSpinCount;
                for (DWORD spinIteration = 0; spinIteration < spinCount; ++spinIteration)
                {
                    if (m_lockState.InterlockedTry_LockAndUnregisterWaiterAndObserveWakeSignal(this))
                    {
                        acquiredLock = true;
                        break;
                    }

                    SpinWait(normalizationInfo, spinIteration);
                }
                if (acquiredLock)
                {
                    break;
                }
            }

            if (m_lockState.InterlockedObserveWakeSignal_Try_LockAndUnregisterWaiter(this))
            {
                break;
            }

            // When calculating duration we consider a couple of special cases.
            // If the end tick is the same as the start tick we make the
            // duration a millisecond, to ensure we make forward progress if
            // there's a lot of contention on the mutex. Secondly, we have to
            // cope with the case where the tick counter wrapped while we where
            // waiting (we can cope with at most one wrap, so don't expect three
            // month timeouts to be very accurate). Luckily for us, the latter
            // case is taken care of by 32-bit modulo arithmetic automatically.
            if (timeOut != (INT32)INFINITE)
            {
                ULONGLONG end = CLRGetTickCount64();
                ULONGLONG duration;
                if (end == start)
                {
                    duration = 1;
                }
                else
                {
                    duration = end - start;
                }
                duration = min(duration, (DWORD)timeOut);
                timeOut -= (INT32)duration;
            }
        }

        pCurThread->DisablePreemptiveGC();
    }
    GCPROTECT_END();
    DecrementTransientPrecious();

    // Fire a contention end event for a managed contention
    FireEtwContentionStop(ETW::ContentionLog::ContentionStructs::ManagedContention, GetClrInstanceId());

    if (ret == WAIT_TIMEOUT)
    {
        return false;
    }

    m_HoldingThread = pCurThread;
    m_Recursion = 1;
    pCurThread->IncLockCount();

#if defined(_DEBUG) && defined(TRACK_SYNC)
    // The best place to grab this is from the ECall frame
    Frame   *pFrame = pCurThread->GetFrame();
    int      caller = (pFrame && pFrame != FRAME_TOP ? (int)pFrame->GetReturnAddress() : -1);
    pCurThread->m_pTrackSync->EnterSync(caller, this);
#endif
    return true;
}


BOOL AwareLock::Leave()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    Thread* pThread = GetThread();

    AwareLock::LeaveHelperAction action = LeaveHelper(pThread);

    switch(action)
    {
    case AwareLock::LeaveHelperAction_None:
        // We are done
        return TRUE;
    case AwareLock::LeaveHelperAction_Signal:
        // Signal the event
        Signal();
        return TRUE;
    default:
        // Must be an error otherwise
        _ASSERTE(action == AwareLock::LeaveHelperAction_Error);
        return FALSE;
    }
}

LONG AwareLock::LeaveCompletely()
{
    WRAPPER_NO_CONTRACT;

    LONG count = 0;
    while (Leave()) {
        count++;
    }
    _ASSERTE(count > 0);            // otherwise we were never in the lock

    return count;
}


BOOL AwareLock::OwnedByCurrentThread()
{
    WRAPPER_NO_CONTRACT;
    return (GetThread() == m_HoldingThread);
}


// ***************************************************************************
//
//              SyncBlock class implementation
//
// ***************************************************************************

// We maintain two queues for SyncBlock::Wait.
// 1. Inside SyncBlock we queue all threads that are waiting on the SyncBlock.
//    When we pulse, we pick the thread from this queue using FIFO.
// 2. We queue all SyncBlocks that a thread is waiting for in Thread::m_WaitEventLink.
//    When we pulse a thread, we find the event from this queue to set, and we also
//    or in a 1 bit in the syncblock value saved in the queue, so that we can return
//    immediately from SyncBlock::Wait if the syncblock has been pulsed.
BOOL SyncBlock::Wait(INT32 timeOut, BOOL exitContext)
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        THROWS;
        GC_TRIGGERS;
        MODE_ANY;
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    Thread  *pCurThread = GetThread();
    BOOL     isTimedOut = FALSE;
    BOOL     isEnqueued = FALSE;
    WaitEventLink waitEventLink;
    WaitEventLink *pWaitEventLink;

    // As soon as we flip the switch, we are in a race with the GC, which could clean
    // up the SyncBlock underneath us -- unless we report the object.
    _ASSERTE(pCurThread->PreemptiveGCDisabled());

    // Does this thread already wait for this SyncBlock?
    WaitEventLink *walk = pCurThread->WaitEventLinkForSyncBlock(this);
    if (walk->m_Next) {
        if (walk->m_Next->m_WaitSB == this) {
            // Wait on the same lock again.
            walk->m_Next->m_RefCount ++;
            pWaitEventLink = walk->m_Next;
        }
        else if ((SyncBlock*)(((DWORD_PTR)walk->m_Next->m_WaitSB) & ~1)== this) {
            // This thread has been pulsed.  No need to wait.
            return TRUE;
        }
    }
    else {
        // First time this thread is going to wait for this SyncBlock.
        CLREvent* hEvent;
        if (pCurThread->m_WaitEventLink.m_Next == NULL) {
            hEvent = &(pCurThread->m_EventWait);
        }
        else {
            hEvent = GetEventFromEventStore();
        }
        waitEventLink.m_WaitSB = this;
        waitEventLink.m_EventWait = hEvent;
        waitEventLink.m_Thread = pCurThread;
        waitEventLink.m_Next = NULL;
        waitEventLink.m_LinkSB.m_pNext = NULL;
        waitEventLink.m_RefCount = 1;
        pWaitEventLink = &waitEventLink;
        walk->m_Next = pWaitEventLink;

        // Before we enqueue it (and, thus, before it can be dequeued), reset the event
        // that will awaken us.
        hEvent->Reset();

        // This thread is now waiting on this sync block
        ThreadQueue::EnqueueThread(pWaitEventLink, this);

        isEnqueued = TRUE;
    }

    _ASSERTE ((SyncBlock*)((DWORD_PTR)walk->m_Next->m_WaitSB & ~1)== this);

    PendingSync   syncState(walk);

    OBJECTREF     obj = m_Monitor.GetOwningObject();

    m_Monitor.IncrementTransientPrecious();

    // While we are in this frame the thread is considered blocked on the
    // event of the monitor lock according to the debugger
    DebugBlockingItem blockingMonitorInfo;
    blockingMonitorInfo.dwTimeout = timeOut;
    blockingMonitorInfo.pMonitor = &m_Monitor;
    blockingMonitorInfo.pAppDomain = SystemDomain::GetCurrentDomain();
    blockingMonitorInfo.type = DebugBlock_MonitorEvent;
    DebugBlockingItemHolder holder(pCurThread, &blockingMonitorInfo);

    GCPROTECT_BEGIN(obj);
    {
        GCX_PREEMP();

        // remember how many times we synchronized
        syncState.m_EnterCount = LeaveMonitorCompletely();
        _ASSERTE(syncState.m_EnterCount > 0);

        Context* targetContext;
        targetContext = pCurThread->GetContext();
        _ASSERTE(targetContext);
        Context* defaultContext;
        defaultContext = pCurThread->GetDomain()->GetDefaultContext();
        _ASSERTE(defaultContext);
        _ASSERTE( exitContext==NULL || targetContext == defaultContext);
        {
            isTimedOut = pCurThread->Block(timeOut, &syncState);
        }
    }
    GCPROTECT_END();
    m_Monitor.DecrementTransientPrecious();

    return !isTimedOut;
}

void SyncBlock::Pulse()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    WaitEventLink  *pWaitEventLink;

    if ((pWaitEventLink = ThreadQueue::DequeueThread(this)) != NULL)
        pWaitEventLink->m_EventWait->Set();
}

void SyncBlock::PulseAll()
{
    CONTRACTL
    {
        INSTANCE_CHECK;
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    WaitEventLink  *pWaitEventLink;

    while ((pWaitEventLink = ThreadQueue::DequeueThread(this)) != NULL)
        pWaitEventLink->m_EventWait->Set();
}

bool SyncBlock::SetInteropInfo(InteropSyncBlockInfo* pInteropInfo)
{
    WRAPPER_NO_CONTRACT;
    SetPrecious();

    // We could be agile, but not have noticed yet.  We can't assert here
    //  that we live in any given domain, nor is this an appropriate place
    //  to re-parent the syncblock.
/*    _ASSERTE (m_dwAppDomainIndex.m_dwIndex == 0 || 
              m_dwAppDomainIndex == SystemDomain::System()->DefaultDomain()->GetIndex() || 
              m_dwAppDomainIndex == GetAppDomain()->GetIndex());
    m_dwAppDomainIndex = GetAppDomain()->GetIndex();
*/
    return (FastInterlockCompareExchangePointer(&m_pInteropInfo,
                                                pInteropInfo,
                                                NULL) == NULL);
}

#ifdef EnC_SUPPORTED
// Store information about fields added to this object by EnC
// This must be called from a thread in the AppDomain of this object instance
void SyncBlock::SetEnCInfo(EnCSyncBlockInfo *pEnCInfo) 
{
    WRAPPER_NO_CONTRACT;

    // We can't recreate the field contents, so this SyncBlock can never go away
    SetPrecious();

    // Store the field info (should only ever happen once)
    _ASSERTE( m_pEnCInfo == NULL );
    m_pEnCInfo = pEnCInfo;

    // Also store the AppDomain that this object lives in.
    // Also verify that the AD was either not yet set, or set correctly before overwriting it.
    // I'm not sure why it should ever be set to the default domain and then changed to a different domain,
    // perhaps that can be removed.
    _ASSERTE (m_dwAppDomainIndex.m_dwIndex == 0 || 
              m_dwAppDomainIndex == SystemDomain::System()->DefaultDomain()->GetIndex() || 
              m_dwAppDomainIndex == GetAppDomain()->GetIndex());
    m_dwAppDomainIndex = GetAppDomain()->GetIndex();
}
#endif // EnC_SUPPORTED
#endif // !DACCESS_COMPILE

#if defined(_WIN64) && defined(_DEBUG)
void ObjHeader::IllegalAlignPad()
{
    WRAPPER_NO_CONTRACT;
#ifdef LOGGING
    void** object = ((void**) this) + 1;
    LogSpewAlways("\n\n******** Illegal ObjHeader m_alignpad not 0, object" FMT_ADDR "\n\n",
                  DBG_ADDR(object));
#endif
    _ASSERTE(m_alignpad == 0);
}
#endif // _WIN64 && _DEBUG