summaryrefslogtreecommitdiff
path: root/src/gc/objecthandle.cpp
blob: 1654cf9b94204a6df700b9277e2b47b082aa5b18 (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
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*
 * Wraps handle table to implement various handle types (Strong, Weak, etc.)
 *

 *
 */

#include "common.h"

#include "gcenv.h"

#include "gc.h"
#include "gcscan.h"

#include "objecthandle.h"
#include "handletablepriv.h"

#ifdef FEATURE_COMINTEROP
#include "comcallablewrapper.h"
#endif // FEATURE_COMINTEROP
#ifndef FEATURE_REDHAWK
#include "nativeoverlapped.h"
#endif // FEATURE_REDHAWK

GVAL_IMPL(HandleTableMap, g_HandleTableMap);

// Array of contexts used while scanning dependent handles for promotion. There are as many contexts as GC
// heaps and they're allocated by Ref_Initialize and initialized during each GC by GcDhInitialScan.
DhContext *g_pDependentHandleContexts;

#ifndef DACCESS_COMPILE

//----------------------------------------------------------------------------

/*
 * struct VARSCANINFO
 *
 * used when tracing variable-strength handles.
 */
struct VARSCANINFO
{
    uintptr_t      lEnableMask; // mask of types to trace
    HANDLESCANPROC pfnTrace;    // tracing function to use
    uintptr_t      lp2;         // second parameter
};


//----------------------------------------------------------------------------

/*
 * Scan callback for tracing variable-strength handles.
 *
 * This callback is called to trace individual objects referred to by handles
 * in the variable-strength table.
 */
void CALLBACK VariableTraceDispatcher(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    WRAPPER_NO_CONTRACT;

    // lp2 is a pointer to our VARSCANINFO
    struct VARSCANINFO *pInfo = (struct VARSCANINFO *)lp2;

    // is the handle's dynamic type one we're currently scanning?
    if ((*pExtraInfo & pInfo->lEnableMask) != 0)
    {
        // yes - call the tracing function for this handle
        pInfo->pfnTrace(pObjRef, NULL, lp1, pInfo->lp2);
    }
}

#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
/*
 * Scan callback for tracing ref-counted handles.
 *
 * This callback is called to trace individual objects referred to by handles
 * in the refcounted table.
 */
void CALLBACK PromoteRefCounted(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    WRAPPER_NO_CONTRACT;
    UNREFERENCED_PARAMETER(pExtraInfo);

    // there are too many races when asychnronously scanning ref-counted handles so we no longer support it
    _ASSERTE(!((ScanContext*)lp1)->concurrent);

    LOG((LF_GC, LL_INFO1000, LOG_HANDLE_OBJECT_CLASS("", pObjRef, "causes promotion of ", *pObjRef)));

    Object *pObj = VolatileLoad((PTR_Object*)pObjRef);

#ifdef _DEBUG
    Object *pOldObj = pObj;
#endif

    if (!HndIsNullOrDestroyedHandle(pObj) && !GCHeap::GetGCHeap()->IsPromoted(pObj))
    {
        if (GCToEEInterface::RefCountedHandleCallbacks(pObj))
        {
            _ASSERTE(lp2);
            promote_func* callback = (promote_func*) lp2;
            callback(&pObj, (ScanContext *)lp1, 0);
        }
    }
    
    // Assert this object wasn't relocated since we are passing a temporary object's address.
    _ASSERTE(pOldObj == pObj);
}
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK

void CALLBACK TraceDependentHandle(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    WRAPPER_NO_CONTRACT;

    if (pObjRef == NULL || pExtraInfo == NULL)
        return;

    // At this point, it's possible that either or both of the primary and secondary
    // objects are NULL.  However, if the secondary object is non-NULL, then the primary
    // object should also be non-NULL.
    _ASSERTE(*pExtraInfo == NULL || *pObjRef != NULL);

    // lp2 is a HANDLESCANPROC
    HANDLESCANPROC pfnTrace = (HANDLESCANPROC) lp2;

    // is the handle's secondary object non-NULL?
    if ((*pObjRef != NULL) && (*pExtraInfo != 0))
    {
        // yes - call the tracing function for this handle
        pfnTrace(pObjRef, NULL, lp1, *pExtraInfo);
    }
}

void CALLBACK UpdateDependentHandle(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(pExtraInfo);

    Object **pPrimaryRef = (Object **)pObjRef;
    Object **pSecondaryRef = (Object **)pExtraInfo;
  
    LOG((LF_GC|LF_ENC, LL_INFO10000, LOG_HANDLE_OBJECT("Querying for new location of ", 
            pPrimaryRef, "to ", *pPrimaryRef)));
    LOG((LF_GC|LF_ENC, LL_INFO10000, LOG_HANDLE_OBJECT(" and ", 
            pSecondaryRef, "to ", *pSecondaryRef)));

#ifdef _DEBUG
    Object *pOldPrimary = *pPrimaryRef;
    Object *pOldSecondary = *pSecondaryRef;
#endif

	_ASSERTE(lp2);
	promote_func* callback = (promote_func*) lp2;
	callback(pPrimaryRef, (ScanContext *)lp1, 0);
	callback(pSecondaryRef, (ScanContext *)lp1, 0);

#ifdef _DEBUG
    if (pOldPrimary != *pPrimaryRef)
        LOG((LF_GC|LF_ENC, LL_INFO10000,  "Updating " FMT_HANDLE "from" FMT_ADDR "to " FMT_OBJECT "\n", 
             DBG_ADDR(pPrimaryRef), DBG_ADDR(pOldPrimary), DBG_ADDR(*pPrimaryRef)));
    else
        LOG((LF_GC|LF_ENC, LL_INFO10000, "Updating " FMT_HANDLE "- " FMT_OBJECT "did not move\n", 
             DBG_ADDR(pPrimaryRef), DBG_ADDR(*pPrimaryRef)));
    if (pOldSecondary != *pSecondaryRef)
        LOG((LF_GC|LF_ENC, LL_INFO10000,  "Updating " FMT_HANDLE "from" FMT_ADDR "to " FMT_OBJECT "\n", 
             DBG_ADDR(pSecondaryRef), DBG_ADDR(pOldSecondary), DBG_ADDR(*pSecondaryRef)));
    else
        LOG((LF_GC|LF_ENC, LL_INFO10000, "Updating " FMT_HANDLE "- " FMT_OBJECT "did not move\n", 
             DBG_ADDR(pSecondaryRef), DBG_ADDR(*pSecondaryRef)));
#endif
}

void CALLBACK PromoteDependentHandle(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(pExtraInfo);
    
    Object **pPrimaryRef = (Object **)pObjRef;
    Object **pSecondaryRef = (Object **)pExtraInfo;
    LOG((LF_GC|LF_ENC, LL_INFO1000, "Checking promotion of DependentHandle"));
    LOG((LF_GC|LF_ENC, LL_INFO1000, LOG_HANDLE_OBJECT_CLASS("\tPrimary:\t", pObjRef, "to ", *pObjRef)));
    LOG((LF_GC|LF_ENC, LL_INFO1000, LOG_HANDLE_OBJECT_CLASS("\tSecondary\t", pSecondaryRef, "to ", *pSecondaryRef)));

    ScanContext *sc = (ScanContext*)lp1;
    DhContext *pDhContext = Ref_GetDependentHandleContext(sc);

    if (*pObjRef && GCHeap::GetGCHeap()->IsPromoted(*pPrimaryRef))
    {
        if (!GCHeap::GetGCHeap()->IsPromoted(*pSecondaryRef))
        {
            LOG((LF_GC|LF_ENC, LL_INFO10000, "\tPromoting secondary " LOG_OBJECT_CLASS(*pSecondaryRef)));
            _ASSERTE(lp2);
            promote_func* callback = (promote_func*) lp2;
            callback(pSecondaryRef, (ScanContext *)lp1, 0);
            // need to rescan because we might have promoted an object that itself has added fields and this
            // promotion might be all that is pinning that object. If we've already scanned that dependent
            // handle relationship, we could lose it secondary object.
            pDhContext->m_fPromoted = true;
        }
    }
    else if (*pObjRef)
    {
        // If we see a non-cleared primary which hasn't been promoted, record the fact. We will only require a
        // rescan if this flag has been set (if it's clear then the previous scan found only clear and
        // promoted handles, so there's no chance of finding an additional handle being promoted on a
        // subsequent scan).
        pDhContext->m_fUnpromotedPrimaries = true;
    }
}
    
void CALLBACK ClearDependentHandle(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t /*lp1*/, uintptr_t /*lp2*/)
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(pExtraInfo);

    Object **pPrimaryRef = (Object **)pObjRef;
    Object **pSecondaryRef = (Object **)pExtraInfo;
    LOG((LF_GC|LF_ENC, LL_INFO1000, "Checking referent of DependentHandle"));
    LOG((LF_GC|LF_ENC, LL_INFO1000, LOG_HANDLE_OBJECT_CLASS("\tPrimary:\t", pPrimaryRef, "to ", *pPrimaryRef)));
    LOG((LF_GC|LF_ENC, LL_INFO1000, LOG_HANDLE_OBJECT_CLASS("\tSecondary\t", pSecondaryRef, "to ", *pSecondaryRef)));

    if (!GCHeap::GetGCHeap()->IsPromoted(*pPrimaryRef))
    {
        LOG((LF_GC|LF_ENC, LL_INFO1000, "\tunreachable ", LOG_OBJECT_CLASS(*pPrimaryRef)));
        LOG((LF_GC|LF_ENC, LL_INFO1000, "\tunreachable ", LOG_OBJECT_CLASS(*pSecondaryRef)));
        *pPrimaryRef = NULL;
        *pSecondaryRef = NULL;
    }
    else
    {
        _ASSERTE(GCHeap::GetGCHeap()->IsPromoted(*pSecondaryRef));
        LOG((LF_GC|LF_ENC, LL_INFO10000, "\tPrimary is reachable " LOG_OBJECT_CLASS(*pPrimaryRef)));
        LOG((LF_GC|LF_ENC, LL_INFO10000, "\tSecondary is reachable " LOG_OBJECT_CLASS(*pSecondaryRef)));
    }
}

