summaryrefslogtreecommitdiff
path: root/src/vm/comsynchronizable.cpp
blob: 772163aff29160538570579ab11b43520cea7d0e (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
// 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.


/*============================================================
**
** Header: COMSynchronizable.cpp
**
** Purpose: Native methods on System.SynchronizableObject
**          and its subclasses.
**
**
===========================================================*/

#include "common.h"

#include <object.h>
#include "threads.h"
#include "excep.h"
#include "vars.hpp"
#include "field.h"
#include "comsynchronizable.h"
#include "dbginterface.h"
#include "comdelegate.h"
#include "eeconfig.h"
#include "callhelpers.h"
#include "appdomain.hpp"
#include "appdomain.inl"

#ifndef FEATURE_PAL
#include "utilcode.h"
#endif

// To include definition of CAPTURE_BUCKETS_AT_TRANSITION
#include "exstate.h"

// The two threads need to communicate some information.  Any object references must
// be declared to GC.
struct SharedState
{
    OBJECTHANDLE    m_Threadable;
    OBJECTHANDLE    m_ThreadStartArg;
    Thread         *m_Internal;

    SharedState(OBJECTREF threadable, OBJECTREF threadStartArg, Thread *internal)
    {
        CONTRACTL
        {
            GC_NOTRIGGER;
            THROWS;  // From CreateHandle()
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;
        AppDomainFromIDHolder ad(internal->GetKickOffDomainId(), TRUE);
        if (ad.IsUnloaded())
            COMPlusThrow(kAppDomainUnloadedException);

        m_Threadable = ad->CreateHandle(threadable);
        m_ThreadStartArg = ad->CreateHandle(threadStartArg);

        m_Internal = internal;
    }

    ~SharedState()
    {
        CONTRACTL
        {
            GC_NOTRIGGER;
            NOTHROW;
            MODE_COOPERATIVE;
        }
        CONTRACTL_END;

        // It's important to have no GC rendez-vous point between the checking and the clean-up below.
        // The three handles below could be in an appdomain which is just starting to be unloaded, or an appdomain
        // which has been unloaded already.  Thus, we need to check whether the appdomain is still valid before
        // we do the clean-up.  Since we suspend all runtime threads when we try to do the unload, there will be no
        // race condition between the checking and the clean-up as long as this thread cannot be suspended in between.
        AppDomainFromIDHolder ad(m_Internal->GetKickOffDomainId(), TRUE);
        if (!ad.IsUnloaded())
        {
            DestroyHandle(m_Threadable);
            DestroyHandle(m_ThreadStartArg);
        }
    }
};


// For the following helpers, we make no attempt to synchronize.  The app developer
// is responsible for managing his own race conditions.
//
// Note: if the internal Thread is NULL, this implies that the exposed object has
//       finalized and then been resurrected.
static inline BOOL ThreadNotStarted(Thread *t)
{
    WRAPPER_NO_CONTRACT;
    return (t && t->IsUnstarted() && !t->HasValidThreadHandle());
}

static inline BOOL ThreadIsRunning(Thread *t)
{
    WRAPPER_NO_CONTRACT;
    return (t &&
            (t->m_State & (Thread::TS_ReportDead|Thread::TS_Dead)) == 0 &&
            (t->HasValidThreadHandle()));
}

static inline BOOL ThreadIsDead(Thread *t)
{
    WRAPPER_NO_CONTRACT;
    return (t == 0 || t->IsDead());
}


// Map our exposed notion of thread priorities into the enumeration that NT uses.
static INT32 MapToNTPriority(INT32 ours)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        THROWS;
        MODE_ANY;
    }
    CONTRACTL_END;

    INT32   NTPriority = 0;

    switch (ours)
    {
    case ThreadNative::PRIORITY_LOWEST:
        NTPriority = THREAD_PRIORITY_LOWEST;
        break;

    case ThreadNative::PRIORITY_BELOW_NORMAL:
        NTPriority = THREAD_PRIORITY_BELOW_NORMAL;
        break;

    case ThreadNative::PRIORITY_NORMAL:
        NTPriority = THREAD_PRIORITY_NORMAL;
        break;

    case ThreadNative::PRIORITY_ABOVE_NORMAL:
        NTPriority = THREAD_PRIORITY_ABOVE_NORMAL;
        break;

    case ThreadNative::PRIORITY_HIGHEST:
        NTPriority = THREAD_PRIORITY_HIGHEST;
        break;

    default:
        COMPlusThrow(kArgumentOutOfRangeException, W("Argument_InvalidFlag"));
    }
    return NTPriority;
}


// Map to our exposed notion of thread priorities from the enumeration that NT uses.
INT32 MapFromNTPriority(INT32 NTPriority)
{
    LIMITED_METHOD_CONTRACT;

    INT32   ours = 0;

    if (NTPriority <= THREAD_PRIORITY_LOWEST)
    {
        // managed code does not support IDLE.  Map it to PRIORITY_LOWEST.
        ours = ThreadNative::PRIORITY_LOWEST;
    }
    else if (NTPriority >= THREAD_PRIORITY_HIGHEST)
    {
        ours = ThreadNative::PRIORITY_HIGHEST;
    }
    else if (NTPriority == THREAD_PRIORITY_BELOW_NORMAL)
    {
        ours = ThreadNative::PRIORITY_BELOW_NORMAL;
    }
    else if (NTPriority == THREAD_PRIORITY_NORMAL)
    {
        ours = ThreadNative::PRIORITY_NORMAL;
    }
    else if (NTPriority == THREAD_PRIORITY_ABOVE_NORMAL)
    {
        ours = ThreadNative::PRIORITY_ABOVE_NORMAL;
    }
    else
    {
        _ASSERTE (!"not supported priority");
        ours = ThreadNative::PRIORITY_NORMAL;
    }
    return ours;
}


