-
Notifications
You must be signed in to change notification settings - Fork 25
/
threads.cpp
14755 lines (12237 loc) · 444 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
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
/* 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 "gcscan.h"
#include "gc.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 "comstring.h"
#include "jitinterface.h"
#include "threads.inl"
#include "appdomainstack.inl"
#include "appdomainhelper.h"
#include "comutilnative.h"
#include "fusion.h"
#include "wrappers.h"
#include "memoryreport.h"
#include "nativeoverlapped.h"
#include "mdaassistantsptr.h"
#include "appdomain.inl"
#include "vmholder.h"
#include "exceptmacros.h"
// from ntstatus.h
#define STATUS_SUSPEND_COUNT_EXCEEDED ((NTSTATUS)0xC000004AL)
#ifndef CONTEXT_EXCEPTION_ACTIVE
#define CONTEXT_EXCEPTION_ACTIVE 0x8000000
#endif//CONTEXT_EXCEPTION_ACTIVE
#ifndef CONTEXT_SERVICE_ACTIVE
#define CONTEXT_SERVICE_ACTIVE 0x10000000
#endif//CONTEXT_SERVICE_ACTIVE
#ifndef CONTEXT_EXCEPTION_REPORTING
#define CONTEXT_EXCEPTION_REPORTING 0x80000000
#endif//CONTEXT_EXCEPTION_REPORTING
#ifndef CONTEXT_EXCEPTION_REQUEST
#define CONTEXT_EXCEPTION_REQUEST 0x40000000
#endif//CONTEXT_EXCEPTION_REQUEST
#if defined(_X86_) || defined(_AMD64_)
#define HIJACK_NONINTERRUPTIBLE_THREADS
#endif
SPTR_IMPL(ThreadStore, ThreadStore, s_pThreadStore);
CONTEXT *ThreadStore::s_pOSContext = NULL;
CLREvent *ThreadStore::s_pWaitForStackCrawlEvent;
#ifndef DACCESS_COMPILE
#include "constrainedexecutionregion.h"
CLREvent* ThreadStore::s_hAbortEvt = NULL;
CLREvent* ThreadStore::s_hAbortEvtCache = NULL;
BOOL Thread::s_fCleanFinalizedThread = FALSE;
bool Thread::s_fSysSuspendInProgress = false;
CLREvent* Thread::g_pGCSuspendEvent = NULL;
CrstStatic g_DeadlockAwareCrst;
// Here starts the unmanaged portion of the compressed stack code.
// The mission of this code is to provide us with an intermediate
// step between the stackwalk that has to happen when we make an
// async call and the formation of the managed PermissionListSet
// object since the latter is a very expensive operation.
//
// The basic structure of the compressed stack at this point is
// a list of compressed stack entries, where each entry represents
// one piece of "interesting" information found during the stackwalk.
// At this time, the "interesting" bits are appdomain transitions,
// assembly security, descriptors, appdomain security descriptors,
// frame security descriptors, and other compressed stacks. Of course,
// if that's all there was to it, there wouldn't be an explanatory
// comment even close to this size before you even started reading
// the code. Since we need to form a compressed stack whenever an
// async operation is registered, it is a very perf critical piece
// of code. As such, things get very much more complicated than
// the simple list of objects described above. The special bonus
// feature is that we need to handle appdomain unloads since the
// list tracks appdomain specific data. Keep reading to find out
// more.
#if defined(_X86_)
#define GetRedirectHandlerForGCThreadControl() (&Thread::RedirectedHandledJITCaseForGCThreadControl)
#define GetRedirectHandlerForDbgThreadControl() (&Thread::RedirectedHandledJITCaseForDbgThreadControl)
#define GetRedirectHandlerForUserSuspend() (&Thread::RedirectedHandledJITCaseForUserSuspend)
#define GetRedirectHandlerForYieldTask() (&Thread::RedirectedHandledJITCaseForYieldTask)
#endif // _IA64_ || _AMD64_
#if USE_INDIRECT_GET_THREAD_APPDOMAIN
EXTERN_C Thread* __stdcall GetThreadGeneric(VOID);
EXTERN_C AppDomain* __stdcall GetAppDomainGeneric(VOID);
#endif
// #define NEW_TLS 1
#ifdef _DEBUG
void Thread::SetFrame(Frame *pFrame)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
DEBUG_ONLY;
}
CONTRACTL_END;
_ASSERTE(NULL != pFrame);
m_pFrame = pFrame;
_ASSERTE(PreemptiveGCDisabled());
if (this != GetThread())
return;
// 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->GetFrameType() < Frame::TYPE_COUNT);
pFrame = pFrame->m_Next;
}
}
#endif // _DEBUG
//************************************************************************
// PRIVATE GLOBALS
//************************************************************************
#endif // #ifndef DACCESS_COMPILE
// 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.
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->GetTransitionType() == Frame::TT_InternalCall)
{
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.
return true;
}
else
{
// The frame is fully initialized.
return false;
}
}
pFrame = pFrame->Next();
}
}
return false;
}
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 )
}
#ifndef DACCESS_COMPILE
#define ThreadInited() (gThreadTLSIndex != TLS_OUT_OF_INDEXES)
// Every PING_JIT_TIMEOUT ms, check to see if a thread in JITted code has wandered
// into some fully interruptible code (or should have a different hijack to improve
// our chances of snagging it at a safe spot).
#define PING_JIT_TIMEOUT 250
// When we find a thread in a spot that's not safe to abort -- how long to wait before
// we try again.
#define ABORT_POLL_TIMEOUT 10
#ifdef _DEBUG
#define ABORT_FAIL_TIMEOUT 40000
#endif // _DEBUG
//
// CANNOT USE IsBad*Ptr() methods here. They are *banned* APIs because of various
// reasons (see http://winweb/wincet/bannedapis.htm).
//
#define IS_VALID_WRITE_PTR(addr, size) _ASSERTE(addr != NULL)
#define IS_VALID_CODE_PTR(addr) _ASSERTE(addr != NULL)
void Thread::SetSysSuspendInProgress(StateHolderParam)
{
_ASSERTE(ThreadStore::HoldingThreadStore() || g_fProcessDetach);
_ASSERTE(!s_fSysSuspendInProgress || g_fProcessDetach);
s_fSysSuspendInProgress = true;
}
void Thread::ResetSysSuspendInProgress(StateHolderParam)
{
_ASSERTE(ThreadStore::HoldingThreadStore() || g_fProcessDetach);
_ASSERTE(s_fSysSuspendInProgress || g_fProcessDetach);
s_fSysSuspendInProgress = false;
}
BOOL Thread::Alert ()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
BOOL fRetVal = FALSE;
HostComHolder<IHostTask> pHostTask(GetHostTaskWithAddRef());
if (pHostTask && !HasThreadStateNC(TSNC_OSAlertableWait)) {
HRESULT hr;
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
hr = pHostTask->Alert();
END_SO_TOLERANT_CODE_CALLING_HOST;
fRetVal = SUCCEEDED(hr);
}
else
{
HANDLE handle = GetThreadHandle();
if (handle != INVALID_HANDLE_VALUE && handle != SWITCHOUT_HANDLE_VALUE)
{
fRetVal = ::QueueUserAPC(UserInterruptAPC, handle, APC_Code);
}
}
return fRetVal;
}
struct HostJoinOnThreadArgs
{
IHostTask *pHostTask;
WaitMode mode;
};
DWORD HostJoinOnThread (void *args, DWORD timeout, DWORD option)
{
CONTRACTL {
THROWS;
if (GetThread()) {GC_TRIGGERS;} else {DISABLED(GC_NOTRIGGER);}
}
CONTRACTL_END;
HostJoinOnThreadArgs *joinArgs = (HostJoinOnThreadArgs*) args;
IHostTask *pHostTask = joinArgs->pHostTask;
if ((joinArgs->mode & WaitMode_InDeadlock) == 0)
{
option |= WAIT_NOTINDEADLOCK;
}
HRESULT hr;
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
hr = pHostTask->Join(timeout, option);
END_SO_TOLERANT_CODE_CALLING_HOST;
if (hr == S_OK) {
return WAIT_OBJECT_0;
}
else if (hr == HOST_E_TIMEOUT) {
return WAIT_TIMEOUT;
}
else if (hr == HOST_E_INTERRUPTED) {
_ASSERTE (option & WAIT_ALERTABLE);
Thread *pThread = GetThread();
if (pThread)
{
Thread::UserInterruptAPC(APC_Code);
}
return WAIT_IO_COMPLETION;
}
else if (hr == HOST_E_ABANDONED)
{
// The task died.
return WAIT_OBJECT_0;
}
else if (hr == HOST_E_DEADLOCK)
{
_ASSERTE ((option & WAIT_NOTINDEADLOCK) == 0);
RaiseDeadLockException();
}
_ASSERTE (!"Unknown host join status\n");
return E_FAIL;
}
DWORD Thread::Join(DWORD timeout, BOOL alertable)
{
WRAPPER_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());
HostComHolder<IHostTask> pHostTask (GetHostTaskWithAddRef());
if (pHostTask == NULL) {
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);
}
}
else {
HostJoinOnThreadArgs args = {pHostTask, mode};
if (pCurThread) {
return GetThread()->DoAppropriateWait(HostJoinOnThread, &args, timeout, mode);
}
else {
return HostJoinOnThread (&args,timeout,alertable?WAIT_ALERTABLE:0);
}
}
}
extern INT32 MapFromNTPriority(INT32 NTPriority);
BOOL Thread::SetThreadPriority(
int nPriority // thread priority level
)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
BOOL fRet;
HostComHolder<IHostTask> pHostTask (GetHostTaskWithAddRef());
if (pHostTask != NULL) {
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
fRet = (pHostTask->SetPriority(nPriority) == S_OK);
END_SO_TOLERANT_CODE_CALLING_HOST;
}
else
{
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)
{
pObject->SetPriority (MapFromNTPriority(nPriority));
}
}
return fRet;
}
int Thread::GetThreadPriority()
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
int nRetVal = -1;
HostComHolder<IHostTask> pHostTask(GetHostTaskWithAddRef());
if (pHostTask != NULL) {
int nPriority;
HRESULT hr;
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
hr = pHostTask->GetPriority(&nPriority);
END_SO_TOLERANT_CODE_CALLING_HOST;
nRetVal = (hr == S_OK)?nPriority:THREAD_PRIORITY_ERROR_RETURN;
}
else if (GetThreadHandle() == INVALID_HANDLE_VALUE) {
nRetVal = FALSE;
}
else
nRetVal = ::GetThreadPriority(GetThreadHandle());
return nRetVal;
}
// When SuspendThread returns, target thread may still be executing user code.
// We can not access data, e.g. m_fPreemptiveGCDisabled, changed by target thread.
// But our code depends on reading these data. To make this operation safe, we
// call GetThreadContext which returns only after target thread does not execute
// any user code.
// Message from David Cutler
/*
After SuspendThread returns, can the suspended thread continue to execute code in user mode?
[David Cutler] The suspended thread cannot execute any more user code, but it might be currently running
on a logical processor whose other logical processor is currently actually executing another thread.
In this case the target thread will not suspend until the hardware switches back to executing instructions
on its logical processor. In this case even the memory barrier would not necessarily work a better solution
would be to use interlocked operations on the variable itself.
After SuspendThread returns, does the store buffer of the CPU for the suspended thread still need to drain?
Historically, weve assumed that the answer to both questions is No. But on one 4/8 hyper-threaded machine
running Win2K3 SP1 build 1421, weve seen two stress failures where SuspendThread returns while writes seem to still be in flight.
Usually after we suspend a thread, we then call GetThreadContext. This seems to guarantee consistency.
But there are places we would like to avoid GetThreadContext, if its safe and legal.
[David Cutler] Get context delivers a APC to the target thread and waits on an event that will be set
when the target thread has delivered its context.
Chris.
*/
// Message from Neill Clift
/*
What SuspendThread does is insert an APC block into a target thread and request an inter-processor interrupt to
do the APC interrupt. It doesnt wait till the thread actually enters some state or the interrupt has been serviced.
I took a quick look at the APIC spec in the Intel manuals this morning. Writing to the APIC posts a message on a bus.
Processors accept messages and presumably queue the s/w interrupts at this time. We dont wait for this acceptance
when we send the IPI so at least on APIC machines when you suspend a thread it continues to execute code for some short time
after the routine returns. We use other mechanisms for IPI and so it could work differently on different h/w.
*/
BOOL EnsureThreadIsSuspended (HANDLE hThread, Thread* pThread)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
WRAPPER_CONTRACT;
CONTEXT ctx;
ctx.ContextFlags = CONTEXT_INTEGER;
BOOL ret;
ret = ::GetThreadContext(hThread, &ctx);
return ret;
}
FORCEINLINE VOID MyEnterLogLock(StateHolderParam)
{
EnterLogLock();
}
FORCEINLINE VOID MyLeaveLogLock(StateHolderParam)
{
LeaveLogLock();
}
// SuspendThread
// Attempts to OS-suspend the thread, whichever GC mode it is in.
// Arguments:
// fOneTryOnly - If TRUE, report failure if the thread has its
// m_dwForbidSuspendThread flag set. If FALSE, retry.
// pdwSuspendCount - If non-NULL, will contain the return code
// of the underlying OS SuspendThread call on success,
// undefined on any kind of failure.
// Return value:
// A SuspendThreadResult value indicating success or failure.
Thread::SuspendThreadResult Thread::SuspendThread(BOOL fOneTryOnly, DWORD *pdwSuspendCount)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef STRESS_LOG
if (StressLog::StressLogOn(-1, 0))
{
// Make sure to create the stress log for the current thread
// (if needed) before we suspend the target thread. The target
// thread may be holding the stress log lock when we suspend it,
// which could cause a deadlock.
if (StressLog::CreateThreadStressLog() == NULL)
{
return STR_NoStressLog;
}
}
#endif
volatile HANDLE hThread;
SuspendThreadResult str = (SuspendThreadResult) -1;
DWORD dwSuspendCount = 0;
DWORD tries = 1;
#if defined(_DEBUG)
// Stop the stress log from allocating any new memory while in this function
// as that can lead to deadlocks
CantAllocHolder hldrCantAlloc;
#endif
while (TRUE) {
StateHolder<MyEnterLogLock, MyLeaveLogLock> LogLockHolder(FALSE);
CounterHolder handleHolder(&m_dwThreadHandleBeingUsed);
hThread = GetThreadHandle();
if (hThread == INVALID_HANDLE_VALUE) {
str = STR_UnstartedOrDead;
break;
}
else if (hThread == SWITCHOUT_HANDLE_VALUE) {
str = STR_SwitchedOut;
break;
}
{
// It is important to avoid two threads suspending each other.
// Before a thread suspends another, it increments its own m_dwForbidSuspendThread count first,
// then it checks the target thread's m_dwForbidSuspendThread.
ForbidSuspendThreadHolder forbidSuspend;
if ((m_dwForbidSuspendThread != 0))
{
goto retry;
}
// We do not want to suspend the target thread while it is holding the log lock.
// By acquiring the lock ourselves, we know that this is not the case.
LogLockHolder.Acquire();
dwSuspendCount = ::SuspendThread(hThread);
}
if ((int)dwSuspendCount >= 0)
{
if (!EnsureThreadIsSuspended(hThread, this))
{
::ResumeThread(hThread);
str = STR_Failure;
break;
}
if (hThread == GetThreadHandle())
{
if (m_dwForbidSuspendThread != 0)
{
::ResumeThread(hThread);
goto retry;
}
// We suspend the right thread
#ifdef _DEBUG
Thread *pCurThread = GetThread();
if (pCurThread) {
pCurThread->m_dwSuspendThread ++;
_ASSERTE (pCurThread->m_dwSuspendThread > 0);
}
#endif
IncCantAllocCount();
m_ThreadHandleForResume = hThread;
str = STR_Success;
break;
}
else
{
::ResumeThread(hThread);
continue;
}
}
else {
// We can get here either SuspendThread fails
// Or the fiber thread dies after this fiber switched out.
if ((int)dwSuspendCount != -1) {
STRESS_LOG1(LF_SYNC, LL_INFO1000, "In Thread::SuspendThread ::SuspendThread returned %x\n", dwSuspendCount);
}
if (GetThreadHandle() == SWITCHOUT_HANDLE_VALUE) {
str = STR_SwitchedOut;
break;
}
else {
// Our callers generally expect that STR_Failure means that
// the thread has exited.
str = STR_Failure;
break;
}
}
retry:
handleHolder.Release();
LogLockHolder.Release();
if (fOneTryOnly)
{
str = STR_Forbidden;
break;
}
// When looking for deadlocks we need to allow the target thread to run in order to make some progress.
// On multi processor machines we saw the suspending thread resuming immediately after the __SwitchToThread()
// because it has another few processors available. As a consequence the target thread was being Resumed and
// Suspended right away, w/o a real chance to make any progress.
if ((tries++) % 20 != 0) {
YieldProcessor(); // play nice on hyperthreaded CPUs
} else {
__SwitchToThread(0);
}
}
#ifdef PROFILING_SUPPORTED
if (CORProfilerTrackSuspends() && str == STR_Success)
{
// Must use wrapper to ensure forbid suspend count is incremented.
// (See RuntimeTheadSuspendedWrapper in threads.h for more information.)
RuntimeThreadSuspendedWrapper((ThreadID)this, (ThreadID)GetThread());
}
#endif // PROFILING_SUPPORTED
if (pdwSuspendCount != NULL)
{
*pdwSuspendCount = dwSuspendCount;
}
_ASSERTE(str != (SuspendThreadResult) -1);
return str;
}
DWORD Thread::StartThread()
{
WRAPPER_CONTRACT;
DWORD dwRetVal = (DWORD) -1;
#ifdef _DEBUG
_ASSERTE (m_Creater.IsSameThread());
m_Creater.ResetThreadId();
#endif
HostComHolder<IHostTask> pHostTask(GetHostTaskWithAddRef());
if (pHostTask)
{
HRESULT hr;
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
hr = pHostTask->Start();
END_SO_TOLERANT_CODE_CALLING_HOST;
if (hr == S_OK) {
dwRetVal = 1;
}
else
dwRetVal = (DWORD) -1;
}
else
{
_ASSERTE (GetThreadHandle() != INVALID_HANDLE_VALUE &&
GetThreadHandle() != SWITCHOUT_HANDLE_VALUE);
dwRetVal = ::ResumeThread(GetThreadHandle());
}
return dwRetVal;
}
DWORD Thread::ResumeThread()
{
WRAPPER_CONTRACT;
_ASSERTE (m_ThreadHandleForResume != INVALID_HANDLE_VALUE);
_ASSERTE (m_pHostTask == 0 || GetThreadHandle() != SWITCHOUT_HANDLE_VALUE);
//DWORD res = ::ResumeThread(GetThreadHandle());
DWORD res = ::ResumeThread(m_ThreadHandleForResume);
_ASSERTE (res != 0 && "Thread is not previously suspended");
#ifdef _DEBUG_IMPL
_ASSERTE (!m_Creater.IsSameThread());
Thread *pCurThread = GetThread();
if (res != (DWORD) -1 && res != 0) {
if (pCurThread) {
_ASSERTE (pCurThread->m_dwSuspendThread > 0);
pCurThread->m_dwSuspendThread --;
}
}
#endif
if (res != (DWORD) -1 && res != 0)
{
DecCantAllocCount ();
}
if (CORProfilerTrackSuspends() && (res != 0) && (res != (DWORD)-1))
{
PROFILER_CALL;
g_profControlBlock.pProfInterface->RuntimeThreadResumed((ThreadID)this, (ThreadID)GetThread());
}
return res;
}
// 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
{
CONTRACT_VIOLATION(SOToleranceViolation);
pThread = SetupThread();
}
EX_CATCH
{
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());
UnsafeTlsSetValue(gThreadTLSIndex, NULL);
UnsafeTlsSetValue(GetAppDomainTLSIndex(), NULL);
if (pThread->HasThreadStateNC(Thread::TSNC_ExistInThreadStore))
{
pThread->DetachThread(FALSE);
}
else
{
FastInterlockOr((ULONG *)&pThread->m_State, Thread::TS_Dead);
delete pThread;
}
}
void EnsurePreemptive(StateHolderParam)
{
WRAPPER_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);}
}
CONTRACTL_END;
CONTRACT_VIOLATION(SOToleranceViolation);
_ASSERTE(ThreadInited());
Thread* pThread;
if ((pThread = GetThread()) != 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(TRUE);
EnsurePreemptiveModeIfException ensurePreemptive;
#ifdef _DEBUG
// Verify that for fiber mode, we do not have a thread that matches the current StackBase.
if (CLRTaskHosted()) {
ThreadStoreLockHolder TSLockHolder(TRUE);
IHostTaskManager *provider = CorHost2::GetHostTaskManager();
IHostTask *pHostTask = NULL;
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
provider->GetCurrentTask(&pHostTask);
END_SO_TOLERANT_CODE_CALLING_HOST;
if (pHostTask)
{
SafeComHolder<IHostTask> pHostTaskHolder(pHostTask);
while ((pThread = ThreadStore::s_pThreadStore->GetAllThreadList(pThread, 0, 0)) != NULL)
{
_ASSERTE ((pThread->m_State&Thread::TS_Unstarted) || pThread->GetHostTask() != pHostTask);
}
}
}
#endif
#ifdef _DEBUG
if (g_pConfig->SuppressChecks())
{
// EnterAssert will suppress any checks
CHECK::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();
IHostTask *curHostTask = NULL;
IHostTaskManager *hostTaskManager = CorHost2::GetHostTaskManager();
if (hostTaskManager) {
BEGIN_SO_TOLERANT_CODE_CALLING_HOST(GetThread());
hostTaskManager->GetCurrentTask(&curHostTask);
END_SO_TOLERANT_CODE_CALLING_HOST;
}
SafeComHolder<IHostTask> pHostTaskHolder(curHostTask);
{
ThreadStoreLockHolder TSLockHolder(TRUE);
_ASSERTE(pThread == NULL);
while ((pThread = ThreadStore::s_pThreadStore->GetAllThreadList(pThread, Thread::TS_Unstarted | Thread::TS_FailStarted, Thread::TS_Unstarted)) != NULL)
{
if (curHostTask)
{
if (curHostTask == pThread->GetHostTask())
{
break;
}
}
else 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);
}
}
// It's perfectly reasonable to not find this guy. 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();
Holder<Thread*,DoNothing<Thread*>,DeleteThread> threadHolder(pThread);
CExecutionEngine::SetupTLSForThread(pThread);
if (!pThread->InitThread(fInternal) ||
!pThread->PrepareApartmentAndContext())
ThrowOutOfMemory();
// make sure we will not fail when we store in TLS in the future.
if (!UnsafeTlsSetValue(gThreadTLSIndex, NULL))
{
ThrowOutOfMemory();
}
if (!UnsafeTlsSetValue(GetAppDomainTLSIndex(), NULL))
{
ThrowOutOfMemory();
}
// 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 = UnsafeTlsSetValue(gThreadTLSIndex, (VOID*)pThread);
_ASSERTE (fOK);
fOK = UnsafeTlsSetValue(GetAppDomainTLSIndex(), (VOID*)pThread->GetDomain());
_ASSERTE (fOK);
// We now have a Thread object visable to the RS. unmark special status.
hCantStop.Release();