/*
 * Scan callback for pinning handles.
 *
 * This callback is called to pin individual objects referred to by handles in
 * the pinning table.
 */
void CALLBACK PinObject(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_SO_TOLERANT;
    STATIC_CONTRACT_MODE_COOPERATIVE;
    UNREFERENCED_PARAMETER(pExtraInfo);

    // PINNING IS BAD - DON'T DO IT IF YOU CAN AVOID IT
    LOG((LF_GC, LL_WARNING, LOG_HANDLE_OBJECT_CLASS("WARNING: ", pObjRef, "causes pinning of ", *pObjRef)));

    Object **pRef = (Object **)pObjRef;
    _ASSERTE(lp2);
    promote_func* callback = (promote_func*) lp2;
    callback(pRef, (ScanContext *)lp1, GC_CALL_PINNED);

#ifndef FEATURE_REDHAWK
    Object * pPinnedObj = *pRef;

    if (!HndIsNullOrDestroyedHandle(pPinnedObj) && pPinnedObj->GetGCSafeMethodTable() == g_pOverlappedDataClass)
    {
        // reporting the pinned user objects
        OverlappedDataObject *pOverlapped = (OverlappedDataObject *)pPinnedObj;
        if (pOverlapped->m_userObject != NULL)
        {
            //callback(OBJECTREF_TO_UNCHECKED_OBJECTREF(pOverlapped->m_userObject), (ScanContext *)lp1, GC_CALL_PINNED);
            if (pOverlapped->m_isArray)
            {
                pOverlapped->m_userObjectInternal = static_cast<void*>(OBJECTREFToObject(pOverlapped->m_userObject));
                ArrayBase* pUserObject = (ArrayBase*)OBJECTREFToObject(pOverlapped->m_userObject);
                Object **ppObj = (Object**)pUserObject->GetDataPtr(TRUE);
                size_t num = pUserObject->GetNumComponents();
                for (size_t i = 0; i < num; i ++)
                {
                    callback(ppObj + i, (ScanContext *)lp1, GC_CALL_PINNED);
                }
            }
            else
            {
                callback(&OBJECTREF_TO_UNCHECKED_OBJECTREF(pOverlapped->m_userObject), (ScanContext *)lp1, GC_CALL_PINNED);
            }
        }

        if (pOverlapped->GetAppDomainId() !=  DefaultADID && pOverlapped->GetAppDomainIndex().m_dwIndex == DefaultADID)
        {
            OverlappedDataObject::MarkCleanupNeededFromGC();
        }
    }
#endif // !FEATURE_REDHAWK
}


/*
 * Scan callback for tracing strong handles.
 *
 * This callback is called to trace individual objects referred to by handles
 * in the strong table.
 */
void CALLBACK PromoteObject(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    WRAPPER_NO_CONTRACT;
    UNREFERENCED_PARAMETER(pExtraInfo);

    LOG((LF_GC, LL_INFO1000, LOG_HANDLE_OBJECT_CLASS("", pObjRef, "causes promotion of ", *pObjRef)));

    Object **ppRef = (Object **)pObjRef;
    _ASSERTE(lp2);
    promote_func* callback = (promote_func*) lp2;
    callback(ppRef, (ScanContext *)lp1, 0);
}


/*
 * Scan callback for disconnecting dead handles.
 *
 * This callback is called to check promotion of individual objects referred to by
 * handles in the weak tables.
 */
void CALLBACK CheckPromoted(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    WRAPPER_NO_CONTRACT;
    UNREFERENCED_PARAMETER(pExtraInfo);
    UNREFERENCED_PARAMETER(lp1);
    UNREFERENCED_PARAMETER(lp2);

    LOG((LF_GC, LL_INFO100000, LOG_HANDLE_OBJECT_CLASS("Checking referent of Weak-", pObjRef, "to ", *pObjRef)));

    Object **ppRef = (Object **)pObjRef;
    if (!GCHeap::GetGCHeap()->IsPromoted(*ppRef))
    {
        LOG((LF_GC, LL_INFO100, LOG_HANDLE_OBJECT_CLASS("Severing Weak-", pObjRef, "to unreachable ", *pObjRef)));

        *ppRef = NULL;
    }
    else
    {
        LOG((LF_GC, LL_INFO1000000, "reachable " LOG_OBJECT_CLASS(*pObjRef)));
    }
}

void CALLBACK CalculateSizedRefSize(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    LIMITED_METHOD_CONTRACT;

    _ASSERTE(pExtraInfo);
    
    Object **ppSizedRef = (Object **)pObjRef;
    size_t* pSize = (size_t *)pExtraInfo;
    LOG((LF_GC, LL_INFO100000, LOG_HANDLE_OBJECT_CLASS("Getting size of referent of SizedRef-", pObjRef, "to ", *pObjRef)));

    ScanContext* sc = (ScanContext *)lp1;
    promote_func* callback = (promote_func*) lp2;

    size_t sizeBegin = GCHeap::GetGCHeap()->GetPromotedBytes(sc->thread_number);
    callback(ppSizedRef, (ScanContext *)lp1, 0);
    size_t sizeEnd = GCHeap::GetGCHeap()->GetPromotedBytes(sc->thread_number);
    *pSize = sizeEnd - sizeBegin;
}

/*
 * Scan callback for updating pointers.
 *
 * This callback is called to update pointers for individual objects referred to by
 * handles in the weak and strong tables.
 */
void CALLBACK UpdatePointer(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    LIMITED_METHOD_CONTRACT;
    UNREFERENCED_PARAMETER(pExtraInfo);

    LOG((LF_GC, LL_INFO100000, LOG_HANDLE_OBJECT("Querying for new location of ", pObjRef, "to ", *pObjRef)));

    Object **ppRef = (Object **)pObjRef;

#ifdef _DEBUG
    Object *pOldLocation = *ppRef;
#endif

    _ASSERTE(lp2);
    promote_func* callback = (promote_func*) lp2;
    callback(ppRef, (ScanContext *)lp1, 0);

#ifdef _DEBUG
    if (pOldLocation != *pObjRef)
        LOG((LF_GC, LL_INFO10000,  "Updating " FMT_HANDLE "from" FMT_ADDR "to " FMT_OBJECT "\n", 
             DBG_ADDR(pObjRef), DBG_ADDR(pOldLocation), DBG_ADDR(*pObjRef)));
    else
        LOG((LF_GC, LL_INFO100000, "Updating " FMT_HANDLE "- " FMT_OBJECT "did not move\n", 
             DBG_ADDR(pObjRef), DBG_ADDR(*pObjRef)));
#endif
}


#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)
/*
 * Scan callback for updating pointers.
 *
 * This callback is called to update pointers for individual objects referred to by
 * handles in the weak and strong tables.
 */
void CALLBACK ScanPointerForProfilerAndETW(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
#ifndef FEATURE_REDHAWK
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        if (GetThreadNULLOk()) { MODE_COOPERATIVE; } 
    }
    CONTRACTL_END;