void ThreadNative::KickOffThread_Worker(LPVOID ptr)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    KickOffThread_Args *args = (KickOffThread_Args *) ptr;
    _ASSERTE(ObjectFromHandle(args->share->m_Threadable) != NULL);
    args->retVal = 0;

    // we are saving the delagate and result primarily for debugging
    struct _gc
    {
        OBJECTREF orThreadStartArg;
        OBJECTREF orDelegate;
        OBJECTREF orResult;
        OBJECTREF orThread;
    } gc;
    ZeroMemory(&gc, sizeof(gc));

    Thread *pThread;
    pThread = GetThread();
    _ASSERTE(pThread);
    GCPROTECT_BEGIN(gc);
    BEGIN_SO_INTOLERANT_CODE(pThread);

    gc.orDelegate = ObjectFromHandle(args->share->m_Threadable);
    gc.orThreadStartArg = ObjectFromHandle(args->share->m_ThreadStartArg);

    // We cannot call the Delegate Invoke method directly from ECall.  The
    //  stub has not been created for non multicast delegates.  Instead, we
    //  will invoke the Method on the OR stored in the delegate directly.
    // If there are changes to the signature of the ThreadStart delegate
    //  this code will need to change.  I've noted this in the Thread start
    //  class.

    delete args->share;
    args->share = 0;

    MethodDesc *pMeth = ((DelegateEEClass*)( gc.orDelegate->GetMethodTable()->GetClass() ))->GetInvokeMethod();
    _ASSERTE(pMeth);
    MethodDescCallSite invokeMethod(pMeth, &gc.orDelegate);

    if (MscorlibBinder::IsClass(gc.orDelegate->GetMethodTable(), CLASS__PARAMETERIZEDTHREADSTART))
    {
        //Parameterized ThreadStart
        ARG_SLOT arg[2];

        arg[0] = ObjToArgSlot(gc.orDelegate);
        arg[1]=ObjToArgSlot(gc.orThreadStartArg);
        invokeMethod.Call(arg);
    }
    else
    {
        //Simple ThreadStart
        ARG_SLOT arg[1];

        arg[0] = ObjToArgSlot(gc.orDelegate);
        invokeMethod.Call(arg);
    }
	STRESS_LOG2(LF_SYNC, LL_INFO10, "Managed thread exiting normally for delegate %p Type %pT\n", OBJECTREFToObject(gc.orDelegate), (size_t) gc.orDelegate->GetMethodTable());

    END_SO_INTOLERANT_CODE;
    GCPROTECT_END();
}

// Helper to avoid two EX_TRY/EX_CATCH blocks in one function
static void PulseAllHelper(Thread* pThread)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        DISABLED(NOTHROW);
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    EX_TRY
    {
        // GetExposedObject() will either throw, or we have a valid object.  Note
        // that we re-acquire it each time, since it may move during calls.
        pThread->GetExposedObject()->EnterObjMonitor();
        pThread->GetExposedObject()->PulseAll();
        pThread->GetExposedObject()->LeaveObjMonitor();
    }
    EX_CATCH
    {
        // just keep going...
    }
    EX_END_CATCH(SwallowAllExceptions)
}

// When an exposed thread is started by Win32, this is where it starts.
ULONG WINAPI ThreadNative::KickOffThread(void* pass)
{

    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_ANY;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    ULONG retVal = 0;
    // Before we do anything else, get Setup so that we have a real thread.

    // Our thread isn't setup yet, so we can't use the standard probe
    BEGIN_SO_INTOLERANT_CODE_NO_THROW_CHECK_THREAD(return E_FAIL);

    KickOffThread_Args args;
    // don't have a separate var becuase this can be updated in the worker
    args.share   = (SharedState *) pass;
    args.pThread = args.share->m_Internal;

    Thread* pThread = args.pThread;

    _ASSERTE(pThread != NULL);

    BOOL ok = TRUE;

    {
        EX_TRY
        {
            CExecutionEngine::CheckThreadState(0);
        }
        EX_CATCH
        {
            // OOM might be thrown from CheckThreadState, so it's important
            // that we don't rethrow it; if we do then the process will die
            // because there are no installed handlers at this point, so
            // swallow the exception.  this will set the thread's state to
            // FailStarted which will result in a ThreadStartException being
            // thrown from the thread that attempted to start this one.
            if (!GET_EXCEPTION()->IsTransient() && !SwallowUnhandledExceptions())
                EX_RETHROW;
        }
        EX_END_CATCH(SwallowAllExceptions);
        if (CExecutionEngine::CheckThreadStateNoCreate(0) == NULL)
        {
            // We can not 
            pThread->SetThreadState(Thread::TS_FailStarted);
            pThread->DetachThread(FALSE);
            // !!! Do not touch any field of Thread object.  The Thread object is subject to delete
            // !!! after DetachThread call.
            ok = FALSE;
        }
    }

    if (ok)
    {
        ok = pThread->HasStarted();
    }

    if (ok)
    {
        // Do not swallow the unhandled exception here
        //

        // Fire ETW event to correlate with the thread that created current thread
        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, ThreadRunning))
            FireEtwThreadRunning(pThread, GetClrInstanceId());

        // We have a sticky problem here.
        //
        // Under some circumstances, the context of 'this' doesn't match the context
        // of the thread.  Today this can only happen if the thread is marked for an
        // STA.  If so, the delegate that is stored in the object may not be directly
        // suitable for invocation.  Instead, we need to call through a proxy so that
        // the correct context transitions occur.
        //
        // All the changes occur inside HasStarted(), which will switch this thread
        // over to a brand new STA as necessary.  We have to notice this happening, so
        // we can adjust the delegate we are going to invoke on.

        _ASSERTE(GetThread() == pThread);        // Now that it's started
        ManagedThreadBase::KickOff(pThread->GetKickOffDomainId(), KickOffThread_Worker, &args);

        // If TS_FailStarted is set then the args are deleted in ThreadNative::StartInner
        if ((args.share) && !pThread->HasThreadState(Thread::TS_FailStarted))
        {
            delete args.share;
        }

        PulseAllHelper(pThread);

        GCX_PREEMP_NO_DTOR();

        pThread->ClearThreadCPUGroupAffinity();

        DestroyThread(pThread);
    }

    END_SO_INTOLERANT_CODE;

    return retVal;
}


FCIMPL1(void, ThreadNative::Start, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_NOPOLL();

    StartInner(pThisUNSAFE);

    HELPER_METHOD_FRAME_END_POLL();
}
FCIMPLEND

