-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
threads.cpp
8144 lines (6790 loc) · 248 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.
//
// THREADS.CPP
//
#include "common.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 "corhost.h"
#include "jitinterface.h"
#include "eventtrace.h"
#include "comutilnative.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#include "wrappers.h"
#include "appdomain.inl"
#include "vmholder.h"
#include "exceptmacros.h"
#ifdef FEATURE_COMINTEROP
#include "runtimecallablewrapper.h"
#include "interoputil.h"
#include "interoputil.inl"
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_COMINTEROP_APARTMENT_SUPPORT
#include "olecontexthelpers.h"
#include "roapi.h"
#endif // FEATURE_COMINTEROP_APARTMENT_SUPPORT
#ifdef FEATURE_SPECIAL_USER_MODE_APC
#include "asmconstants.h"
#include <versionhelpers.h>
#endif
static const PortableTailCallFrame g_sentinelTailCallFrame = { NULL, NULL };
TailCallTls::TailCallTls()
// A new frame will always be allocated before the frame is modified,
// so casting away const is ok here.
: m_frame(const_cast<PortableTailCallFrame*>(&g_sentinelTailCallFrame))
, m_argBuffer(NULL)
{
}
#ifndef _MSC_VER
thread_local RuntimeThreadLocals t_runtime_thread_locals;
#endif
Thread* STDCALL GetThreadHelper()
{
return GetThreadNULLOk();
}
TailCallArgBuffer* TailCallTls::AllocArgBuffer(int size, void* gcDesc)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END
_ASSERTE(size >= (int)offsetof(TailCallArgBuffer, Args));
if (m_argBuffer != NULL && m_argBuffer->Size < size)
{
FreeArgBuffer();
}
if (m_argBuffer == NULL)
{
m_argBuffer = (TailCallArgBuffer*)new (nothrow) BYTE[size];
if (m_argBuffer == NULL)
return NULL;
m_argBuffer->Size = size;
}
m_argBuffer->State = TAILCALLARGBUFFER_ACTIVE;
m_argBuffer->GCDesc = gcDesc;
if (gcDesc != NULL)
{
memset(m_argBuffer->Args, 0, size - offsetof(TailCallArgBuffer, Args));
}
return m_argBuffer;
}
#if defined (_DEBUG_IMPL) || defined(_PREFAST_)
thread_local int t_ForbidGCLoaderUseCount;
#endif
uint64_t Thread::dead_threads_non_alloc_bytes = 0;
SPTR_IMPL(ThreadStore, ThreadStore, s_pThreadStore);
CONTEXT* ThreadStore::s_pOSContext = NULL;
BYTE* ThreadStore::s_pOSContextBuffer = NULL;
CLREvent *ThreadStore::s_pWaitForStackCrawlEvent;
#ifndef DACCESS_COMPILE
BOOL Thread::s_fCleanFinalizedThread = FALSE;
UINT64 Thread::s_monitorLockContentionCountOverflow = 0;
CrstStatic g_DeadlockAwareCrst;
//
// A transient thread value that indicates this thread is currently walking its stack
// or the stack of another thread. This value is useful to help short-circuit
// some problematic checks in the loader, guarantee that types & assemblies
// encountered during the walk must already be loaded, and provide information to control
// assembly loading behavior during stack walks.
//
// This value is set around the main portions of the stack walk (as those portions may
// enter the type & assembly loaders). This is also explicitly cleared while the
// walking thread calls the stackwalker callback or needs to execute managed code, as
// such calls may execute arbitrary code unrelated to the actual stack walking, and
// may never return, in the case of exception stackwalk callbacks.
//
thread_local Thread* t_pStackWalkerWalkingThread;
#if defined(_DEBUG)
BOOL MatchThreadHandleToOsId ( HANDLE h, DWORD osId )
{
#ifndef TARGET_UNIX
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 // !TARGET_UNIX
return TRUE;
#endif // !TARGET_UNIX
}
#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)
{
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(IsExecutingOnAltStack() || espVal < pFrame);
_ASSERTE(IsExecutingOnAltStack() || pFrame < m_CacheStackBase);
_ASSERTE(pFrame->GetFrameType() < Frame::TYPE_COUNT);
pFrame = pFrame->m_Next;
}
}
#endif // _DEBUG
//************************************************************************
// PRIVATE GLOBALS
//************************************************************************
extern uint64_t getTimeStamp();
extern uint64_t getTickFrequency();
uint64_t tgetFrequency() {
static uint64_t cachedFreq = (uint64_t) -1;
if (cachedFreq != (uint64_t) -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() == (PCODE)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;
}
#ifndef _MSC_VER
__thread ThreadLocalInfo gCurrentThreadInfo;
#endif
#ifndef DACCESS_COMPILE
void SetThread(Thread* t)
{
LIMITED_METHOD_CONTRACT
gCurrentThreadInfo.m_pThread = t;
if (t != NULL)
{
InitializeCurrentThreadsStaticData(t);
EnsureTlsDestructionMonitor();
t->InitRuntimeThreadLocals();
}
// Clear or set the app domain to the one domain based on if the thread is being nulled out or set
gCurrentThreadInfo.m_pAppDomain = t == NULL ? NULL : AppDomain::GetCurrentDomain();
}
BOOL Thread::Alert ()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
BOOL fRetVal = FALSE;
{
HANDLE handle = GetThreadHandle();
if (handle != INVALID_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 (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
BOOL alertable = (mode & WaitMode_Alertable)?TRUE:FALSE;
Thread *pCurThread = GetThreadNULLOk();
_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) {
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 TARGET_UNIX
if (!CPUGroupInfo::CanEnableGCCPUGroups() ||
!CPUGroupInfo::CanEnableThreadUseAllCpuGroups() ||
!CPUGroupInfo::CanAssignCpuGroupsToThreads())
{
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 // !TARGET_UNIX
}
void Thread::ClearThreadCPUGroupAffinity()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifndef TARGET_UNIX
if (!CPUGroupInfo::CanEnableGCCPUGroups() ||
!CPUGroupInfo::CanEnableThreadUseAllCpuGroups() ||
!CPUGroupInfo::CanAssignCpuGroupsToThreads())
{
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 // !TARGET_UNIX
}
DWORD Thread::StartThread()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifdef _DEBUG
_ASSERTE (m_Creator.IsCurrentThread());
m_Creator.Clear();
#endif
_ASSERTE (GetThreadHandle() != INVALID_HANDLE_VALUE);
DWORD dwRetVal = ClrResumeThread(GetThreadHandle());
return dwRetVal;
}
// Class static data:
LONG Thread::m_DebugWillSyncCount = -1;
LONG Thread::m_DetachCount = 0;
LONG Thread::m_ActiveDetachCount = 0;
static void DeleteThread(Thread* pThread)
{
CONTRACTL {
NOTHROW;
if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
//_ASSERTE (pThread == GetThread());
SetThread(NULL);
if (pThread->HasThreadStateNC(Thread::TSNC_ExistInThreadStore))
{
pThread->DetachThread(FALSE);
}
else
{
#ifdef FEATURE_COMINTEROP
pThread->RevokeApartmentSpy();
#endif // FEATURE_COMINTEROP
pThread->SetThreadState(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;
}
}
static void EnsurePreemptive()
{
WRAPPER_NO_CONTRACT;
Thread *pThread = GetThreadNULLOk();
if (pThread && pThread->PreemptiveGCDisabled())
{
pThread->EnablePreemptiveGC();
}
}
typedef StateHolder<DoNothing, EnsurePreemptive> EnsurePreemptiveModeIfException;
Thread* SetupThread()
{
CONTRACTL {
THROWS;
if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
Thread* pThread;
if ((pThread = GetThreadNULLOk()) != NULL)
return pThread;
// 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->GetPendingThreadCount() != 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 the thread. It's just an unrelated
// thread spinning up.
if (pThread)
{
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);
SetupTLSForThread();
pThread->InitThread();
pThread->PrepareApartmentAndContext();
// reset any unstarted bits on the thread object
pThread->ResetThreadState(Thread::TS_Unstarted);
pThread->SetThreadState(Thread::TS_LegalToJoin);
ThreadStore::AddThread(pThread);
SetThread(pThread);
#ifdef FEATURE_INTEROP_DEBUGGING
// Ensure that debugger word slot is allocated
TlsSetValue(g_debuggerWordTLSIndex, 0);
#endif
// We now have a Thread object visable to the RS. unmark special status.
hCantStop.Release();
threadHolder.SuppressRelease();
pThread->SetThreadState(Thread::TS_FullyInitialized);
#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_PROFILER_CALLBACK(CORProfilerTrackThreads());
{
GCX_PREEMP();
(&g_profControlBlock)->ThreadCreated(
(ThreadID)pThread);
}
DWORD osThreadId = ::GetCurrentThreadId();
(&g_profControlBlock)->ThreadAssignedToOSThread(
(ThreadID)pThread, osThreadId);
END_PROFILER_CALLBACK();
}
#endif // PROFILING_SUPPORTED
_ASSERTE(!pThread->IsBackground()); // doesn't matter, but worth checking
pThread->SetBackground(TRUE);
ensurePreemptive.SuppressRelease();
#ifdef FEATURE_EVENT_TRACE
ETW::ThreadLog::FireThreadCreated(pThread);
#endif // FEATURE_EVENT_TRACE
return pThread;
}
//-------------------------------------------------------------------------
// 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;
if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
HRESULT hr = S_OK;
Thread *pThread = GetThreadNULLOk();
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;
}
//-------------------------------------------------------------------------
// 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(SetupUnstartedThreadFlags flags)
{
CONTRACTL {
THROWS;
if (GetThreadNULLOk()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
Thread* pThread = new Thread();
if (flags & SUTF_ThreadStoreLockAlreadyTaken)
{
_ASSERTE(ThreadStore::HoldingThreadStore());
pThread->SetThreadStateNC(Thread::TSNC_TSLTakenForStartup);
}
pThread->SetThreadState((Thread::ThreadState)(Thread::TS_Unstarted | Thread::TS_WeOwn));
ThreadStore::AddThread(pThread);
return pThread;
}
//-------------------------------------------------------------------------
// 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());
GCX_PREEMP_NO_DTOR();
if (th->IsAbortRequested()) {
// Reset trapping count.
th->UnmarkThreadForAbort();
}
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.
// !!! At the end of this function, we call InternalSwitchOut,
// !!! and then GetThread()=NULL, and dtor of contract does not work any more.
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
#ifdef FEATURE_COMINTEROP
IErrorInfo *pErrorInfo;
// Avoid calling GetErrorInfo() if ole32 has already executed the DLL_THREAD_DETACH,
// otherwise we'll cause ole32 to re-allocate and leak its TLS data (SOleTlsData).
if (ClrTeb::GetOleReservedPtr() != NULL && GetErrorInfo(0, &pErrorInfo) == S_OK)
{
// if this is our IErrorInfo, release it now - we don't want ole32 to do it later as
// part of its DLL_THREAD_DETACH as we won't be able to handle the call at that point
if (!ComInterfaceSlotIs(pErrorInfo, 2, Unknown_ReleaseSpecial_IErrorInfo))
{
// if it's not our IErrorInfo, put it back
SetErrorInfo(0, pErrorInfo);
}
pErrorInfo->Release();
}
// Revoke our IInitializeSpy registration only if we are not in DLL_THREAD_DETACH
// (COM will do it or may have already done it automatically in that case).
if (!fDLLThreadDetach)
{
RevokeApartmentSpy();
}
#endif // FEATURE_COMINTEROP
_ASSERTE(!PreemptiveGCDisabled());
_ASSERTE ((m_State & Thread::TS_Detached) == 0);
_ASSERTE (this == GetThread());
InterlockedIncrement(&Thread::m_DetachCount);
if (IsAbortRequested()) {
// Reset trapping count.
UnmarkThreadForAbort();
}
if (!IsBackground())
{
InterlockedIncrement(&Thread::m_ActiveDetachCount);
ThreadStore::CheckForEEShutdown();
}
HANDLE hThread = GetThreadHandle();
SetThreadHandle (INVALID_HANDLE_VALUE);
while (m_dwThreadHandleBeingUsed > 0)
{
// Another thread is using the handle now.
// We can not call __SwitchToThread since we can not go back to host.
ClrSleepEx(10, FALSE);
}
if (m_WeOwnThreadHandle && m_ThreadHandleForClose == INVALID_HANDLE_VALUE)
{
m_ThreadHandleForClose = hThread;
}
CooperativeCleanup();
// We need to make sure that TLS are touched last here.
SetThread(NULL);
SetThreadState((Thread::ThreadState)(Thread::TS_Detached | Thread::TS_ReportDead));
// Do not touch Thread object any more. It may be destroyed.
// These detached threads will be cleaned up by finalizer thread. But if the process uses
// little managed heap, it will be a while before GC happens, and finalizer thread starts
// working on detached thread. So we wake up finalizer thread to clean up resources.
//
// (It's possible that this is the startup thread, and startup failed, and so the finalization
// machinery isn't fully initialized. Hence this check.)
if (g_fEEStarted)
FinalizerThread::EnableFinalization();
return S_OK;
}
DWORD GetRuntimeId()
{
LIMITED_METHOD_CONTRACT;
#ifdef HOST_WINDOWS
return _tls_index;
#else
return 0;
#endif
}
#ifdef _DEBUG
DWORD_PTR Thread::OBJREF_HASH = OBJREF_TABSIZE;
#endif
extern "C" void STDCALL JIT_PatchedCodeStart();
extern "C" void STDCALL JIT_PatchedCodeLast();
static void* s_barrierCopy = NULL;
BYTE* GetWriteBarrierCodeLocation(VOID* barrier)
{
if (IsWriteBarrierCopyEnabled())
{
return (BYTE*)PINSTRToPCODE((TADDR)s_barrierCopy + ((TADDR)barrier - (TADDR)JIT_PatchedCodeStart));
}
else
{
return (BYTE*)barrier;
}
}
BOOL IsIPInWriteBarrierCodeCopy(PCODE controlPc)
{
if (IsWriteBarrierCopyEnabled())
{
return (s_barrierCopy <= (void*)controlPc && (void*)controlPc < ((BYTE*)s_barrierCopy + ((BYTE*)JIT_PatchedCodeLast - (BYTE*)JIT_PatchedCodeStart)));
}
else
{
return FALSE;
}
}
PCODE AdjustWriteBarrierIP(PCODE controlPc)
{
_ASSERTE(IsIPInWriteBarrierCodeCopy(controlPc));