#endif // FEATURE_REDHAWK
    UNREFERENCED_PARAMETER(pExtraInfo);
    UNREFERENCED_PARAMETER(lp2);

    LOG((LF_GC | LF_CORPROF, LL_INFO100000, LOG_HANDLE_OBJECT_CLASS("Notifying profiler of ", pObjRef, "to ", *pObjRef)));

    // Get the baseobject (which can subsequently be cast into an OBJECTREF == ObjectID
    Object **pRef = (Object **)pObjRef;

    // Get a hold of the heap ID that's tacked onto the end of the scancontext struct.
    ProfilingScanContext *pSC = (ProfilingScanContext *)lp1;

    uint32_t rootFlags = 0;
    BOOL isDependent = FALSE;

    OBJECTHANDLE handle = (OBJECTHANDLE)(pRef);
    switch (HandleFetchType(handle))
    {
    case    HNDTYPE_DEPENDENT:
        isDependent = TRUE;
        break;
    case    HNDTYPE_WEAK_SHORT:
    case    HNDTYPE_WEAK_LONG:
#ifdef FEATURE_COMINTEROP
    case    HNDTYPE_WEAK_WINRT:
#endif // FEATURE_COMINTEROP
        rootFlags |= kEtwGCRootFlagsWeakRef;
        break;

    case    HNDTYPE_STRONG:
    case    HNDTYPE_SIZEDREF:
        break;

    case    HNDTYPE_PINNED:
    case    HNDTYPE_ASYNCPINNED:
        rootFlags |= kEtwGCRootFlagsPinning;
        break;

    case    HNDTYPE_VARIABLE:
#ifdef FEATURE_REDHAWK
    {
        // Set the appropriate ETW flags for the current strength of this variable handle
        uint32_t nVarHandleType = GetVariableHandleType(handle);
        if (((nVarHandleType & VHT_WEAK_SHORT) != 0) ||
            ((nVarHandleType & VHT_WEAK_LONG) != 0))
        {
            rootFlags |= kEtwGCRootFlagsWeakRef;
        }
        if ((nVarHandleType & VHT_PINNED) != 0)
        {
            rootFlags |= kEtwGCRootFlagsPinning;
        }

        // No special ETW flag for strong handles (VHT_STRONG)
    }
#else
        _ASSERTE(!"Variable handle encountered");
#endif
        break;

#if defined(FEATURE_COMINTEROP) && !defined(FEATURE_REDHAWK)
    case    HNDTYPE_REFCOUNTED:
        rootFlags |= kEtwGCRootFlagsRefCounted;
        if (*pRef != NULL)
        {
            ComCallWrapper* pWrap = ComCallWrapper::GetWrapperForObject((OBJECTREF)*pRef);
            if (pWrap == NULL || !pWrap->IsWrapperActive())
                rootFlags |= kEtwGCRootFlagsWeakRef;
        }
        break;
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
    }

    _UNCHECKED_OBJECTREF pSec = NULL;

#ifdef GC_PROFILING
    // Give the profiler the objectref.
    if (pSC->fProfilerPinned)
    {
        if (!isDependent)
        {
            BEGIN_PIN_PROFILER(CORProfilerTrackGC());
            g_profControlBlock.pProfInterface->RootReference2(
                (uint8_t *)*pRef,
                kEtwGCRootKindHandle,
                (EtwGCRootFlags)rootFlags,
                pRef, 
                &pSC->pHeapId);
            END_PIN_PROFILER();
        }
        else
        {
            BEGIN_PIN_PROFILER(CORProfilerTrackConditionalWeakTableElements());
            pSec = (_UNCHECKED_OBJECTREF)HndGetHandleExtraInfo(handle);
            g_profControlBlock.pProfInterface->ConditionalWeakTableElementReference(
                (uint8_t*)*pRef,
                (uint8_t*)pSec,
                pRef,
                &pSC->pHeapId);
            END_PIN_PROFILER();
        }
    }
#endif // GC_PROFILING

    // Notify ETW of the handle
    if (ETW::GCLog::ShouldWalkHeapRootsForEtw())
    {
        if (isDependent && (pSec == NULL))
        {
            pSec = (_UNCHECKED_OBJECTREF)HndGetHandleExtraInfo(handle);

        }

        ETW::GCLog::RootReference(
            handle,
            *pRef,          // object being rooted
            pSec,           // pSecondaryNodeForDependentHandle
            isDependent,
            pSC,
            0,              // dwGCFlags,
            rootFlags);     // ETW handle flags
    }
}
#endif // defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)



/*
 * Scan callback for updating pointers.
 *
 * This callback is called to update pointers for individual objects referred to by
 * handles in the pinned table.
 */
void CALLBACK UpdatePointerPinned(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    LIMITED_METHOD_CONTRACT;
    UNREFERENCED_PARAMETER(pExtraInfo);

    Object **ppRef = (Object **)pObjRef;

    _ASSERTE(lp2);
    promote_func* callback = (promote_func*) lp2;
    callback(ppRef, (ScanContext *)lp1, GC_CALL_PINNED);
    
    LOG((LF_GC, LL_INFO100000, LOG_HANDLE_OBJECT("Updating ", pObjRef, "to pinned ", *pObjRef)));
}


//----------------------------------------------------------------------------

// flags describing the handle types
static const uint32_t s_rgTypeFlags[] =
{
    HNDF_NORMAL,    // HNDTYPE_WEAK_SHORT
    HNDF_NORMAL,    // HNDTYPE_WEAK_LONG
    HNDF_NORMAL,    // HNDTYPE_STRONG
    HNDF_NORMAL,    // HNDTYPE_PINNED
    HNDF_EXTRAINFO, // HNDTYPE_VARIABLE
    HNDF_NORMAL,    // HNDTYPE_REFCOUNTED
    HNDF_EXTRAINFO, // HNDTYPE_DEPENDENT
    HNDF_NORMAL,    // HNDTYPE_ASYNCPINNED
    HNDF_EXTRAINFO, // HNDTYPE_SIZEDREF
    HNDF_EXTRAINFO, // HNDTYPE_WEAK_WINRT
};

int getNumberOfSlots()
{
    WRAPPER_NO_CONTRACT;

    // when Ref_Initialize called, GCHeap::GetNumberOfHeaps() is still 0, so use #procs as a workaround
    // it is legal since even if later #heaps < #procs we create handles by thread home heap
    // and just have extra unused slots in HandleTableBuckets, which does not take a lot of space
    if (!GCHeap::IsServerHeap())
        return 1;

#ifdef FEATURE_REDHAWK
    return g_SystemInfo.dwNumberOfProcessors;
#else
    return (CPUGroupInfo::CanEnableGCCPUGroups() ? CPUGroupInfo::GetNumActiveProcessors() :
                                                   g_SystemInfo.dwNumberOfProcessors);
#endif
}

class HandleTableBucketHolder
{
private:
    HandleTableBucket* m_bucket;
    int m_slots;
    BOOL m_SuppressRelease;
public:
    HandleTableBucketHolder(HandleTableBucket* bucket, int slots);
    ~HandleTableBucketHolder();

    void SuppressRelease()
    {
        m_SuppressRelease = TRUE;
    }
};

HandleTableBucketHolder::HandleTableBucketHolder(HandleTableBucket* bucket, int slots)
    :m_bucket(bucket), m_slots(slots), m_SuppressRelease(FALSE)
{
}

HandleTableBucketHolder::~HandleTableBucketHolder()
{
    if (m_SuppressRelease)
    {
        return;
    }
    if (m_bucket->pTable)
    {
        for (int n = 0; n < m_slots; n ++)
        {
            if (m_bucket->pTable[n])
            {
                HndDestroyHandleTable(m_bucket->pTable[n]);
            }
        }
        delete [] m_bucket->pTable;
    }
    delete m_bucket;
}