// Start up a thread, which by now should be in the ThreadStore's Unstarted list.
void ThreadNative::StartInner(ThreadBaseObject* pThisUNSAFE)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    struct _gc
    {
        THREADBASEREF   pThis;
    } gc;

    gc.pThis       = (THREADBASEREF) pThisUNSAFE;

    GCPROTECT_BEGIN(gc);

    if (gc.pThis == NULL)
        COMPlusThrow(kNullReferenceException, W("NullReference_This"));

    Thread        *pNewThread = gc.pThis->GetInternal();
    if (pNewThread == NULL)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);

    _ASSERTE(GetThread() != NULL);          // Current thread wandered in!

    gc.pThis->EnterObjMonitor();

    EX_TRY
    {
        // Is the thread already started?  You can't restart a thread.
        if (!ThreadNotStarted(pNewThread))
        {
            COMPlusThrow(kThreadStateException, IDS_EE_THREADSTART_STATE);
        }

        OBJECTREF   threadable = gc.pThis->GetDelegate();
        OBJECTREF   threadStartArg = gc.pThis->GetThreadStartArg();
        gc.pThis->SetDelegate(NULL);
        gc.pThis->SetThreadStartArg(NULL);

        // This can never happen, because we construct it with a valid one and then
        // we never let you change it (because SetStart is private).
        _ASSERTE(threadable != NULL);

        // Allocate this away from our stack, so we can unwind without affecting
        // KickOffThread.  It is inside a GCFrame, so we can enable GC now.
        NewHolder<SharedState> share(new SharedState(threadable, threadStartArg, pNewThread));

        pNewThread->IncExternalCount();

        // Fire an ETW event to mark the current thread as the launcher of the new thread
        if (ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, ThreadCreating))
            FireEtwThreadCreating(pNewThread, GetClrInstanceId());

        // As soon as we create the new thread, it is eligible for suspension, etc.
        // So it gets transitioned to cooperative mode before this call returns to
        // us.  It is our duty to start it running immediately, so that GC isn't blocked.

        BOOL success = pNewThread->CreateNewThread(
                                        pNewThread->RequestedThreadStackSize() /* 0 stackSize override*/,
                                        KickOffThread, share);

        if (!success)
        {
            pNewThread->DecExternalCount(FALSE);
            COMPlusThrowOM();
        }

        // After we have established the thread handle, we can check m_Priority.
        // This ordering is required to eliminate the race condition on setting the
        // priority of a thread just as it starts up.
        pNewThread->SetThreadPriority(MapToNTPriority(gc.pThis->m_Priority));
        pNewThread->ChooseThreadCPUGroupAffinity();

        FastInterlockOr((ULONG *) &pNewThread->m_State, Thread::TS_LegalToJoin);

        DWORD   ret;
        ret = pNewThread->StartThread();

        // When running under a user mode native debugger there is a race
        // between the moment we've created the thread (in CreateNewThread) and 
        // the moment we resume it (in StartThread); the debugger may receive 
        // the "ct" (create thread) notification, and it will attempt to 
        // suspend/resume all threads in the process.  Now imagine the debugger
        // resumes this thread first, and only later does it try to resume the
        // newly created thread.  In these conditions our call to ResumeThread  
        // may come before the debugger's call to ResumeThread actually causing 
        // ret to equal 2.
        // We cannot use IsDebuggerPresent() in the condition below because the 
        // debugger may have been detached between the time it got the notification
        // and the moment we execute the test below.
        _ASSERTE(ret == 1 || ret == 2);

        {
            GCX_PREEMP();

            // Synchronize with HasStarted.
            YIELD_WHILE (!pNewThread->HasThreadState(Thread::TS_FailStarted) &&
                   pNewThread->HasThreadState(Thread::TS_Unstarted));
        }

        if (!pNewThread->HasThreadState(Thread::TS_FailStarted))
        {
            share.SuppressRelease();       // we have handed off ownership of the shared struct
        }
        else
        {
            share.Release();
            PulseAllHelper(pNewThread);
            pNewThread->HandleThreadStartupFailure();
        }
    }
    EX_CATCH
    {
        gc.pThis->LeaveObjMonitor();
        EX_RETHROW;
    }
    EX_END_CATCH_UNREACHABLE;
    
    gc.pThis->LeaveObjMonitor();

    GCPROTECT_END();
}

FCIMPL1(void, ThreadNative::Abort, ThreadBaseObject* pThis)
{
    FCALL_CONTRACT;

    if (pThis == NULL)
        FCThrowVoid(kNullReferenceException);

    THREADBASEREF thisRef(pThis);
    // We need to keep the managed Thread object alive so that we can call UserAbort on
    // unmanaged thread object.
    HELPER_METHOD_FRAME_BEGIN_1(thisRef);

    Thread *thread = thisRef->GetInternal();
    if (thread == NULL)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);
#ifdef _DEBUG
    DWORD testAbort = g_pConfig->GetHostTestThreadAbort();
    if (testAbort != 0) {
        thread->UserAbort(Thread::TAR_Thread, testAbort == 1 ? EEPolicy::TA_Safe : EEPolicy::TA_Rude, INFINITE, Thread::UAC_Normal);
    }
    else
#endif
        thread->UserAbort(Thread::TAR_Thread, EEPolicy::TA_V1Compatible, INFINITE, Thread::UAC_Normal);

    if (thread->CatchAtSafePoint())
        CommonTripThread();
    HELPER_METHOD_FRAME_END_POLL();
}
FCIMPLEND

FCIMPL1(void, ThreadNative::ResetAbort, ThreadBaseObject* pThis)
{
    FCALL_CONTRACT;

    _ASSERTE(pThis);
    VALIDATEOBJECT(pThis);

    Thread *thread = pThis->GetInternal();
    // We do not allow user to reset rude thread abort in MustRun code.
    if (thread && thread->IsRudeAbort())
    {
        return;
    }

    HELPER_METHOD_FRAME_BEGIN_NOPOLL();

    if (thread == NULL)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);
    thread->UserResetAbort(Thread::TAR_Thread);
    thread->ClearAborted();
    HELPER_METHOD_FRAME_END_POLL();
}
FCIMPLEND


// Note that you can manipulate the priority of a thread that hasn't started yet,
// or one that is running.  But you get an exception if you manipulate the priority
// of a thread that has died.
FCIMPL1(INT32, ThreadNative::GetPriority, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowRes(kNullReferenceException, W("NullReference_This"));

    // validate the handle
    if (ThreadIsDead(pThisUNSAFE->GetInternal()))
        FCThrowEx(kThreadStateException, IDS_EE_THREAD_DEAD_PRIORITY, NULL, NULL, NULL);

    return pThisUNSAFE->m_Priority;
}
FCIMPLEND

FCIMPL2(void, ThreadNative::SetPriority, ThreadBaseObject* pThisUNSAFE, INT32 iPriority)
{
    FCALL_CONTRACT;

    int     priority;
    Thread *thread;

    THREADBASEREF  pThis = (THREADBASEREF) pThisUNSAFE;
    HELPER_METHOD_FRAME_BEGIN_1(pThis);

    if (pThis==NULL)
    {
        COMPlusThrow(kNullReferenceException, W("NullReference_This"));
    }

    // translate the priority (validating as well)
    priority = MapToNTPriority(iPriority);  // can throw; needs a frame

    // validate the thread
    thread = pThis->GetInternal();

    if (ThreadIsDead(thread))
    {
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_DEAD_PRIORITY, NULL, NULL, NULL);
    }

    INT32 oldPriority = pThis->m_Priority;

    // Eliminate the race condition by establishing m_Priority before we check for if
    // the thread is running.  See ThreadNative::Start() for the other half.
    pThis->m_Priority = iPriority;

    if (!thread->SetThreadPriority(priority))
    {
        pThis->m_Priority = oldPriority;
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_PRIORITY_FAIL, NULL, NULL, NULL);
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

