This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy paththreads.cpp
11563 lines (9616 loc) · 351 KB
/
threads.cpp
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
// 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.
//
// THREADS.CPP
//
//
//
#include "common.h"
#include "tls.h"
#include "frames.h"
#include "threads.h"
#include "stackwalk.h"
#include "excep.h"
#include "comsynchronizable.h"
#include "log.h"
#include "gcheaputilities.h"
#include "mscoree.h"
#include "dbginterface.h"
#include "corprof.h" // profiling
#include "eeprofinterfaces.h"
#include "eeconfig.h"
#include "perfcounters.h"
#include "corhost.h"
#include "win32threadpool.h"
#include "jitinterface.h"
#include "appdomainstack.inl"
#include "eventtrace.h"
#include "comutilnative.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#include "wrappers.h"
#include "nativeoverlapped.h"
#include "mdaassistants.h"
#include "appdomain.inl"
#include "vmholder.h"
#include "exceptmacros.h"
#include "win32threadpool.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "interoputil.h"
#include "interoputil.inl"
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
#include "olecontexthelpers.h"
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
SPTR_IMPL(ThreadStore, ThreadStore, s_pThreadStore);
CONTEXT *ThreadStore::s_pOSContext = NULL;
CLREvent *ThreadStore::s_pWaitForStackCrawlEvent;
#ifndef DACCESS_COMPILE
BOOL Thread::s_fCleanFinalizedThread = FALSE;
#ifdef ENABLE_GET_THREAD_GENERIC_FULL_CHECK
BOOL Thread::s_fEnforceEEThreadNotRequiredContracts = FALSE;
#endif
Volatile<LONG> Thread::s_threadPoolCompletionCountOverflow = 0;
CrstStatic g_DeadlockAwareCrst;
#if defined(_DEBUG)
BOOL MatchThreadHandleToOsId ( HANDLE h, DWORD osId )
{
#ifndef FEATURE_PAL
LIMITED_METHOD_CONTRACT;
DWORD id = GetThreadId(h);
// OS call GetThreadId may fail, and return 0. In this case we can not
// make a decision if the two match or not. Instead, we ignore this check.
return id == 0 || id == osId;
#else // !FEATURE_PAL
return TRUE;
#endif // !FEATURE_PAL
}
#endif // _DEBUG
#ifdef _DEBUG_IMPL
template<> AutoCleanupGCAssert<TRUE>::AutoCleanupGCAssert()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
}
template<> AutoCleanupGCAssert<FALSE>::AutoCleanupGCAssert()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
template<> void GCAssert<TRUE>::BeginGCAssert()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
}
template<> void GCAssert<FALSE>::BeginGCAssert()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
#endif
// #define NEW_TLS 1
#ifdef _DEBUG
void Thread::SetFrame(Frame *pFrame)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
DEBUG_ONLY;
MODE_COOPERATIVE;
// It only makes sense for a Thread to call SetFrame on itself.
PRECONDITION(this == GetThread());
PRECONDITION(CheckPointer(pFrame));
}
CONTRACTL_END;
if (g_pConfig->fAssertOnFailFast())
{
Frame *pWalk = m_pFrame;
BOOL fExist = FALSE;
while (pWalk != (Frame*) -1)
{
if (pWalk == pFrame)
{
fExist = TRUE;
break;
}
pWalk = pWalk->m_Next;
}
pWalk = m_pFrame;
while (fExist && pWalk != pFrame && pWalk != (Frame*)-1)
{
if (pWalk->GetVTablePtr() == ContextTransitionFrame::GetMethodFrameVPtr())
{
_ASSERTE (((ContextTransitionFrame *)pWalk)->GetReturnDomain() == m_pDomain);
}
pWalk = pWalk->m_Next;
}
}
m_pFrame = pFrame;
// If stack overrun corruptions are expected, then skip this check
// as the Frame chain may have been corrupted.
if (g_pConfig->fAssertOnFailFast() == false)
return;
Frame* espVal = (Frame*)GetCurrentSP();
while (pFrame != (Frame*) -1)
{
static Frame* stopFrame = 0;
if (pFrame == stopFrame)
_ASSERTE(!"SetFrame frame == stopFrame");
_ASSERTE(espVal < pFrame);
_ASSERTE(pFrame < m_CacheStackBase);
_ASSERTE(pFrame->GetFrameType() < Frame::TYPE_COUNT);
pFrame = pFrame->m_Next;
}
}
#endif // _DEBUG
//************************************************************************
// PRIVATE GLOBALS
//************************************************************************
extern unsigned __int64 getTimeStamp();
extern unsigned __int64 getTickFrequency();
unsigned __int64 tgetFrequency() {
static unsigned __int64 cachedFreq = (unsigned __int64) -1;
if (cachedFreq != (unsigned __int64) -1)
return cachedFreq;
else {
cachedFreq = getTickFrequency();
return cachedFreq;
}
}
#endif // #ifndef DACCESS_COMPILE
static StackWalkAction DetectHandleILStubsForDebugger_StackWalkCallback(CrawlFrame *pCF, VOID *pData)
{
WRAPPER_NO_CONTRACT;
// It suffices to wait for the first CrawlFrame with non-NULL function
MethodDesc *pMD = pCF->GetFunction();
if (pMD != NULL)
{
*(bool *)pData = pMD->IsILStub();
return SWA_ABORT;
}
return SWA_CONTINUE;
}
// This is really just a heuristic to detect if we are executing in an M2U IL stub or
// one of the marshaling methods it calls. It doesn't deal with U2M IL stubs.
// We loop through the frame chain looking for an uninitialized TransitionFrame.
// If there is one, then we are executing in an M2U IL stub or one of the methods it calls.
// On the other hand, if there is an initialized TransitionFrame, then we are not.
// Also, if there is an HMF on the stack, then we stop. This could be the case where
// an IL stub calls an FCALL which ends up in a managed method, and the debugger wants to
// stop in those cases. Some examples are COMException..ctor and custom marshalers.
//
// X86 IL stubs use InlinedCallFrame and are indistinguishable from ordinary methods with
// inlined P/Invoke when judging just from the frame chain. We use stack walk to decide
// this case.
bool Thread::DetectHandleILStubsForDebugger()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
Frame* pFrame = GetFrame();
if (pFrame != NULL)
{
while (pFrame != FRAME_TOP)
{
// Check for HMF's. See the comment at the beginning of this function.
if (pFrame->GetVTablePtr() == HelperMethodFrame::GetMethodFrameVPtr())
{
break;
}
// If there is an entry frame (i.e. U2M managed), we should break.
else if (pFrame->GetFrameType() == Frame::TYPE_ENTRY)
{
break;
}
// Check for M2U transition frames. See the comment at the beginning of this function.
else if (pFrame->GetFrameType() == Frame::TYPE_EXIT)
{
if (pFrame->GetReturnAddress() == NULL)
{
// If the return address is NULL, then the frame has not been initialized yet.
// We may see InlinedCallFrame in ordinary methods as well. Have to do
// stack walk to find out if this is really an IL stub.
bool fInILStub = false;
StackWalkFrames(&DetectHandleILStubsForDebugger_StackWalkCallback,
&fInILStub,
QUICKUNWIND,
dac_cast<PTR_Frame>(pFrame));
if (fInILStub) return true;
}
else
{
// The frame is fully initialized.
return false;
}
}
pFrame = pFrame->Next();
}
}
return false;
}
#ifdef FEATURE_IMPLICIT_TLS
extern "C" {
#ifndef __llvm__
__declspec(thread)
#else // !__llvm__
__thread
#endif // !__llvm__
ThreadLocalInfo gCurrentThreadInfo =
{
NULL, // m_pThread
NULL, // m_pAppDomain
NULL, // m_EETlsData
#if defined(FEATURE_MERGE_JIT_AND_ENGINE)
NULL, // m_pCompiler
#endif
};
} // extern "C"
// index into TLS Array. Definition added by compiler
EXTERN_C UINT32 _tls_index;
#else // FEATURE_IMPLICIT_TLS
extern "C" {
GVAL_IMPL_INIT(DWORD, gThreadTLSIndex, TLS_OUT_OF_INDEXES); // index ( (-1) == uninitialized )
GVAL_IMPL_INIT(DWORD, gAppDomainTLSIndex, TLS_OUT_OF_INDEXES); // index ( (-1) == uninitialized )
}
#endif // FEATURE_IMPLICIT_TLS
#ifndef DACCESS_COMPILE
#ifdef FEATURE_IMPLICIT_TLS
BOOL SetThread(Thread* t)
{
LIMITED_METHOD_CONTRACT
gCurrentThreadInfo.m_pThread = t;
return TRUE;
}
BOOL SetAppDomain(AppDomain* ad)
{
LIMITED_METHOD_CONTRACT
gCurrentThreadInfo.m_pAppDomain = ad;
return TRUE;
}
#if defined(FEATURE_MERGE_JIT_AND_ENGINE)
extern "C"
{
void* GetJitTls()
{
LIMITED_METHOD_CONTRACT
return gCurrentThreadInfo.m_pJitTls;
}
void SetJitTls(void* v)
{
LIMITED_METHOD_CONTRACT
gCurrentThreadInfo.m_pJitTls = v;
}
}
#endif // defined(FEATURE_MERGE_JIT_AND_ENGINE)
#define ThreadInited() (TRUE)
#else // FEATURE_IMPLICIT_TLS
BOOL SetThread(Thread* t)
{
WRAPPER_NO_CONTRACT
return UnsafeTlsSetValue(GetThreadTLSIndex(), t);
}
BOOL SetAppDomain(AppDomain* ad)
{
WRAPPER_NO_CONTRACT
return UnsafeTlsSetValue(GetAppDomainTLSIndex(), ad);
}
#define ThreadInited() (gThreadTLSIndex != TLS_OUT_OF_INDEXES)
#endif // FEATURE_IMPLICIT_TLS
BOOL Thread::Alert ()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
BOOL fRetVal = FALSE;
{
HANDLE handle = GetThreadHandle();
if (handle != INVALID_HANDLE_VALUE && handle != SWITCHOUT_HANDLE_VALUE)
{
fRetVal = ::QueueUserAPC(UserInterruptAPC, handle, APC_Code);
}
}
return fRetVal;
}
DWORD Thread::Join(DWORD timeout, BOOL alertable)
{
WRAPPER_NO_CONTRACT;
return JoinEx(timeout,alertable?WaitMode_Alertable:WaitMode_None);
}
DWORD Thread::JoinEx(DWORD timeout, WaitMode mode)
{
CONTRACTL {
THROWS;
if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
BOOL alertable = (mode & WaitMode_Alertable)?TRUE:FALSE;
Thread *pCurThread = GetThread();
_ASSERTE(pCurThread || dbgOnly_IsSpecialEEThread());
{
// We're not hosted, so WaitMode_InDeadlock is irrelevant. Clear it, so that this wait can be
// forwarded to a SynchronizationContext if needed.
mode = (WaitMode)(mode & ~WaitMode_InDeadlock);
HANDLE handle = GetThreadHandle();
if (handle == INVALID_HANDLE_VALUE || handle == SWITCHOUT_HANDLE_VALUE) {
return WAIT_FAILED;
}
if (pCurThread) {
return pCurThread->DoAppropriateWait(1, &handle, FALSE, timeout, mode);
}
else {
return WaitForSingleObjectEx(handle,timeout,alertable);
}
}
}
extern INT32 MapFromNTPriority(INT32 NTPriority);
BOOL Thread::SetThreadPriority(
int nPriority // thread priority level
)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
BOOL fRet;
{
if (GetThreadHandle() == INVALID_HANDLE_VALUE) {
// When the thread starts running, we will set the thread priority.
fRet = TRUE;
}
else
fRet = ::SetThreadPriority(GetThreadHandle(), nPriority);
}
if (fRet)
{
GCX_COOP();
THREADBASEREF pObject = (THREADBASEREF)ObjectFromHandle(m_ExposedObject);
if (pObject != NULL)
{
// TODO: managed ThreadPriority only supports up to 4.
pObject->SetPriority (MapFromNTPriority(nPriority));
}
}
return fRet;
}
int Thread::GetThreadPriority()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
int nRetVal = -1;
if (GetThreadHandle() == INVALID_HANDLE_VALUE) {
nRetVal = FALSE;
}
else
nRetVal = ::GetThreadPriority(GetThreadHandle());
return nRetVal;
}
void Thread::ChooseThreadCPUGroupAffinity()
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS;
}
CONTRACTL_END;
#ifndef FEATURE_PAL
if (!CPUGroupInfo::CanEnableGCCPUGroups() || !CPUGroupInfo::CanEnableThreadUseAllCpuGroups())
return;
//Borrow the ThreadStore Lock here: Lock ThreadStore before distributing threads
ThreadStoreLockHolder TSLockHolder(TRUE);
// this thread already has CPU group affinity set
if (m_pAffinityMask != 0)
return;
if (GetThreadHandle() == INVALID_HANDLE_VALUE)
return;
GROUP_AFFINITY groupAffinity;
CPUGroupInfo::ChooseCPUGroupAffinity(&groupAffinity);
CPUGroupInfo::SetThreadGroupAffinity(GetThreadHandle(), &groupAffinity, NULL);
m_wCPUGroup = groupAffinity.Group;
m_pAffinityMask = groupAffinity.Mask;
#endif // !FEATURE_PAL
}
void Thread::ClearThreadCPUGroupAffinity()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifndef FEATURE_PAL
if (!CPUGroupInfo::CanEnableGCCPUGroups() || !CPUGroupInfo::CanEnableThreadUseAllCpuGroups())
return;
ThreadStoreLockHolder TSLockHolder(TRUE);
// this thread does not have CPU group affinity set
if (m_pAffinityMask == 0)
return;
GROUP_AFFINITY groupAffinity;
groupAffinity.Group = m_wCPUGroup;
groupAffinity.Mask = m_pAffinityMask;
CPUGroupInfo::ClearCPUGroupAffinity(&groupAffinity);
m_wCPUGroup = 0;
m_pAffinityMask = 0;
#endif // !FEATURE_PAL
}
DWORD Thread::StartThread()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
DWORD dwRetVal = (DWORD) -1;
#ifdef _DEBUG
_ASSERTE (m_Creater.IsCurrentThread());
m_Creater.Clear();
#endif
_ASSERTE (GetThreadHandle() != INVALID_HANDLE_VALUE &&
GetThreadHandle() != SWITCHOUT_HANDLE_VALUE);
dwRetVal = ::ResumeThread(GetThreadHandle());
return dwRetVal;
}
// Class static data:
LONG Thread::m_DebugWillSyncCount = -1;
LONG Thread::m_DetachCount = 0;
LONG Thread::m_ActiveDetachCount = 0;
int Thread::m_offset_counter = 0;
Volatile<LONG> Thread::m_threadsAtUnsafePlaces = 0;
//-------------------------------------------------------------------------
// Public function: SetupThreadNoThrow()
// Creates Thread for current thread if not previously created.
// Returns NULL for failure (usually due to out-of-memory.)
//-------------------------------------------------------------------------
Thread* SetupThreadNoThrow(HRESULT *pHR)
{
CONTRACTL {
NOTHROW;
SO_TOLERANT;
if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
HRESULT hr = S_OK;
Thread *pThread = GetThread();
if (pThread != NULL)
{
return pThread;
}
EX_TRY
{
pThread = SetupThread();
}
EX_CATCH
{
// We failed SetupThread. GET_EXCEPTION() may depend on Thread object.
if (__pException == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
hr = GET_EXCEPTION()->GetHR();
}
}
EX_END_CATCH(SwallowAllExceptions);
if (pHR)
{
*pHR = hr;
}
return pThread;
}
void DeleteThread(Thread* pThread)
{
CONTRACTL {
NOTHROW;
if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
//_ASSERTE (pThread == GetThread());
SetThread(NULL);
SetAppDomain(NULL);
if (pThread->HasThreadStateNC(Thread::TSNC_ExistInThreadStore))
{
pThread->DetachThread(FALSE);
}
else
{
#ifdef FEATURE_COMINTEROP
pThread->RevokeApartmentSpy();
#endif // FEATURE_COMINTEROP
FastInterlockOr((ULONG *)&pThread->m_State, Thread::TS_Dead);
// ~Thread() calls SafeSetThrowables which has a conditional contract
// which says that if you call it with a NULL throwable then it is
// MODE_ANY, otherwise MODE_COOPERATIVE. Scan doesn't understand that
// and assumes that we're violating the MODE_COOPERATIVE.
CONTRACT_VIOLATION(ModeViolation);
delete pThread;
}
}
void EnsurePreemptive()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThread();
if (pThread && pThread->PreemptiveGCDisabled())
{
pThread->EnablePreemptiveGC();
}
}
typedef StateHolder<DoNothing, EnsurePreemptive> EnsurePreemptiveModeIfException;
Thread* SetupThread(BOOL fInternal)
{
CONTRACTL {
THROWS;
if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
SO_TOLERANT;
}
CONTRACTL_END;
_ASSERTE(ThreadInited());
Thread* pThread;
if ((pThread = GetThread()) != NULL)
return pThread;
#ifdef FEATURE_STACK_PROBE
RetailStackProbe(ADJUST_PROBE(DEFAULT_ENTRY_PROBE_AMOUNT), NULL);
#endif //FEATURE_STACK_PROBE
CONTRACT_VIOLATION(SOToleranceViolation);
// For interop debugging, we must mark that we're in a can't-stop region
// b.c we may take Crsts here that may block the helper thread.
// We're especially fragile here b/c we don't have a Thread object yet
CantStopHolder hCantStop;
EnsurePreemptiveModeIfException ensurePreemptive;
#ifdef _DEBUG
CHECK chk;
if (g_pConfig->SuppressChecks())
{
// EnterAssert will suppress any checks
chk.EnterAssert();
}
#endif
// Normally, HasStarted is called from the thread's entrypoint to introduce it to
// the runtime. But sometimes that thread is used for DLL_THREAD_ATTACH notifications
// that call into managed code. In that case, a call to SetupThread here must
// find the correct Thread object and install it into TLS.
if (ThreadStore::s_pThreadStore->m_PendingThreadCount != 0)
{
DWORD ourOSThreadId = ::GetCurrentThreadId();
{
ThreadStoreLockHolder TSLockHolder;
_ASSERTE(pThread == NULL);
while ((pThread = ThreadStore::s_pThreadStore->GetAllThreadList(pThread, Thread::TS_Unstarted | Thread::TS_FailStarted, Thread::TS_Unstarted)) != NULL)
{
if (pThread->GetOSThreadId() == ourOSThreadId)
{
break;
}
}
if (pThread != NULL)
{
STRESS_LOG2(LF_SYNC, LL_INFO1000, "T::ST - recycling thread 0x%p (state: 0x%x)\n", pThread, pThread->m_State.Load());
}
}
// It's perfectly reasonable to not find this guy. It's just an unrelated
// thread spinning up.
if (pThread)
{
if (IsThreadPoolWorkerSpecialThread())
{
FastInterlockOr((ULONG *) &pThread->m_State, Thread::TS_TPWorkerThread);
pThread->SetBackground(TRUE);
}
else if (IsThreadPoolIOCompletionSpecialThread())
{
FastInterlockOr ((ULONG *) &pThread->m_State, Thread::TS_CompletionPortThread);
pThread->SetBackground(TRUE);
}
else if (IsTimerSpecialThread() || IsWaitSpecialThread())
{
FastInterlockOr((ULONG *) &pThread->m_State, Thread::TS_TPWorkerThread);
pThread->SetBackground(TRUE);
}
BOOL fStatus = pThread->HasStarted();
ensurePreemptive.SuppressRelease();
return fStatus ? pThread : NULL;
}
}
// First time we've seen this thread in the runtime:
pThread = new Thread();
// What state are we in here? COOP???
Holder<Thread*,DoNothing<Thread*>,DeleteThread> threadHolder(pThread);
CExecutionEngine::SetupTLSForThread(pThread);
// A host can deny a thread entering runtime by returning a NULL IHostTask.
// But we do want threads used by threadpool.
if (IsThreadPoolWorkerSpecialThread() ||
IsThreadPoolIOCompletionSpecialThread() ||
IsTimerSpecialThread() ||
IsWaitSpecialThread())
{
fInternal = TRUE;
}
if (!pThread->InitThread(fInternal) ||
!pThread->PrepareApartmentAndContext())
ThrowOutOfMemory();
#ifndef FEATURE_IMPLICIT_TLS
// make sure we will not fail when we store in TLS in the future.
if (!UnsafeTlsSetValue(gThreadTLSIndex, NULL))
{
ThrowOutOfMemory();
}
if (!UnsafeTlsSetValue(GetAppDomainTLSIndex(), NULL))
{
ThrowOutOfMemory();
}
#endif
// reset any unstarted bits on the thread object
FastInterlockAnd((ULONG *) &pThread->m_State, ~Thread::TS_Unstarted);
FastInterlockOr((ULONG *) &pThread->m_State, Thread::TS_LegalToJoin);
ThreadStore::AddThread(pThread);
BOOL fOK = SetThread(pThread);
_ASSERTE (fOK);
fOK = SetAppDomain(pThread->GetDomain());
_ASSERTE (fOK);
// We now have a Thread object visable to the RS. unmark special status.
hCantStop.Release();
pThread->SetupThreadForHost();
threadHolder.SuppressRelease();
FastInterlockOr((ULONG *) &pThread->m_State, Thread::TS_FullyInitialized);
#ifdef _DEBUG
pThread->AddFiberInfo(Thread::ThreadTrackInfo_Lifetime);
#endif
#ifdef DEBUGGING_SUPPORTED
//
// If we're debugging, let the debugger know that this
// thread is up and running now.
//
if (CORDebuggerAttached())
{
g_pDebugInterface->ThreadCreated(pThread);
}
else
{
LOG((LF_CORDB, LL_INFO10000, "ThreadCreated() not called due to CORDebuggerAttached() being FALSE for thread 0x%x\n", pThread->GetThreadId()));
}
#endif // DEBUGGING_SUPPORTED
#ifdef PROFILING_SUPPORTED
// If a profiler is present, then notify the profiler that a
// thread has been created.
if (!IsGCSpecialThread())
{
BEGIN_PIN_PROFILER(CORProfilerTrackThreads());
{
GCX_PREEMP();
g_profControlBlock.pProfInterface->ThreadCreated(
(ThreadID)pThread);
}
DWORD osThreadId = ::GetCurrentThreadId();
g_profControlBlock.pProfInterface->ThreadAssignedToOSThread(
(ThreadID)pThread, osThreadId);
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
_ASSERTE(!pThread->IsBackground()); // doesn't matter, but worth checking
pThread->SetBackground(TRUE);
ensurePreemptive.SuppressRelease();
if (IsThreadPoolWorkerSpecialThread())
{
FastInterlockOr((ULONG *) &pThread->m_State, Thread::TS_TPWorkerThread);
}
else if (IsThreadPoolIOCompletionSpecialThread())
{
FastInterlockOr ((ULONG *) &pThread->m_State, Thread::TS_CompletionPortThread);
}
else if (IsTimerSpecialThread() || IsWaitSpecialThread())
{
FastInterlockOr((ULONG *) &pThread->m_State, Thread::TS_TPWorkerThread);
}
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
if (g_fEnableARM)
{
pThread->QueryThreadProcessorUsage();
}
#endif // FEATURE_APPDOMAIN_RESOURCE_MONITORING
#ifdef FEATURE_EVENT_TRACE
ETW::ThreadLog::FireThreadCreated(pThread);
#endif // FEATURE_EVENT_TRACE
return pThread;
}
//-------------------------------------------------------------------------
void STDMETHODCALLTYPE CorMarkThreadInThreadPool()
{
LIMITED_METHOD_CONTRACT;
BEGIN_ENTRYPOINT_VOIDRET;
END_ENTRYPOINT_VOIDRET;
// this is no longer needed after our switch to
// the Win32 threadpool.
// keeping in mscorwks for compat reasons and to keep rotor sscoree and
// mscoree consistent.
}
//-------------------------------------------------------------------------
// Public function: SetupUnstartedThread()
// This sets up a Thread object for an exposed System.Thread that
// has not been started yet. This allows us to properly enumerate all threads
// in the ThreadStore, so we can report on even unstarted threads. Clearly
// there is no physical thread to match, yet.
//
// When there is, complete the setup with code:Thread::HasStarted()
//-------------------------------------------------------------------------
Thread* SetupUnstartedThread(BOOL bRequiresTSL)
{
CONTRACTL {
THROWS;
if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
_ASSERTE(ThreadInited());
Thread* pThread = new Thread();
FastInterlockOr((ULONG *) &pThread->m_State,
(Thread::TS_Unstarted | Thread::TS_WeOwn));
ThreadStore::AddThread(pThread, bRequiresTSL);
return pThread;
}
FCIMPL0(INT32, GetRuntimeId_Wrapper)
{
FCALL_CONTRACT;
return GetRuntimeId();
}
FCIMPLEND
//-------------------------------------------------------------------------
// Public function: DestroyThread()
// Destroys the specified Thread object, for a thread which is about to die.
//-------------------------------------------------------------------------
void DestroyThread(Thread *th)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
}
CONTRACTL_END;
_ASSERTE (th == GetThread());
_ASSERTE(g_fEEShutDown || th->m_dwLockCount == 0 || th->m_fRudeAborted);
#ifdef FEATURE_APPDOMAIN_RESOURCE_MONITORING
if (g_fEnableARM)
{
AppDomain* pDomain = th->GetDomain();
pDomain->UpdateProcessorUsage(th->QueryThreadProcessorUsage());
FireEtwThreadTerminated((ULONGLONG)th, (ULONGLONG)pDomain, GetClrInstanceId());
}
#endif // FEATURE_APPDOMAIN_RESOURCE_MONITORING
th->FinishSOWork();
GCX_PREEMP_NO_DTOR();
if (th->IsAbortRequested()) {
// Reset trapping count.
th->UnmarkThreadForAbort(Thread::TAR_ALL);
}
// Clear any outstanding stale EH state that maybe still active on the thread.
#ifdef WIN64EXCEPTIONS
ExceptionTracker::PopTrackers((void*)-1);
#else // !WIN64EXCEPTIONS
#ifdef _TARGET_X86_
PTR_ThreadExceptionState pExState = th->GetExceptionState();
if (pExState->IsExceptionInProgress())
{
GCX_COOP();
pExState->GetCurrentExceptionTracker()->UnwindExInfo((void *)-1);
}
#else // !_TARGET_X86_
#error Unsupported platform
#endif // _TARGET_X86_
#endif // WIN64EXCEPTIONS
if (g_fEEShutDown == 0)
{
th->SetThreadState(Thread::TS_ReportDead);
th->OnThreadTerminate(FALSE);
}
}
//-------------------------------------------------------------------------
// Public function: DetachThread()
// Marks the thread as needing to be destroyed, but doesn't destroy it yet.
//-------------------------------------------------------------------------
HRESULT Thread::DetachThread(BOOL fDLLThreadDetach)
{
// !!! Can not use contract here.
// !!! Contract depends on Thread object for GC_TRIGGERS.