bool Ref_Initialize()
{
    CONTRACTL
    {
        NOTHROW;
        WRAPPER(GC_NOTRIGGER);
        INJECT_FAULT(return false);
    }
    CONTRACTL_END;

    // sanity
    _ASSERTE(g_HandleTableMap.pBuckets == NULL);

    // Create an array of INITIAL_HANDLE_TABLE_ARRAY_SIZE HandleTableBuckets to hold the handle table sets
    HandleTableBucket** pBuckets = new (nothrow) HandleTableBucket * [ INITIAL_HANDLE_TABLE_ARRAY_SIZE ];
    if (pBuckets == NULL)
        return false;

    ZeroMemory(pBuckets,
         INITIAL_HANDLE_TABLE_ARRAY_SIZE * sizeof (HandleTableBucket *));

    // Crate the first bucket
    HandleTableBucket * pBucket = new (nothrow) HandleTableBucket;
    if (pBucket != NULL)
    {
        pBucket->HandleTableIndex = 0;

        int n_slots = getNumberOfSlots();

        HandleTableBucketHolder bucketHolder(pBucket, n_slots);

        // create the handle table set for the first bucket
        pBucket->pTable = new (nothrow) HHANDLETABLE[n_slots];
        if (pBucket->pTable == NULL)
            goto CleanupAndFail;

        ZeroMemory(pBucket->pTable,
            n_slots * sizeof(HHANDLETABLE));
        for (int uCPUindex = 0; uCPUindex < n_slots; uCPUindex++)
        {
            pBucket->pTable[uCPUindex] = HndCreateHandleTable(s_rgTypeFlags, _countof(s_rgTypeFlags), ADIndex(1));
            if (pBucket->pTable[uCPUindex] == NULL)
                goto CleanupAndFail;

            HndSetHandleTableIndex(pBucket->pTable[uCPUindex], 0);
        }

        pBuckets[0] = pBucket;
        bucketHolder.SuppressRelease();

        g_HandleTableMap.pBuckets = pBuckets;
        g_HandleTableMap.dwMaxIndex = INITIAL_HANDLE_TABLE_ARRAY_SIZE;
        g_HandleTableMap.pNext = NULL;

        // Allocate contexts used during dependent handle promotion scanning. There's one of these for every GC
        // heap since they're scanned in parallel.
        g_pDependentHandleContexts = new (nothrow) DhContext[n_slots];
        if (g_pDependentHandleContexts == NULL)
            goto CleanupAndFail;

        return true;
    }

CleanupAndFail:
    if (pBuckets != NULL)
        delete[] pBuckets;
    return false;
}

void Ref_Shutdown()
{
    WRAPPER_NO_CONTRACT;

    if (g_pDependentHandleContexts)
    {
        delete [] g_pDependentHandleContexts;
        g_pDependentHandleContexts = NULL;
    }

    // are there any handle tables?
    if (g_HandleTableMap.pBuckets)
    {
        // don't destroy any of the indexed handle tables; they should
        // be destroyed externally.

        // destroy the global handle table bucket tables
        Ref_DestroyHandleTableBucket(g_HandleTableMap.pBuckets[0]);

        // destroy the handle table bucket array
        HandleTableMap *walk = &g_HandleTableMap;
        while (walk) {
            delete [] walk->pBuckets;
            walk = walk->pNext;
        }

        // null out the handle table array
        g_HandleTableMap.pNext = NULL;
        g_HandleTableMap.dwMaxIndex = 0;

        // null out the global table handle
        g_HandleTableMap.pBuckets = NULL;
    }
}

#ifndef FEATURE_REDHAWK
// ATTENTION: interface changed
// Note: this function called only from AppDomain::Init()
HandleTableBucket *Ref_CreateHandleTableBucket(ADIndex uADIndex)
{
    CONTRACTL
    {
        THROWS;
        WRAPPER(GC_TRIGGERS);
        INJECT_FAULT(COMPlusThrowOM());
    }
    CONTRACTL_END;

    HandleTableBucket *result = NULL;
    HandleTableMap *walk;
    
    walk = &g_HandleTableMap;
    HandleTableMap *last = NULL;
    uint32_t offset = 0;

    result = new HandleTableBucket;
    result->pTable = NULL;

    // create handle table set for the bucket
    int n_slots = getNumberOfSlots();

    HandleTableBucketHolder bucketHolder(result, n_slots);

    result->pTable = new HHANDLETABLE [ n_slots ];
    ZeroMemory(result->pTable, n_slots * sizeof (HHANDLETABLE));

    for (int uCPUindex=0; uCPUindex < n_slots; uCPUindex++) {
        result->pTable[uCPUindex] = HndCreateHandleTable(s_rgTypeFlags, _countof(s_rgTypeFlags), uADIndex);
        if (!result->pTable[uCPUindex])
            COMPlusThrowOM();
    }

    for (;;) {
        // Do we have free slot
        while (walk) {
            for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++) {
                if (walk->pBuckets[i] == 0) {
                    for (int uCPUindex=0; uCPUindex < n_slots; uCPUindex++)
                        HndSetHandleTableIndex(result->pTable[uCPUindex], i+offset);

                    result->HandleTableIndex = i+offset;
                    if (Interlocked::CompareExchangePointer(&walk->pBuckets[i], result, NULL) == 0) {
                        // Get a free slot.
                        bucketHolder.SuppressRelease();
                        return result;
                    }
                }
            }
            last = walk;
            offset = walk->dwMaxIndex;
            walk = walk->pNext;
        }

        // No free slot.
        // Let's create a new node
        NewHolder<HandleTableMap> newMap;
        newMap = new HandleTableMap;

        newMap->pBuckets = new HandleTableBucket * [ INITIAL_HANDLE_TABLE_ARRAY_SIZE ];
        newMap.SuppressRelease();

        newMap->dwMaxIndex = last->dwMaxIndex + INITIAL_HANDLE_TABLE_ARRAY_SIZE;
        newMap->pNext = NULL;
        ZeroMemory(newMap->pBuckets,
                INITIAL_HANDLE_TABLE_ARRAY_SIZE * sizeof (HandleTableBucket *));

        if (Interlocked::CompareExchangePointer(&last->pNext, newMap.GetValue(), NULL) != NULL) 
        {
            // This thread loses.
            delete [] newMap->pBuckets;
            delete newMap;
        }
        walk = last->pNext;
        offset = last->dwMaxIndex;
    }
}
#endif // !FEATURE_REDHAWK

void Ref_RemoveHandleTableBucket(HandleTableBucket *pBucket)
{
    LIMITED_METHOD_CONTRACT;

    size_t          index   = pBucket->HandleTableIndex;
    HandleTableMap* walk    = &g_HandleTableMap;
    size_t          offset  = 0;

    while (walk) 
    {
        if ((index < walk->dwMaxIndex) && (index >= offset)) 
        {
            // During AppDomain unloading, we first remove a handle table and then destroy
            // the table.  As soon as the table is removed, the slot can be reused.
            if (walk->pBuckets[index - offset] == pBucket)
            {
                walk->pBuckets[index - offset] = NULL;
                return;
            }
        }
        offset = walk->dwMaxIndex;
        walk   = walk->pNext;
    }

    // Didn't find it.  This will happen typically from Ref_DestroyHandleTableBucket if 
    // we explicitly call Ref_RemoveHandleTableBucket first.
}


void Ref_DestroyHandleTableBucket(HandleTableBucket *pBucket)
{
    WRAPPER_NO_CONTRACT;

    // this check is because here we might be called from AppDomain::Terminate after AppDomain::ClearGCRoots,
    // which calls Ref_RemoveHandleTableBucket itself

    Ref_RemoveHandleTableBucket(pBucket);
    for (int uCPUindex=0; uCPUindex < getNumberOfSlots(); uCPUindex++)
    {
        HndDestroyHandleTable(pBucket->pTable[uCPUindex]);
    }
    delete [] pBucket->pTable;
    delete pBucket;
}

int getSlotNumber(ScanContext* sc)
{
    WRAPPER_NO_CONTRACT;

    return (GCHeap::IsServerHeap() ? sc->thread_number : 0);
}

// <TODO> - reexpress as complete only like hndtable does now!!! -fmh</REVISIT_TODO>
void Ref_EndSynchronousGC(uint32_t condemned, uint32_t maxgen)
{
    LIMITED_METHOD_CONTRACT;
    UNREFERENCED_PARAMETER(condemned);
    UNREFERENCED_PARAMETER(maxgen);

// NOT used, must be modified for MTHTS (scalable HandleTable scan) if planned to use:
// need to pass ScanContext info to split HT bucket by threads, or to be performed under t_join::join
/*
    // tell the table we finished a GC
    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++) {
            HHANDLETABLE hTable = walk->pTable[i];
            if (hTable)
                HndNotifyGcCycleComplete(hTable, condemned, maxgen);
        }
        walk = walk->pNext;
    }
*/    
}


OBJECTHANDLE CreateDependentHandle(HHANDLETABLE table, OBJECTREF primary, OBJECTREF secondary)
{ 
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    OBJECTHANDLE handle = HndCreateHandle(table, HNDTYPE_DEPENDENT, primary); 

    SetDependentHandleSecondary(handle, secondary);

    return handle;
}