// This service can be called on unstarted and dead threads.  For unstarted ones, the
// next wait will be interrupted.  For dead ones, this service quietly does nothing.
FCIMPL1(void, ThreadNative::Interrupt, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowResVoid(kNullReferenceException, W("NullReference_This"));

    Thread  *thread = pThisUNSAFE->GetInternal();

    if (thread == 0)
        FCThrowExVoid(kThreadStateException, IDS_EE_THREAD_CANNOT_GET, NULL, NULL, NULL);

    HELPER_METHOD_FRAME_BEGIN_0();

    thread->UserInterrupt(Thread::TI_Interrupt);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

FCIMPL1(FC_BOOL_RET, ThreadNative::IsAlive, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowRes(kNullReferenceException, W("NullReference_This"));

    THREADBASEREF thisRef(pThisUNSAFE);
    BOOL ret = false;

    // Keep managed Thread object alive, since the native object's
    // lifetime is tied to the managed object's finalizer.  And with 
    // resurrection, it may be possible to get a dangling pointer here -
    // consider both protecting thisRef and setting the managed object's
    // Thread* to NULL in the GC's ScanForFinalization method.
    HELPER_METHOD_FRAME_BEGIN_RET_1(thisRef);

    Thread  *thread = thisRef->GetInternal();

    if (thread == 0)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);

    ret = ThreadIsRunning(thread);

    HELPER_METHOD_POLL();
    HELPER_METHOD_FRAME_END();

    FC_RETURN_BOOL(ret);
}
FCIMPLEND

FCIMPL2(FC_BOOL_RET, ThreadNative::Join, ThreadBaseObject* pThisUNSAFE, INT32 Timeout)
{
    FCALL_CONTRACT;

    BOOL            retVal = FALSE;
    THREADBASEREF   pThis   = (THREADBASEREF) pThisUNSAFE;

    HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);

    if (pThis==NULL)
        COMPlusThrow(kNullReferenceException, W("NullReference_This"));

    // validate the timeout
    if ((Timeout < 0) && (Timeout != INFINITE_TIMEOUT))
        COMPlusThrowArgumentOutOfRange(W("millisecondsTimeout"), W("ArgumentOutOfRange_NeedNonNegOrNegative1"));

    retVal = DoJoin(pThis, Timeout);

    HELPER_METHOD_FRAME_END();

    FC_RETURN_BOOL(retVal);
}
FCIMPLEND