void SetDependentHandleSecondary(OBJECTHANDLE handle, OBJECTREF objref)
{ 
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // sanity
    _ASSERTE(handle);

#ifdef _DEBUG
    // handle should not be in unloaded domain
    ValidateAppDomainForHandle(handle);

    // Make sure the objref is valid before it is assigned to a handle
    ValidateAssignObjrefForHandle(objref, HndGetHandleTableADIndex(HndGetHandleTable(handle)));
#endif
    // unwrap the objectref we were given
    _UNCHECKED_OBJECTREF value = OBJECTREF_TO_UNCHECKED_OBJECTREF(objref);

    // if we are doing a non-NULL pointer store then invoke the write-barrier
    if (value)
        HndWriteBarrier(handle, objref);

    // store the pointer
    HndSetHandleExtraInfo(handle, HNDTYPE_DEPENDENT, (uintptr_t)value);
}


//----------------------------------------------------------------------------

/*
 * CreateVariableHandle.
 *
 * Creates a variable-strength handle.
 *
 * N.B. This routine is not a macro since we do validation in RETAIL.
 * We always validate the type here because it can come from external callers.
 */
OBJECTHANDLE CreateVariableHandle(HHANDLETABLE hTable, OBJECTREF object, uint32_t type)
{
    WRAPPER_NO_CONTRACT;

    // verify that we are being asked to create a valid type
    if (!IS_VALID_VHT_VALUE(type))
    {
        // bogus value passed in
        _ASSERTE(FALSE);
        return NULL;
    }

    // create the handle
    return HndCreateHandle(hTable, HNDTYPE_VARIABLE, object, (uintptr_t)type);
}

/*
* GetVariableHandleType.
*
* Retrieves the dynamic type of a variable-strength handle.
*/
uint32_t GetVariableHandleType(OBJECTHANDLE handle)
{
    WRAPPER_NO_CONTRACT;

    return (uint32_t)HndGetHandleExtraInfo(handle);
}

/*
 * UpdateVariableHandleType.
 *
 * Changes the dynamic type of a variable-strength handle.
 *
 * N.B. This routine is not a macro since we do validation in RETAIL.
 * We always validate the type here because it can come from external callers.
 */
void UpdateVariableHandleType(OBJECTHANDLE handle, uint32_t type)
{
    WRAPPER_NO_CONTRACT;

    // verify that we are being asked to set a valid type
    if (!IS_VALID_VHT_VALUE(type))
    {
        // bogus value passed in
        _ASSERTE(FALSE);
        return;
    }

    // <REVISIT_TODO> (francish)  CONCURRENT GC NOTE</REVISIT_TODO>
    //
    // If/when concurrent GC is implemented, we need to make sure variable handles
    // DON'T change type during an asynchronous scan, OR that we properly recover
    // from the change.  Some changes are benign, but for example changing to or
    // from a pinning handle in the middle of a scan would not be fun.
    //

    // store the type in the handle's extra info
    HndSetHandleExtraInfo(handle, HNDTYPE_VARIABLE, (uintptr_t)type);
}

/*
* CompareExchangeVariableHandleType.
*
* Changes the dynamic type of a variable-strength handle. Unlike UpdateVariableHandleType we assume that the
* types have already been validated.
*/
uint32_t CompareExchangeVariableHandleType(OBJECTHANDLE handle, uint32_t oldType, uint32_t newType)
{
    WRAPPER_NO_CONTRACT;

    // verify that we are being asked to get/set valid types
    _ASSERTE(IS_VALID_VHT_VALUE(oldType) && IS_VALID_VHT_VALUE(newType));

    // attempt to store the type in the handle's extra info
    return (uint32_t)HndCompareExchangeHandleExtraInfo(handle, HNDTYPE_VARIABLE, (uintptr_t)oldType, (uintptr_t)newType);
}


/*
 * TraceVariableHandles.
 *
 * Convenience function for tracing variable-strength handles.
 * Wraps HndScanHandlesForGC.
 */
void TraceVariableHandles(HANDLESCANPROC pfnTrace, uintptr_t lp1, uintptr_t lp2, uint32_t uEnableMask, uint32_t condemned, uint32_t maxgen, uint32_t flags)
{
    WRAPPER_NO_CONTRACT;

    // set up to scan variable handles with the specified mask and trace function
    uint32_t               type = HNDTYPE_VARIABLE;
    struct VARSCANINFO info = { (uintptr_t)uEnableMask, pfnTrace, lp2 };

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber((ScanContext*) lp1)];
                if (hTable)
                {
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
                    if (g_fEnableARM)
                    {
                        ScanContext* sc = (ScanContext *)lp1;
                        sc->pCurrentDomain = SystemDomain::GetAppDomainAtIndex(HndGetHandleTableADIndex(hTable));
                    }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
                    HndScanHandlesForGC(hTable, VariableTraceDispatcher,
                                        lp1, (uintptr_t)&info, &type, 1, condemned, maxgen, HNDGCF_EXTRAINFO | flags);
                }
            }
        walk = walk->pNext;
    }
}

/*
  loop scan version of TraceVariableHandles for single-thread-managed Ref_* functions
  should be kept in sync with the code above
*/
void TraceVariableHandlesBySingleThread(HANDLESCANPROC pfnTrace, uintptr_t lp1, uintptr_t lp2, uint32_t uEnableMask, uint32_t condemned, uint32_t maxgen, uint32_t flags)
{
    WRAPPER_NO_CONTRACT;

    // set up to scan variable handles with the specified mask and trace function
    uint32_t type = HNDTYPE_VARIABLE;
    struct VARSCANINFO info = { (uintptr_t)uEnableMask, pfnTrace, lp2 };

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                  // this is the one of Ref_* function performed by single thread in MULTI_HEAPS case, so we need to loop through all HT of the bucket
                for (int uCPUindex=0; uCPUindex < getNumberOfSlots(); uCPUindex++)
                {
                   HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                    if (hTable)
                        HndScanHandlesForGC(hTable, VariableTraceDispatcher,
                                        lp1, (uintptr_t)&info, &type, 1, condemned, maxgen, HNDGCF_EXTRAINFO | flags);
                }
            }
        walk = walk->pNext;
    }
}

//----------------------------------------------------------------------------

void Ref_TracePinningRoots(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Pinning referents of pinned handles in generation %u\n", condemned));

    // pin objects pointed to by pinning handles
    uint32_t types[2] = {HNDTYPE_PINNED, HNDTYPE_ASYNCPINNED};
    uint32_t flags = sc->concurrent ? HNDGCF_ASYNC : HNDGCF_NORMAL;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber((ScanContext*) sc)];
                if (hTable)
                {
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
                    if (g_fEnableARM)
                    {
                        sc->pCurrentDomain = SystemDomain::GetAppDomainAtIndex(HndGetHandleTableADIndex(hTable));
                    }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
                    HndScanHandlesForGC(hTable, PinObject, uintptr_t(sc), uintptr_t(fn), types, _countof(types), condemned, maxgen, flags);
                }
            }
        walk = walk->pNext;
    }

    // pin objects pointed to by variable handles whose dynamic type is VHT_PINNED
    TraceVariableHandles(PinObject, uintptr_t(sc), uintptr_t(fn), VHT_PINNED, condemned, maxgen, flags);
}


void Ref_TraceNormalRoots(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Promoting referents of strong handles in generation %u\n", condemned));

    // promote objects pointed to by strong handles
    // during ephemeral GCs we also want to promote the ones pointed to by sizedref handles.
    uint32_t types[2] = {HNDTYPE_STRONG, HNDTYPE_SIZEDREF};
    uint32_t uTypeCount = (((condemned >= maxgen) && !GCHeap::GetGCHeap()->IsConcurrentGCInProgress()) ? 1 : _countof(types));
    uint32_t flags = (sc->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                if (hTable)
                {
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
                    if (g_fEnableARM)
                    {
                        sc->pCurrentDomain = SystemDomain::GetAppDomainAtIndex(HndGetHandleTableADIndex(hTable));
                    }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING

                    HndScanHandlesForGC(hTable, PromoteObject, uintptr_t(sc), uintptr_t(fn), types, uTypeCount, condemned, maxgen, flags);
                }
            }
        walk = walk->pNext;
    }

    // promote objects pointed to by variable handles whose dynamic type is VHT_STRONG
    TraceVariableHandles(PromoteObject, uintptr_t(sc), uintptr_t(fn), VHT_STRONG, condemned, maxgen, flags);

#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
    // don't scan ref-counted handles during concurrent phase as the clean-up of CCWs can race with AD unload and cause AV's
    if (!sc->concurrent)
    {
        // promote ref-counted handles
        uint32_t type = HNDTYPE_REFCOUNTED;

        walk = &g_HandleTableMap;
        while (walk) {
            for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
                if (walk->pBuckets[i] != NULL)
                {
                    HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                    if (hTable)
                        HndScanHandlesForGC(hTable, PromoteRefCounted, uintptr_t(sc), uintptr_t(fn), &type, 1, condemned, maxgen, flags );
                }
            walk = walk->pNext;
        }
    }
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
}

#ifdef FEATURE_COMINTEROP

void Ref_TraceRefCountHandles(HANDLESCANPROC callback, uintptr_t lParam1, uintptr_t lParam2)
{
    int max_slots = getNumberOfSlots();
    uint32_t handleType = HNDTYPE_REFCOUNTED;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk)
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                for (int j = 0; j < max_slots; j++)
                {
                    HHANDLETABLE hTable = walk->pBuckets[i]->pTable[j];
                    if (hTable)
                        HndEnumHandles(hTable, &handleType, 1, callback, lParam1, lParam2, false);
                }
            }
        }
        walk = walk->pNext;
    }
}

#endif



void Ref_CheckReachable(uint32_t condemned, uint32_t maxgen, uintptr_t lp1)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Checking reachability of referents of long-weak handles in generation %u\n", condemned));

    // these are the handle types that need to be checked
    uint32_t types[] =
    {
        HNDTYPE_WEAK_LONG,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
    };

    // check objects pointed to by short weak handles
    uint32_t flags = (((ScanContext*) lp1)->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;
    int uCPUindex = getSlotNumber((ScanContext*) lp1);

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
            if (walk->pBuckets[i] != NULL)
           {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                if (hTable)
                    HndScanHandlesForGC(hTable, CheckPromoted, lp1, 0, types, _countof(types), condemned, maxgen, flags);
        }
        }
        walk = walk->pNext;
    }

    // check objects pointed to by variable handles whose dynamic type is VHT_WEAK_LONG
    TraceVariableHandles(CheckPromoted, lp1, 0, VHT_WEAK_LONG, condemned, maxgen, flags);
}

//
// Dependent handles manages the relationship between primary and secondary objects, where the lifetime of
// the secondary object is dependent upon that of the primary. The handle itself holds the primary instance,
// while the extra handle info holds the secondary object. The secondary object should always be promoted
// when the primary is, and the handle should be cleared if the primary is not promoted. Can't use ordinary
// strong handle to refer to the secondary as this could case a cycle in the graph if the secondary somehow
// pointed back to the primary. Can't use weak handle because that would not keep the secondary object alive.
//
// The result is that a dependenHandle has the EFFECT of 
//    * long weak handles in both the primary and secondary objects
//    * a strong reference from the primary object to the secondary one
//
// Dependent handles are currently used for
// 
//    * managing fields added to EnC classes, where the handle itself holds the this pointer and the
//        secondary object represents the new field that was added.
//    * it is exposed to managed code (as System.Runtime.CompilerServices.DependentHandle) and is used in the
//        implementation of ConditionWeakTable.
//

// Retrieve the dependent handle context associated with the current GC scan context.
DhContext *Ref_GetDependentHandleContext(ScanContext* sc)
{
    WRAPPER_NO_CONTRACT;
    return &g_pDependentHandleContexts[getSlotNumber(sc)];
}

// Scan the dependent handle table promoting any secondary object whose associated primary object is promoted.
//
// Multiple scans may be required since (a) secondary promotions made during one scan could cause the primary
// of another handle to be promoted and (b) the GC may not have marked all promoted objects at the time it
// initially calls us.
//
// Returns true if any promotions resulted from this scan.
bool Ref_ScanDependentHandlesForPromotion(DhContext *pDhContext)
{
    LOG((LF_GC, LL_INFO10000, "Checking liveness of referents of dependent handles in generation %u\n", pDhContext->m_iCondemned));
    uint32_t type = HNDTYPE_DEPENDENT;
    uint32_t flags = (pDhContext->m_pScanContext->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;
    flags |= HNDGCF_EXTRAINFO;

    // Keep a note of whether we promoted anything over the entire scan (not just the last iteration). We need
    // to return this data since under server GC promotions from this table may cause further promotions in
    // tables handled by other threads.
    bool fAnyPromotions = false;

    // Keep rescanning the table while both the following conditions are true:
    //  1) There's at least primary object left that could have been promoted.
    //  2) We performed at least one secondary promotion (which could have caused a primary promotion) on the
    //     last scan.
    // Note that even once we terminate the GC may call us again (because it has caused more objects to be
    // marked as promoted). But we scan in a loop here anyway because it is cheaper for us to loop than the GC
    // (especially on server GC where each external cycle has to be synchronized between GC worker threads).
    do
    {
        // Assume the conditions for re-scanning are both false initially. The scan callback below
        // (PromoteDependentHandle) will set the relevant flag on the first unpromoted primary it sees or
        // secondary promotion it performs.
        pDhContext->m_fUnpromotedPrimaries = false;
        pDhContext->m_fPromoted = false;

        HandleTableMap *walk = &g_HandleTableMap;
        while (walk) 
        {
            for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            {
                if (walk->pBuckets[i] != NULL)
                {
                    HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(pDhContext->m_pScanContext)];
                    if (hTable)
                    {
                        HndScanHandlesForGC(hTable,
                                            PromoteDependentHandle,
                                            uintptr_t(pDhContext->m_pScanContext),
                                            uintptr_t(pDhContext->m_pfnPromoteFunction),
                                            &type, 1,
                                            pDhContext->m_iCondemned,
                                            pDhContext->m_iMaxGen,
                                            flags );
                    }
                }
            }
            walk = walk->pNext;
        }

        if (pDhContext->m_fPromoted)
            fAnyPromotions = true;

    } while (pDhContext->m_fUnpromotedPrimaries && pDhContext->m_fPromoted);

    return fAnyPromotions;
}

// Perform a scan of dependent handles for the purpose of clearing any that haven't had their primary
// promoted.
void Ref_ScanDependentHandlesForClearing(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    LOG((LF_GC, LL_INFO10000, "Clearing dead dependent handles in generation %u\n", condemned));
    uint32_t type = HNDTYPE_DEPENDENT;
    uint32_t flags = (sc->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;
    flags |= HNDGCF_EXTRAINFO;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) 
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                if (hTable)
                {
                    HndScanHandlesForGC(hTable, ClearDependentHandle, uintptr_t(sc), uintptr_t(fn), &type, 1, condemned, maxgen, flags );
                }
            }
        }
        walk = walk->pNext;
    }
}

// Perform a scan of dependent handles for the purpose of updating handles to track relocated objects.
void Ref_ScanDependentHandlesForRelocation(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    LOG((LF_GC, LL_INFO10000, "Relocating moved dependent handles in generation %u\n", condemned));
    uint32_t type = HNDTYPE_DEPENDENT;
    uint32_t flags = (sc->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;
    flags |= HNDGCF_EXTRAINFO;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) 
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                if (hTable)
                {
                    HndScanHandlesForGC(hTable, UpdateDependentHandle, uintptr_t(sc), uintptr_t(fn), &type, 1, condemned, maxgen, flags );
                }
            }
        }
        walk = walk->pNext;
    }
}

/*
  loop scan version of TraceVariableHandles for single-thread-managed Ref_* functions
  should be kept in sync with the code above
*/
void TraceDependentHandlesBySingleThread(HANDLESCANPROC pfnTrace, uintptr_t lp1, uint32_t condemned, uint32_t maxgen, uint32_t flags)
{
    WRAPPER_NO_CONTRACT;

    // set up to scan variable handles with the specified mask and trace function
    uint32_t type = HNDTYPE_DEPENDENT;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                // this is the one of Ref_* function performed by single thread in MULTI_HEAPS case, so we need to loop through all HT of the bucket
                for (int uCPUindex=0; uCPUindex < getNumberOfSlots(); uCPUindex++)
                {
                    HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                    if (hTable)
                        HndScanHandlesForGC(hTable, TraceDependentHandle,
                                    lp1, (uintptr_t)pfnTrace, &type, 1, condemned, maxgen, HNDGCF_EXTRAINFO | flags);
                }
            }
        walk = walk->pNext;
    }
}