#undef Sleep
FCIMPL1(void, ThreadNative::Sleep, INT32 iTime)
{
    FCALL_CONTRACT;

    HELPER_METHOD_FRAME_BEGIN_0();

    // validate the sleep time
    if ((iTime < 0) && (iTime != INFINITE_TIMEOUT))
        COMPlusThrowArgumentOutOfRange(W("millisecondsTimeout"), W("ArgumentOutOfRange_NeedNonNegOrNegative1"));

    while(true)
    {
        INT64 sPauseTime = g_PauseTime;
        INT64 sTime = CLRGetTickCount64();
        GetThread()->UserSleep(iTime);       
        iTime = (INT32)AdditionalWait(sPauseTime, sTime, iTime);
        if(iTime == 0)
            break;
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

#define Sleep(dwMilliseconds) Dont_Use_Sleep(dwMilliseconds)

FCIMPL1(INT32, ThreadNative::GetManagedThreadId, ThreadBaseObject* th) {
    FCALL_CONTRACT;

    FC_GC_POLL_NOT_NEEDED();
    if (th == NULL)
        FCThrow(kNullReferenceException);

    return th->GetManagedThreadId();
}
FCIMPLEND

NOINLINE static Object* GetCurrentThreadHelper()
{
    FCALL_CONTRACT;
    FC_INNER_PROLOG(ThreadNative::GetCurrentThread);
    OBJECTREF   refRetVal  = NULL;

    HELPER_METHOD_FRAME_BEGIN_RET_ATTRIB_1(Frame::FRAME_ATTR_EXACT_DEPTH|Frame::FRAME_ATTR_CAPTURE_DEPTH_2, refRetVal);
    refRetVal = GetThread()->GetExposedObject();
    HELPER_METHOD_FRAME_END();

    FC_INNER_EPILOG();
    return OBJECTREFToObject(refRetVal);
}

FCIMPL0(Object*, ThreadNative::GetCurrentThread)
{
    FCALL_CONTRACT;
    OBJECTHANDLE ExposedObject = GetThread()->m_ExposedObject;
    _ASSERTE(ExposedObject != 0); //Thread's constructor always initializes its GCHandle
    Object* result = *((Object**) ExposedObject);
    if (result != 0)
        return result;

    FC_INNER_RETURN(Object*, GetCurrentThreadHelper());
}
FCIMPLEND


FCIMPL3(void, ThreadNative::SetStart, ThreadBaseObject* pThisUNSAFE, Object* pDelegateUNSAFE, INT32 iRequestedStackSize)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowResVoid(kNullReferenceException, W("NullReference_This"));

    THREADBASEREF   pThis       = (THREADBASEREF) pThisUNSAFE;
    OBJECTREF       pDelegate   = (OBJECTREF    ) pDelegateUNSAFE;

    HELPER_METHOD_FRAME_BEGIN_2(pThis, pDelegate);

    _ASSERTE(pThis != NULL);
    _ASSERTE(pDelegate != NULL); // Thread's constructor validates this

    if (pThis->m_InternalThread == NULL)
    {
        // if we don't have an internal Thread object associated with this exposed object,
        // now is our first opportunity to create one.
        Thread      *unstarted = SetupUnstartedThread();

        PREFIX_ASSUME(unstarted != NULL);

        if (GetThread()->GetDomain()->IgnoreUnhandledExceptions())
        {
            unstarted->SetThreadStateNC(Thread::TSNC_IgnoreUnhandledExceptions);
        }

        pThis->SetInternal(unstarted);
        pThis->SetManagedThreadId(unstarted->GetThreadId());
        unstarted->SetExposedObject(pThis);
        unstarted->RequestedThreadStackSize(iRequestedStackSize);
    }

    // save off the delegate
    pThis->SetDelegate(pDelegate);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND


// Set whether or not this is a background thread.
FCIMPL2(void, ThreadNative::SetBackground, ThreadBaseObject* pThisUNSAFE, CLR_BOOL isBackground)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowResVoid(kNullReferenceException, W("NullReference_This"));

    // validate the thread
    Thread  *thread = pThisUNSAFE->GetInternal();

    if (ThreadIsDead(thread))
        FCThrowExVoid(kThreadStateException, IDS_EE_THREAD_DEAD_STATE, NULL, NULL, NULL);

    HELPER_METHOD_FRAME_BEGIN_0();

    thread->SetBackground(isBackground);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

// Return whether or not this is a background thread.
FCIMPL1(FC_BOOL_RET, ThreadNative::IsBackground, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowRes(kNullReferenceException, W("NullReference_This"));

    // validate the thread
    Thread  *thread = pThisUNSAFE->GetInternal();

    if (ThreadIsDead(thread))
        FCThrowEx(kThreadStateException, IDS_EE_THREAD_DEAD_STATE, NULL, NULL, NULL);

    FC_RETURN_BOOL(thread->IsBackground());
}
FCIMPLEND


// Deliver the state of the thread as a consistent set of bits.
// This copied in VM\EEDbgInterfaceImpl.h's
//     CorDebugUserState GetUserState( Thread *pThread )
// , so propogate changes to both functions
FCIMPL1(INT32, ThreadNative::GetThreadState, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    INT32               res = 0;
    Thread::ThreadState state;

    if (pThisUNSAFE==NULL)
        FCThrowRes(kNullReferenceException, W("NullReference_This"));

    // validate the thread.  Failure here implies that the thread was finalized
    // and then resurrected.
    Thread  *thread = pThisUNSAFE->GetInternal();

    if (!thread)
        FCThrowEx(kThreadStateException, IDS_EE_THREAD_CANNOT_GET, NULL, NULL, NULL);

    HELPER_METHOD_FRAME_BEGIN_RET_0();

    // grab a snapshot
    state = thread->GetSnapshotState();

    if (state & Thread::TS_Background)
        res |= ThreadBackground;

    if (state & Thread::TS_Unstarted)
        res |= ThreadUnstarted;

    // Don't report a StopRequested if the thread has actually stopped.
    if (state & Thread::TS_Dead)
    {
        if (state & Thread::TS_Aborted)
            res |= ThreadAborted;
        else
            res |= ThreadStopped;
    }
    else
    {
        if (state & Thread::TS_AbortRequested)
            res |= ThreadAbortRequested;
    }

    if (state & Thread::TS_Interruptible)
        res |= ThreadWaitSleepJoin;

    // CoreCLR does not support user-requested thread suspension
    _ASSERTE(!(state & Thread::TS_UserSuspendPending));

    HELPER_METHOD_POLL();
    HELPER_METHOD_FRAME_END();

    return res;
}
FCIMPLEND

#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT

// Indicate whether the thread will host an STA (this may fail if the thread has
// already been made part of the MTA, use GetApartmentState or the return state
// from this routine to check for this).
FCIMPL3(INT32, ThreadNative::SetApartmentState, ThreadBaseObject* pThisUNSAFE, INT32 iState, CLR_BOOL fireMDAOnMismatch)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowRes(kNullReferenceException, W("NullReference_This"));

    INT32           retVal  = ApartmentUnknown;
    BOOL    ok = TRUE;
    THREADBASEREF   pThis   = (THREADBASEREF) pThisUNSAFE;

    HELPER_METHOD_FRAME_BEGIN_RET_1(pThis);

    // Translate state input. ApartmentUnknown is not an acceptable input state.
    // Throw an exception here rather than pass it through to the internal
    // routine, which asserts.
    Thread::ApartmentState state = Thread::AS_Unknown;
    if (iState == ApartmentSTA)
        state = Thread::AS_InSTA;
    else if (iState == ApartmentMTA)
        state = Thread::AS_InMTA;
    else if (iState == ApartmentUnknown)
        state = Thread::AS_Unknown;
    else
        COMPlusThrow(kArgumentOutOfRangeException, W("ArgumentOutOfRange_Enum"));

    Thread  *thread = pThis->GetInternal();
    if (!thread)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);

    {
        pThis->EnterObjMonitor();

        // We can only change the apartment if the thread is unstarted or
        // running, and if it's running we have to be in the thread's
        // context.
        if ((!ThreadNotStarted(thread) && !ThreadIsRunning(thread)) ||
            (!ThreadNotStarted(thread) && (GetThread() != thread)))
            ok = FALSE;
        else
        {
            EX_TRY
            {
                state = thread->SetApartment(state, fireMDAOnMismatch == TRUE);
            }
            EX_CATCH
            {
                pThis->LeaveObjMonitor();
                EX_RETHROW;
            }
            EX_END_CATCH_UNREACHABLE;
        }

        pThis->LeaveObjMonitor();
    }


    // Now it's safe to throw exceptions again.
    if (!ok)
        COMPlusThrow(kThreadStateException);

    // Translate state back into external form
    if (state == Thread::AS_InSTA)
        retVal = ApartmentSTA;
    else if (state == Thread::AS_InMTA)
        retVal = ApartmentMTA;
    else if (state == Thread::AS_Unknown)
        retVal = ApartmentUnknown;
    else
        _ASSERTE(!"Invalid state returned from SetApartment");

    HELPER_METHOD_FRAME_END();

    return retVal;
}
FCIMPLEND

// Return whether the thread hosts an STA, is a member of the MTA or is not
// currently initialized for COM.
FCIMPL1(INT32, ThreadNative::GetApartmentState, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    INT32 retVal = 0;

    THREADBASEREF refThis = (THREADBASEREF) ObjectToOBJECTREF(pThisUNSAFE);

    HELPER_METHOD_FRAME_BEGIN_RET_1(refThis);

    if (refThis == NULL)
    {
        COMPlusThrow(kNullReferenceException, W("NullReference_This"));
    }

    Thread* thread = refThis->GetInternal();

    if (ThreadIsDead(thread))
    {
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_DEAD_STATE);
    }

    Thread::ApartmentState state = thread->GetApartment();

#ifdef FEATURE_COMINTEROP
    if (state == Thread::AS_Unknown)
    {
        // If the CLR hasn't started COM yet, start it up and attempt the call again.
        // We do this in order to minimize the number of situations under which we return
        // ApartmentState.Unknown to our callers.
        if (!g_fComStarted)
        {
            EnsureComStarted();
            state = thread->GetApartment();
        }
    }
#endif // FEATURE_COMINTEROP

    // Translate state into external form
    retVal = ApartmentUnknown;
    if (state == Thread::AS_InSTA)
    {
        retVal = ApartmentSTA;
    }
    else if (state == Thread::AS_InMTA)
    {
        retVal = ApartmentMTA;
    }
    else if (state == Thread::AS_Unknown)
    {
        retVal = ApartmentUnknown;
    }
    else
    {
        _ASSERTE(!"Invalid state returned from GetApartment");
    }

    HELPER_METHOD_FRAME_END();

    return retVal;
}
FCIMPLEND