// We scan handle tables by their buckets (ie, AD index). We could get into the situation where
// the AD indices are not very compacted (for example if we have just unloaded ADs and their 
// indices haven't been reused yet) and we could be scanning them in an unbalanced fashion. 
// Consider using an array to represent the compacted form of all AD indices exist for the 
// sized ref handles. 
void ScanSizedRefByAD(uint32_t maxgen, HANDLESCANPROC scanProc, ScanContext* sc, Ref_promote_func* fn, uint32_t flags)
{
    HandleTableMap *walk = &g_HandleTableMap;
    uint32_t type = HNDTYPE_SIZEDREF;
    int uCPUindex = getSlotNumber(sc);
    int n_slots = GCHeap::GetGCHeap()->GetNumberOfHeaps();

    while (walk)
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                ADIndex adIndex = HndGetHandleTableADIndex(walk->pBuckets[i]->pTable[0]);
                if ((adIndex.m_dwIndex % n_slots) == (uint32_t)uCPUindex)
                {
                    for (int index = 0; index < n_slots; index++)
                    {
                        HHANDLETABLE hTable = walk->pBuckets[i]->pTable[index];
                        if (hTable)
                        {
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
                            if (g_fEnableARM)
                            {
                                sc->pCurrentDomain = SystemDomain::GetAppDomainAtIndex(adIndex);
                            }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING
                            HndScanHandlesForGC(hTable, scanProc, uintptr_t(sc), uintptr_t(fn), &type, 1, maxgen, maxgen, flags);
                        }
                    }
                }
            }
        }
        walk = walk->pNext;
    }
}

void ScanSizedRefByCPU(uint32_t maxgen, HANDLESCANPROC scanProc, ScanContext* sc, Ref_promote_func* fn, uint32_t flags)
{
    HandleTableMap *walk = &g_HandleTableMap;
    uint32_t type = HNDTYPE_SIZEDREF;
    int uCPUindex = getSlotNumber(sc);

    while (walk) 
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
        	if (walk->pBuckets[i] != NULL)
	        {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                if (hTable)
                {
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
                    if (g_fEnableARM)
                    {
                        sc->pCurrentDomain = SystemDomain::GetAppDomainAtIndex(HndGetHandleTableADIndex(hTable));
                    }
#endif //FEATURE_APPDOMAIN_RESOURCE_MONITORING

                    HndScanHandlesForGC(hTable, scanProc, uintptr_t(sc), uintptr_t(fn), &type, 1, maxgen, maxgen, flags);
                }
            }
        }
        walk = walk->pNext;
    }
}

void Ref_ScanSizedRefHandles(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    LOG((LF_GC, LL_INFO10000, "Scanning SizedRef handles to in generation %u\n", condemned));
    UNREFERENCED_PARAMETER(condemned);
    _ASSERTE (condemned == maxgen);
    uint32_t flags = (sc->concurrent ? HNDGCF_ASYNC : HNDGCF_NORMAL) | HNDGCF_EXTRAINFO;

    ScanSizedRefByCPU(maxgen, CalculateSizedRefSize, sc, fn, flags);
}

void Ref_CheckAlive(uint32_t condemned, uint32_t maxgen, uintptr_t lp1)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Checking liveness of referents of short-weak handles in generation %u\n", condemned));

    // perform a multi-type scan that checks for unreachable objects
    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT
#ifdef FEATURE_COMINTEROP
        , HNDTYPE_WEAK_WINRT
#endif // FEATURE_COMINTEROP
    };
    uint32_t flags = (((ScanContext*) lp1)->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;

    int uCPUindex = getSlotNumber((ScanContext*) lp1);
    HandleTableMap *walk = &g_HandleTableMap;
    while (walk)
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                if (hTable)
                    HndScanHandlesForGC(hTable, CheckPromoted, lp1, 0, types, _countof(types), condemned, maxgen, flags);
            }
        }
        walk = walk->pNext;
    }
    // check objects pointed to by variable handles whose dynamic type is VHT_WEAK_SHORT
    TraceVariableHandles(CheckPromoted, lp1, 0, VHT_WEAK_SHORT, condemned, maxgen, flags);
}

static VOLATILE(int32_t) uCount = 0;

// NOTE: Please: if you update this function, update the very similar profiling function immediately below!!!
void Ref_UpdatePointers(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    WRAPPER_NO_CONTRACT;

    // For now, treat the syncblock as if it were short weak handles.  <REVISIT_TODO>Later, get
    // the benefits of fast allocation / free & generational awareness by supporting
    // the SyncTable as a new block type.
    // @TODO cwb: wait for compelling performance measurements.</REVISIT_TODO>
    BOOL bDo = TRUE;

    if (GCHeap::IsServerHeap()) 
    {
        bDo = (Interlocked::Increment(&uCount) == 1);
        Interlocked::CompareExchange (&uCount, 0, GCHeap::GetGCHeap()->GetNumberOfHeaps());
        _ASSERTE (uCount <= GCHeap::GetGCHeap()->GetNumberOfHeaps());
    }

    if (bDo)   
        GCToEEInterface::SyncBlockCacheWeakPtrScan(&UpdatePointer, uintptr_t(sc), uintptr_t(fn));

    LOG((LF_GC, LL_INFO10000, "Updating pointers to referents of non-pinning handles in generation %u\n", condemned));

    // these are the handle types that need their pointers updated
    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT,
        HNDTYPE_WEAK_LONG,
        HNDTYPE_STRONG,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
#ifdef FEATURE_COMINTEROP
        HNDTYPE_WEAK_WINRT,
#endif // FEATURE_COMINTEROP
        HNDTYPE_SIZEDREF,
    };

    // perform a multi-type scan that updates pointers
    uint32_t flags = (sc->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                if (hTable)
                    HndScanHandlesForGC(hTable, UpdatePointer, uintptr_t(sc), uintptr_t(fn), types, _countof(types), condemned, maxgen, flags);
            }
        walk = walk->pNext;
    }

    // update pointers in variable handles whose dynamic type is VHT_WEAK_SHORT, VHT_WEAK_LONG or VHT_STRONG
    TraceVariableHandles(UpdatePointer, uintptr_t(sc), uintptr_t(fn), VHT_WEAK_SHORT | VHT_WEAK_LONG | VHT_STRONG, condemned, maxgen, flags);
}

#if defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)

// Please update this if you change the Ref_UpdatePointers function above.
void Ref_ScanPointersForProfilerAndETW(uint32_t maxgen, uintptr_t lp1)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC | LF_CORPROF, LL_INFO10000, "Scanning all handle roots for profiler.\n"));

    // Don't scan the sync block because they should not be reported. They are weak handles only

    // <REVISIT_TODO>We should change the following to not report weak either
    // these are the handle types that need their pointers updated</REVISIT_TODO>
    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT,
        HNDTYPE_WEAK_LONG,
        HNDTYPE_STRONG,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
#ifdef FEATURE_COMINTEROP
        HNDTYPE_WEAK_WINRT,
#endif // FEATURE_COMINTEROP
        HNDTYPE_PINNED,
//        HNDTYPE_VARIABLE,
        HNDTYPE_ASYNCPINNED,
        HNDTYPE_SIZEDREF,
    };

    uint32_t flags = HNDGCF_NORMAL;

    // perform a multi-type scan that updates pointers
    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
                // this is the one of Ref_* function performed by single thread in MULTI_HEAPS case, so we need to loop through all HT of the bucket
                for (int uCPUindex=0; uCPUindex < getNumberOfSlots(); uCPUindex++)
                {
                    HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                    if (hTable)
                        HndScanHandlesForGC(hTable, &ScanPointerForProfilerAndETW, lp1, 0, types, _countof(types), maxgen, maxgen, flags);
                }
        walk = walk->pNext;
    }

    // update pointers in variable handles whose dynamic type is VHT_WEAK_SHORT, VHT_WEAK_LONG or VHT_STRONG
    TraceVariableHandlesBySingleThread(&ScanPointerForProfilerAndETW, lp1, 0, VHT_WEAK_SHORT | VHT_WEAK_LONG | VHT_STRONG, maxgen, maxgen, flags);
}

void Ref_ScanDependentHandlesForProfilerAndETW(uint32_t maxgen, ProfilingScanContext * SC)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC | LF_CORPROF, LL_INFO10000, "Scanning dependent handles for profiler.\n"));

    uint32_t flags = HNDGCF_NORMAL;

    uintptr_t lp1 = (uintptr_t)SC;
    // we'll re-use pHeapId (which was either unused (0) or freed by EndRootReferences2
    // (-1)), so reset it to NULL
    _ASSERTE((*((size_t *)(&SC->pHeapId)) == (size_t)(-1)) ||
             (*((size_t *)(&SC->pHeapId)) == (size_t)(0)));
    SC->pHeapId = NULL;
    TraceDependentHandlesBySingleThread(&ScanPointerForProfilerAndETW, lp1, maxgen, maxgen, flags);
}

#endif // defined(GC_PROFILING) || defined(FEATURE_EVENT_TRACE)

// Callback to enumerate all object references held in handles.
void CALLBACK ScanPointer(_UNCHECKED_OBJECTREF *pObjRef, uintptr_t *pExtraInfo, uintptr_t lp1, uintptr_t lp2)
{
    WRAPPER_NO_CONTRACT;
    UNREFERENCED_PARAMETER(pExtraInfo);

    Object **pRef = (Object **)pObjRef;
    _ASSERTE(lp2);
    promote_func* callback = (promote_func*)lp2;
    callback(pRef, (ScanContext *)lp1, 0);
}