// Attempt to eagerly set the apartment state during thread startup.
FCIMPL1(void, ThreadNative::StartupSetApartmentState, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    THREADBASEREF refThis = (THREADBASEREF) ObjectToOBJECTREF(pThisUNSAFE);

    HELPER_METHOD_FRAME_BEGIN_1(refThis);

    if (refThis == NULL)
    {
        COMPlusThrow(kNullReferenceException, W("NullReference_This"));
    }

    Thread* thread = refThis->GetInternal();

    if (!ThreadNotStarted(thread))
        COMPlusThrow(kThreadStateException, IDS_EE_THREADSTART_STATE);

    // Assert that the thread hasn't been started yet.
    _ASSERTE(Thread::TS_Unstarted & thread->GetSnapshotState());

    Thread::ApartmentState as = thread->GetExplicitApartment();
    if (as == Thread::AS_Unknown)
    {
        thread->SetApartment(Thread::AS_InMTA, TRUE);
    }

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT

void ReleaseThreadExternalCount(Thread * pThread)
{
    WRAPPER_NO_CONTRACT;
    pThread->DecExternalCount(FALSE);
}

typedef Holder<Thread *, DoNothing, ReleaseThreadExternalCount> ThreadExternalCountHolder;

// Wait for the thread to die
BOOL ThreadNative::DoJoin(THREADBASEREF DyingThread, INT32 timeout)
{
    CONTRACTL
    {
        THROWS;
        GC_TRIGGERS;
        MODE_COOPERATIVE;
        PRECONDITION(DyingThread != NULL);
        PRECONDITION((timeout >= 0) || (timeout == INFINITE_TIMEOUT));
    }
    CONTRACTL_END;

    Thread * DyingInternal = DyingThread->GetInternal();

    // Validate the handle.  It's valid to Join a thread that's not running -- so
    // long as it was once started.
    if (DyingInternal == 0 ||
        !(DyingInternal->m_State & Thread::TS_LegalToJoin))
    {
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_NOTSTARTED);
    }

    // Don't grab the handle until we know it has started, to eliminate the race
    // condition.
    if (ThreadIsDead(DyingInternal) || !DyingInternal->HasValidThreadHandle())
        return TRUE;

    DWORD dwTimeOut32 = (timeout == INFINITE_TIMEOUT
                   ? INFINITE
                   : (DWORD) timeout);

    // There is a race here.  DyingThread is going to close its thread handle.
    // If we grab the handle and then DyingThread closes it, we will wait forever
    // in DoAppropriateWait.
    int RefCount = DyingInternal->IncExternalCount();
    if (RefCount == 1)
    {
        // !!! We resurrect the Thread Object.
        // !!! We will keep the Thread ref count to be 1 so that we will not try
        // !!! to destroy the Thread Object again.
        // !!! Do not call DecExternalCount here!
        _ASSERTE (!DyingInternal->HasValidThreadHandle());
        return TRUE;
    }

    ThreadExternalCountHolder dyingInternalHolder(DyingInternal);

    if (!DyingInternal->HasValidThreadHandle())
    {
        return TRUE;
    }

    GCX_PREEMP();
    DWORD rv = DyingInternal->JoinEx(dwTimeOut32, (WaitMode)(WaitMode_Alertable/*alertable*/|WaitMode_InDeadlock));

    switch(rv)
    {
        case WAIT_OBJECT_0:
            return TRUE;

        case WAIT_TIMEOUT:
            break;

        case WAIT_FAILED:
            if(!DyingInternal->HasValidThreadHandle())
                return TRUE;
            break;
            
        default:
            _ASSERTE(!"This return code is not understood \n");
            break;
    }    

    return FALSE;
}


// We don't get a constructor for ThreadBaseObject, so we rely on the fact that this
// method is only called once, out of SetStart.  Since SetStart is private/native
// and only called from the constructor, we'll only get called here once to set it
// up and once (with NULL) to tear it down.  The 'null' can only come from Finalize
// because the constructor throws if it doesn't get a valid delegate.
void ThreadBaseObject::SetDelegate(OBJECTREF delegate)
{
    CONTRACTL
    {
        GC_TRIGGERS;
        THROWS;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

#ifdef APPDOMAIN_STATE
    if (delegate != NULL)
    {
        AppDomain *pDomain = delegate->GetAppDomain();
        Thread *pThread = GetInternal();
        AppDomain *kickoffDomain = pThread->GetKickOffDomain();
        _ASSERTE_ALL_BUILDS("clr/src/VM/COMSynchronizable.cpp", !pDomain || pDomain == kickoffDomain);
        _ASSERTE_ALL_BUILDS("clr/src/VM/COMSynchronizable.cpp", kickoffDomain == GetThread()->GetDomain());
    }
#endif

    SetObjectReferenceUnchecked( (OBJECTREF *)&m_Delegate, delegate );

    // If the delegate is being set then initialize the other data members.
    if (m_Delegate != NULL)
    {
        // Initialize the thread priority to normal.
        m_Priority = ThreadNative::PRIORITY_NORMAL;
    }
}


// If the exposed object is created after-the-fact, for an existing thread, we call
// InitExisting on it.  This is the other "construction", as opposed to SetDelegate.
void ThreadBaseObject::InitExisting()
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    Thread *pThread = GetInternal();
    _ASSERTE (pThread);
    switch (pThread->GetThreadPriority())
    {
    case THREAD_PRIORITY_LOWEST:
    case THREAD_PRIORITY_IDLE:
        m_Priority = ThreadNative::PRIORITY_LOWEST;
        break;

    case THREAD_PRIORITY_BELOW_NORMAL:
        m_Priority = ThreadNative::PRIORITY_BELOW_NORMAL;
        break;

    case THREAD_PRIORITY_NORMAL:
        m_Priority = ThreadNative::PRIORITY_NORMAL;
        break;

    case THREAD_PRIORITY_ABOVE_NORMAL:
        m_Priority = ThreadNative::PRIORITY_ABOVE_NORMAL;
        break;

    case THREAD_PRIORITY_HIGHEST:
    case THREAD_PRIORITY_TIME_CRITICAL:
        m_Priority = ThreadNative::PRIORITY_HIGHEST;
        break;

    case THREAD_PRIORITY_ERROR_RETURN:
        _ASSERTE(FALSE);
        m_Priority = ThreadNative::PRIORITY_NORMAL;
        break;

    default:
        m_Priority = ThreadNative::PRIORITY_NORMAL;
        break;
    }

}

OBJECTREF ThreadBaseObject::GetManagedThreadCulture(BOOL bUICulture)
{
    CONTRACTL {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_COOPERATIVE;
    }
    CONTRACTL_END;

    // This is the case when we're building mscorlib and haven't yet created
    // the system assembly.
    if (SystemDomain::System()->SystemAssembly()==NULL || g_fForbidEnterEE) {
        return NULL;
    }

    OBJECTREF *pCurrentCulture = NULL;
    Thread    *pThread = GetInternal();
    FieldDesc *pFD = NULL;

    if (bUICulture)
    {
        pFD = pThread->managedThreadCurrentUICulture;
    }
    else
    {
        pFD = pThread->managedThreadCurrentCulture;
    }

    if (pFD != NULL)
    {
        pCurrentCulture = (OBJECTREF*)pThread->GetStaticFieldAddrNoCreate(pFD, NULL);
        if (pCurrentCulture)
        {
            return *pCurrentCulture;
        }
    }

    return NULL;
}

CULTUREINFOBASEREF ThreadBaseObject::GetCurrentUserCulture()
{
    WRAPPER_NO_CONTRACT;

    return (CULTUREINFOBASEREF)GetManagedThreadCulture(false);
}

CULTUREINFOBASEREF ThreadBaseObject::GetCurrentUICulture()
{
    WRAPPER_NO_CONTRACT;

    return (CULTUREINFOBASEREF)GetManagedThreadCulture(true);
}

// If the thread pool thread switched appdomains and the culture was set, the culture won't be
// reset for the second appdomain. It's impossible to do general cleanup of thread pool threads
// because we don't have the right extensible infrastructure for it. For example, if the second
// appdomain was in a different CLR you won't be able to reset the culture without introducing 
// new cross-CLR communication mechanism. However, note that this isn't a user scenario in 
// CoreCLR anyway.
void ThreadBaseObject::ResetCurrentUserCulture()
{
    WRAPPER_NO_CONTRACT;
    ResetManagedThreadCulture(false);
}

void ThreadBaseObject::ResetCurrentUICulture()
{
    WRAPPER_NO_CONTRACT;
    ResetManagedThreadCulture(true);
}

void ThreadBaseObject::ResetManagedThreadCulture(BOOL bUICulture)
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    // This is the case when we're building mscorlib and haven't yet created
    // the system assembly.
    if (SystemDomain::System()->SystemAssembly()==NULL || g_fForbidEnterEE) {
        return;
    }
    
    Thread    *pThread = GetInternal();
    FieldDesc *pFD = NULL;

    if (bUICulture)
    {
        pFD = pThread->managedThreadCurrentUICulture;
    }
    else
    {
        pFD = pThread->managedThreadCurrentCulture;
    }

    if (pFD != NULL)
    {
        OBJECTREF *pCulture = NULL;
        BEGIN_SO_INTOLERANT_CODE_NO_THROW_CHECK_THREAD(COMPlusThrowSO());
        pCulture = (OBJECTREF*)pThread->GetStaticFieldAddrNoCreate(pFD, NULL);
        if (pCulture) 
        {
            SetObjectReferenceUnchecked(pCulture, NULL);
        }
        END_SO_INTOLERANT_CODE;

    }
}



FCIMPL1(void, ThreadNative::Finalize, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    // This function is intentionally blank.
    // See comment in code:MethodTable::CallFinalizer.

    _ASSERTE (!"Should not be called");

    FCUnique(0x21);
}
FCIMPLEND

#ifdef FEATURE_COMINTEROP
FCIMPL1(void, ThreadNative::DisableComObjectEagerCleanup, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    _ASSERTE(pThisUNSAFE != NULL);
    VALIDATEOBJECT(pThisUNSAFE);
    Thread *pThread = pThisUNSAFE->GetInternal();

    HELPER_METHOD_FRAME_BEGIN_0();

    if (pThread == NULL)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);

    pThread->SetDisableComObjectEagerCleanup();

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND
#endif //FEATURE_COMINTEROP


FCIMPL0(Object*, ThreadNative::GetDomain)
{
    FCALL_CONTRACT;

    APPDOMAINREF refRetVal = NULL;

    Thread* thread = GetThread();

    if ((thread) && (thread->GetDomain()))
    {
        HELPER_METHOD_FRAME_BEGIN_RET_1(refRetVal);
        refRetVal = (APPDOMAINREF) thread->GetDomain()->GetExposedObject();
        HELPER_METHOD_FRAME_END();
    }

    return OBJECTREFToObject(refRetVal);
}
FCIMPLEND

#if defined(_TARGET_X86_) && defined(_MSC_VER)
__declspec(naked) LPVOID __fastcall ThreadNative::FastGetDomain()
{
    STATIC_CONTRACT_MODE_COOPERATIVE;
    STATIC_CONTRACT_GC_NOTRIGGER;
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_SO_TOLERANT;

    __asm {
        call GetAppDomain
        test eax, eax
        je done
        mov eax, dword ptr [eax]AppDomain.m_ExposedObject
        test eax, eax
        je done
        mov eax, dword ptr [eax]
done:
        ret
    }
}
#else // _TARGET_X86_ && _MSC_VER
LPVOID F_CALL_CONV ThreadNative::FastGetDomain()
{
    CONTRACTL
    {
        GC_NOTRIGGER;
        NOTHROW;
        MODE_COOPERATIVE;
        SO_TOLERANT;
    }
    CONTRACTL_END;

    Thread *pThread;
    AppDomain *pDomain;
    OBJECTHANDLE ExposedObject;

    pDomain = GetAppDomain();
    if (!pDomain) {
        return NULL;
    }
    ExposedObject = pDomain->m_ExposedObject;
    if (ExposedObject) {
        return *(LPVOID *)ExposedObject;
    }
    return NULL;
}
#endif // _TARGET_X86_ && _MSC_VER


//
// nativeGetSafeCulture is used when the culture get requested from the thread object. 
// we have to check the culture in the FCALL because in FCALL the thread cannot be 
// interrupted and unload other app domian.
// the concern here is if the thread hold a subclassed culture object and somebody 
// requested it from other app domain then we shouldn't hold any reference to that 
// culture object any time because the app domain created this culture may get 
// unloaded and this culture will survive although the type metadata will be unloaded 
// and GC will crash first time accessing this object after the app domain unload.
//

void QCALLTYPE ThreadNative::nativeInitCultureAccessors()
{
    QCALL_CONTRACT;

    BEGIN_QCALL;

    Thread* pThread = GetThread();
    pThread->InitCultureAccessors();

    END_QCALL;
}