// Enumerate all object references held by any of the handle tables in the system.
void Ref_ScanPointers(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    WRAPPER_NO_CONTRACT;

    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT,
        HNDTYPE_WEAK_LONG,
        HNDTYPE_STRONG,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
        HNDTYPE_PINNED,
        HNDTYPE_ASYNCPINNED,
        HNDTYPE_SIZEDREF,
    };

    uint32_t flags = HNDGCF_NORMAL;

    // perform a multi-type scan that enumerates pointers
    for (HandleTableMap * walk = &g_HandleTableMap; 
         walk != nullptr; 
         walk = walk->pNext)
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                // this is the one of Ref_* function performed by single thread in MULTI_HEAPS case, so we need to loop through all HT of the bucket
                for (int uCPUindex = 0; uCPUindex < getNumberOfSlots(); uCPUindex++)
                {
                    HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                    if (hTable)
                        HndScanHandlesForGC(hTable, &ScanPointer, uintptr_t(sc), uintptr_t(fn), types, _countof(types), condemned, maxgen, flags);
                }
            }
        }
    }

    // enumerate pointers in variable handles whose dynamic type is VHT_WEAK_SHORT, VHT_WEAK_LONG or VHT_STRONG
    TraceVariableHandlesBySingleThread(&ScanPointer, uintptr_t(sc), uintptr_t(fn), VHT_WEAK_SHORT | VHT_WEAK_LONG | VHT_STRONG, condemned, maxgen, flags);
}

void Ref_UpdatePinnedPointers(uint32_t condemned, uint32_t maxgen, ScanContext* sc, Ref_promote_func* fn)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Updating pointers to referents of pinning handles in generation %u\n", condemned));

    // these are the handle types that need their pointers updated
    uint32_t types[2] = {HNDTYPE_PINNED, HNDTYPE_ASYNCPINNED};
    uint32_t flags = (sc->concurrent) ? HNDGCF_ASYNC : HNDGCF_NORMAL;

    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                if (hTable)
                    HndScanHandlesForGC(hTable, UpdatePointerPinned, uintptr_t(sc), uintptr_t(fn), types, _countof(types), condemned, maxgen, flags); 
            }
        walk = walk->pNext;
    }

    // update pointers in variable handles whose dynamic type is VHT_PINNED
    TraceVariableHandles(UpdatePointerPinned, uintptr_t(sc), uintptr_t(fn), VHT_PINNED, condemned, maxgen, flags);
}


void Ref_AgeHandles(uint32_t condemned, uint32_t maxgen, uintptr_t lp1)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Aging handles in generation %u\n", condemned));

    // these are the handle types that need their ages updated
    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT,
        HNDTYPE_WEAK_LONG,

        HNDTYPE_STRONG,

        HNDTYPE_PINNED,
        HNDTYPE_VARIABLE,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
#ifdef FEATURE_COMINTEROP
        HNDTYPE_WEAK_WINRT,
#endif // FEATURE_COMINTEROP
        HNDTYPE_ASYNCPINNED,
        HNDTYPE_SIZEDREF,
    };

    int uCPUindex = getSlotNumber((ScanContext*) lp1);
    // perform a multi-type scan that ages the handles
    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                if (hTable)
                    HndScanHandlesForGC(hTable, NULL, 0, 0, types, _countof(types), condemned, maxgen, HNDGCF_AGE);
            }
        walk = walk->pNext;
    }
}


void Ref_RejuvenateHandles(uint32_t condemned, uint32_t maxgen, uintptr_t lp1)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Rejuvenating handles.\n"));

    // these are the handle types that need their ages updated
    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT,
        HNDTYPE_WEAK_LONG,


        HNDTYPE_STRONG,

        HNDTYPE_PINNED,
        HNDTYPE_VARIABLE,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
#ifdef FEATURE_COMINTEROP
        HNDTYPE_WEAK_WINRT,
#endif // FEATURE_COMINTEROP
        HNDTYPE_ASYNCPINNED,
        HNDTYPE_SIZEDREF,
    };

    int uCPUindex = getSlotNumber((ScanContext*) lp1);
    // reset the ages of these handles
    HandleTableMap *walk = &g_HandleTableMap;
    while (walk) {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[uCPUindex];
                if (hTable)
                    HndResetAgeMap(hTable, types, _countof(types), condemned, maxgen, HNDGCF_NORMAL);
            }
        walk = walk->pNext;
    }
}

void Ref_VerifyHandleTable(uint32_t condemned, uint32_t maxgen, ScanContext* sc)
{
    WRAPPER_NO_CONTRACT;

    LOG((LF_GC, LL_INFO10000, "Verifying handles.\n"));

    // these are the handle types that need to be verified
    uint32_t types[] =
    {
        HNDTYPE_WEAK_SHORT,
        HNDTYPE_WEAK_LONG,


        HNDTYPE_STRONG,

        HNDTYPE_PINNED,
        HNDTYPE_VARIABLE,
#if defined(FEATURE_COMINTEROP) || defined(FEATURE_REDHAWK)
        HNDTYPE_REFCOUNTED,
#endif // FEATURE_COMINTEROP || FEATURE_REDHAWK
#ifdef FEATURE_COMINTEROP
        HNDTYPE_WEAK_WINRT,
#endif // FEATURE_COMINTEROP
        HNDTYPE_ASYNCPINNED,
        HNDTYPE_SIZEDREF,
        HNDTYPE_DEPENDENT,
    };

    // verify these handles
    HandleTableMap *walk = &g_HandleTableMap;
    while (walk)
    {
        for (uint32_t i = 0; i < INITIAL_HANDLE_TABLE_ARRAY_SIZE; i ++)
        {
            if (walk->pBuckets[i] != NULL)
            {
                HHANDLETABLE hTable = walk->pBuckets[i]->pTable[getSlotNumber(sc)];
                if (hTable)
                    HndVerifyTable(hTable, types, _countof(types), condemned, maxgen, HNDGCF_NORMAL);
            }
        }
        walk = walk->pNext;
    }
}

int GetCurrentThreadHomeHeapNumber()
{
    WRAPPER_NO_CONTRACT;

    if (!GCHeap::IsGCHeapInitialized())
        return 0;
    return GCHeap::GetGCHeap()->GetHomeHeapNumber();
}

bool HandleTableBucket::Contains(OBJECTHANDLE handle)
{
    LIMITED_METHOD_CONTRACT;

    if (NULL == handle)
    {
        return FALSE;
    }
    
    HHANDLETABLE hTable = HndGetHandleTable(handle);
    for (int uCPUindex=0; uCPUindex < GCHeap::GetGCHeap()->GetNumberOfHeaps(); uCPUindex++)
    {
        if (hTable == this->pTable[uCPUindex]) 
        {
            return TRUE;
        }
    }
    return FALSE;
}

void DestroySizedRefHandle(OBJECTHANDLE handle)
{ 
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        SO_TOLERANT;
        MODE_ANY;
    }
    CONTRACTL_END;

    HHANDLETABLE hTable = HndGetHandleTable(handle);
    HndDestroyHandle(hTable , HNDTYPE_SIZEDREF, handle);
    AppDomain* pDomain = SystemDomain::GetAppDomainAtIndex(HndGetHandleTableADIndex(hTable));
    pDomain->DecNumSizedRefHandles();
}

#ifdef FEATURE_COMINTEROP

void DestroyWinRTWeakHandle(OBJECTHANDLE handle)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        CAN_TAKE_LOCK;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    // Release the WinRT weak reference if we have one.  We're assuming that this will not reenter the
    // runtime, since if we are pointing at a managed object, we should not be using a HNDTYPE_WEAK_WINRT
    // but rather a HNDTYPE_WEAK_SHORT or HNDTYPE_WEAK_LONG.
    IWeakReference* pWinRTWeakReference = reinterpret_cast<IWeakReference*>(HndGetHandleExtraInfo(handle));
    if (pWinRTWeakReference != NULL)
    {
        pWinRTWeakReference->Release();
    }

    HndDestroyHandle(HndGetHandleTable(handle), HNDTYPE_WEAK_WINRT, handle);
}

#endif // FEATURE_COMINTEROP

#endif // !DACCESS_COMPILE

OBJECTREF GetDependentHandleSecondary(OBJECTHANDLE handle)
{ 
    WRAPPER_NO_CONTRACT;

    return UNCHECKED_OBJECTREF_TO_OBJECTREF((_UNCHECKED_OBJECTREF)HndGetHandleExtraInfo(handle));
}