void QCALLTYPE ThreadNative::InformThreadNameChange(QCall::ThreadHandle thread, LPCWSTR name, INT32 len)
{
    QCALL_CONTRACT;

    BEGIN_QCALL;
    
    Thread* pThread = &(*thread);

#ifndef FEATURE_PAL
    // Set on Windows 10 Creators Update and later machines the unmanaged thread name as well. That will show up in ETW traces and debuggers which is very helpful
    // if more and more threads get a meaningful name
    if (len > 0 && name != NULL)
    {
        SetThreadName(pThread->GetThreadHandle(), name);
    }
#endif

#ifdef PROFILING_SUPPORTED
    {
        BEGIN_PIN_PROFILER(CORProfilerTrackThreads());
        if (name == NULL)
        {
            g_profControlBlock.pProfInterface->ThreadNameChanged((ThreadID)pThread, 0, NULL);
        }
        else
        {
            g_profControlBlock.pProfInterface->ThreadNameChanged((ThreadID)pThread, len, (WCHAR*)name);
        }
        END_PIN_PROFILER();
    }
#endif // PROFILING_SUPPORTED


#ifdef DEBUGGING_SUPPORTED
    if (CORDebuggerAttached())
    {
        _ASSERTE(NULL != g_pDebugInterface);
        g_pDebugInterface->NameChangeEvent(NULL, pThread);
    }
#endif // DEBUGGING_SUPPORTED

    END_QCALL;
}

UINT64 QCALLTYPE ThreadNative::GetProcessDefaultStackSize()
{
    QCALL_CONTRACT;

    SIZE_T reserve = 0;
    SIZE_T commit = 0;

    BEGIN_QCALL;

    if (!Thread::GetProcessDefaultStackSize(&reserve, &commit))
        reserve = 1024 * 1024;

    END_QCALL;

    return (UINT64)reserve;
}



FCIMPL1(FC_BOOL_RET, ThreadNative::IsThreadpoolThread, ThreadBaseObject* thread)
{
    FCALL_CONTRACT;

    if (thread==NULL)
        FCThrowRes(kNullReferenceException, W("NullReference_This"));

    Thread *pThread = thread->GetInternal();

    if (pThread == NULL)
        FCThrowEx(kThreadStateException, IDS_EE_THREAD_DEAD_STATE, NULL, NULL, NULL);

    BOOL ret = pThread->IsThreadPoolThread();

    FC_GC_POLL_RET();

    FC_RETURN_BOOL(ret);
}
FCIMPLEND

INT32 QCALLTYPE ThreadNative::GetOptimalMaxSpinWaitsPerSpinIteration()
{
    QCALL_CONTRACT;

    INT32 optimalMaxNormalizedYieldsPerSpinIteration;

    BEGIN_QCALL;

    // RuntimeThread calls this function only once lazily and caches the result, so ensure initialization
    EnsureYieldProcessorNormalizedInitialized();
    optimalMaxNormalizedYieldsPerSpinIteration = g_optimalMaxNormalizedYieldsPerSpinIteration;

    END_QCALL;

    return optimalMaxNormalizedYieldsPerSpinIteration;
}

FCIMPL1(void, ThreadNative::SpinWait, int iterations)
{
    FCALL_CONTRACT;

    if (iterations <= 0)
    {
        return;
    }

    //
    // If we're not going to spin for long, it's ok to remain in cooperative mode.
    // The threshold is determined by the cost of entering preemptive mode; if we're
    // spinning for less than that number of cycles, then switching to preemptive
    // mode won't help a GC start any faster.
    //
    if (iterations <= 100000)
    {
        YieldProcessorNormalized(YieldProcessorNormalizationInfo(), iterations);
        return;
    }

    //
    // Too many iterations; better switch to preemptive mode to avoid stalling a GC.
    //
    HELPER_METHOD_FRAME_BEGIN_NOPOLL();
    GCX_PREEMP();

    YieldProcessorNormalized(YieldProcessorNormalizationInfo(), iterations);

    HELPER_METHOD_FRAME_END();
}
FCIMPLEND

BOOL QCALLTYPE ThreadNative::YieldThread()
{
    QCALL_CONTRACT;

    BOOL ret = FALSE;

    BEGIN_QCALL

    ret = __SwitchToThread(0, CALLER_LIMITS_SPINNING);

    END_QCALL

    return ret;
}

FCIMPL2(void, ThreadNative::SetAbortReason, ThreadBaseObject* pThisUNSAFE, Object* pObject)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowResVoid(kNullReferenceException, W("NullReference_This"));

    OBJECTREF refObject = static_cast<OBJECTREF>(pObject);

    Thread *pThread = pThisUNSAFE->GetInternal();

    // If the OBJECTHANDLE is not 0, already set so just return
    if (pThread != NULL && pThread->m_AbortReason != 0)
        return;

    // Set up a frame in case of GC or EH
    HELPER_METHOD_FRAME_BEGIN_1(refObject)

    if (pThread == NULL)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);

    // Get the AppDomain ID for the AppDomain on the currently running thread.
    //  NOTE: the currently running thread may be different from this thread object!
    AppDomain *pCurrentDomain = GetThread()->GetDomain();
    ADID adid = pCurrentDomain->GetId();

    // Create a OBJECTHANDLE for the object.
    OBJECTHANDLE oh = pCurrentDomain->CreateHandle(refObject);

    // Scope the lock to peeking at and updating the two fields on the Thread object.
    {   // Atomically check whether the OBJECTHANDLE has been set, and if not,
        //  store it and the ADID of the object.
        //  NOTE: get the lock on this thread object, not on the executing thread.
        Thread::AbortRequestLockHolder lock(pThread);
        if (pThread->m_AbortReason == 0)
        {
            pThread->m_AbortReason = oh;
            pThread->m_AbortReasonDomainID = adid;
            // Set the OBJECTHANDLE so we can know that we stored it on the Thread object.
            oh = 0;
        }
    }

    // If the OBJECTHANDLE created above was not stored onto the Thread object, then
    //  another thread beat this one to the update.  Destroy the OBJECTHANDLE that
    //  was not used, created above.
    if (oh != 0)
    {
        DestroyHandle(oh);
    }

    HELPER_METHOD_FRAME_END()

}
FCIMPLEND


FCIMPL1(void, ThreadNative::ClearAbortReason, ThreadBaseObject* pThisUNSAFE)
{
    FCALL_CONTRACT;

    if (pThisUNSAFE==NULL)
        FCThrowResVoid(kNullReferenceException, W("NullReference_This"));

    Thread *pThread = pThisUNSAFE->GetInternal();

    // Clearing from managed code can only happen on the current thread.
    _ASSERTE(pThread == GetThread());

    HELPER_METHOD_FRAME_BEGIN_0();

    if (pThread == NULL)
        COMPlusThrow(kThreadStateException, IDS_EE_THREAD_CANNOT_GET);

    pThread->ClearAbortReason();

    HELPER_METHOD_FRAME_END();

}
FCIMPLEND


FCIMPL0(INT32, ThreadNative::GetCurrentProcessorNumber)
{
    FCALL_CONTRACT;

    return ::GetCurrentProcessorNumber();
}
FCIMPLEND;