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
/
threadsuspend.cpp
7064 lines (6020 loc) · 250 KB
/
threadsuspend.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.
//
// threadsuspend.CPP
//
// This file contains the implementation of thread suspension. The implementation of thread suspension
// used to be spread through multiple places. That is why, many methods still live in their own homes
// (class Thread, class ThreadStore, etc.). They should be eventually refactored into class ThreadSuspend.
//
#include "common.h"
#include "threadsuspend.h"
#include "finalizerthread.h"
#include "dbginterface.h"
// from ntstatus.h
#define STATUS_SUSPEND_COUNT_EXCEEDED ((NTSTATUS)0xC000004AL)
#define HIJACK_NONINTERRUPTIBLE_THREADS
bool ThreadSuspend::s_fSuspendRuntimeInProgress = false;
CLREvent* ThreadSuspend::g_pGCSuspendEvent = NULL;
ThreadSuspend::SUSPEND_REASON ThreadSuspend::m_suspendReason;
Thread* ThreadSuspend::m_pThreadAttemptingSuspendForGC;
CLREventBase * ThreadSuspend::s_hAbortEvt = NULL;
CLREventBase * ThreadSuspend::s_hAbortEvtCache = NULL;
// If you add any thread redirection function, make sure the debugger can 1) recognize the redirection
// function, and 2) retrieve the original CONTEXT. See code:Debugger.InitializeHijackFunctionAddress and
// code:DacDbiInterfaceImpl.RetrieveHijackedContext.
extern "C" void RedirectedHandledJITCaseForGCThreadControl_Stub(void);
extern "C" void RedirectedHandledJITCaseForDbgThreadControl_Stub(void);
extern "C" void RedirectedHandledJITCaseForUserSuspend_Stub(void);
#define GetRedirectHandlerForGCThreadControl() \
((PFN_REDIRECTTARGET) GetEEFuncEntryPoint(RedirectedHandledJITCaseForGCThreadControl_Stub))
#define GetRedirectHandlerForDbgThreadControl() \
((PFN_REDIRECTTARGET) GetEEFuncEntryPoint(RedirectedHandledJITCaseForDbgThreadControl_Stub))
#define GetRedirectHandlerForUserSuspend() \
((PFN_REDIRECTTARGET) GetEEFuncEntryPoint(RedirectedHandledJITCaseForUserSuspend_Stub))
#if defined(_TARGET_AMD64_) || defined(_TARGET_ARM_) || defined(_TARGET_ARM64_)
#if defined(HAVE_GCCOVER) && defined(USE_REDIRECT_FOR_GCSTRESS) // GCCOVER
extern "C" void RedirectedHandledJITCaseForGCStress_Stub(void);
#define GetRedirectHandlerForGCStress() \
((PFN_REDIRECTTARGET) GetEEFuncEntryPoint(RedirectedHandledJITCaseForGCStress_Stub))
#endif // HAVE_GCCOVER && USE_REDIRECT_FOR_GCSTRESS
#endif // _TARGET_AMD64_ || _TARGET_ARM_
// 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 1
// 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 ThreadSuspend::SetSuspendRuntimeInProgress()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(ThreadStore::HoldingThreadStore() || IsAtProcessExit());
_ASSERTE(!s_fSuspendRuntimeInProgress || IsAtProcessExit());
s_fSuspendRuntimeInProgress = true;
}
void ThreadSuspend::ResetSuspendRuntimeInProgress()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(ThreadStore::HoldingThreadStore() || IsAtProcessExit());
_ASSERTE(s_fSuspendRuntimeInProgress || IsAtProcessExit());
s_fSuspendRuntimeInProgress = false;
}
// 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, we've assumed that the answer to both questions is No. But on one 4/8 hyper-threaded machine
running Win2K3 SP1 build 1421, we've 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 it's 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 doesn't 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 don't 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_NO_CONTRACT;
CONTEXT ctx;
ctx.ContextFlags = CONTEXT_INTEGER;
BOOL ret;
ret = ::GetThreadContext(hThread, &ctx);
return ret;
}
FORCEINLINE VOID MyEnterLogLock()
{
EnterLogLock();
}
FORCEINLINE VOID MyLeaveLogLock()
{
LeaveLogLock();
}
// On non-Windows CORECLR platforms remove Thread::SuspendThread support
#ifndef DISABLE_THREADSUSPEND
// 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((unsigned int)-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)
int nCnt = 0;
bool bDiagSuspend = g_pConfig->GetDiagnosticSuspend();
ULONGLONG i64TimestampStart = CLRGetTickCount64();
ULONGLONG i64TimestampCur = i64TimestampStart;
ULONGLONG i64TimestampPrev = i64TimestampStart;
// This is the max allowed timestamp ticks to transpire from beginning of
// our attempt to suspend the thread, before we'll assert (implying we believe
// there might be a deadlock) - (default = 2000).
ULONGLONG i64TimestampTicksMax = g_pConfig->SuspendThreadDeadlockTimeoutMs();
#endif // _DEBUG
#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
DWORD dwSwitchCount = 0;
while (TRUE) {
StateHolder<MyEnterLogLock, MyLeaveLogLock> LogLockHolder(FALSE);
CounterHolder handleHolder(&m_dwThreadHandleBeingUsed);
// Whether or not "goto retry" should YieldProcessor and __SwitchToThread
BOOL doSwitchToThread = TRUE;
hThread = GetThreadHandle();
if (hThread == INVALID_HANDLE_VALUE) {
str = STR_UnstartedOrDead;
break;
}
else if (hThread == SWITCHOUT_HANDLE_VALUE) {
str = STR_SwitchedOut;
break;
}
{
// 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();
// 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))
{
#if defined(_DEBUG)
// Enable the diagnostic ::SuspendThread() if the
// DiagnosticSuspend config setting is set.
// This will interfere with the mutual suspend race but it's
// here only for diagnostic purposes anyway
if (!bDiagSuspend)
#endif // _DEBUG
goto retry;
}
dwSuspendCount = ::SuspendThread(hThread);
//
// Since SuspendThread is asynchronous, we now must wait for the thread to
// actually be suspended before decrementing our own m_dwForbidSuspendThread count.
// Otherwise there would still be a chance for the "suspended" thread to suspend us
// before it really stops running.
//
if ((int)dwSuspendCount >= 0)
{
if (!EnsureThreadIsSuspended(hThread, this))
{
::ResumeThread(hThread);
str = STR_Failure;
break;
}
}
}
if ((int)dwSuspendCount >= 0)
{
if (hThread == GetThreadHandle())
{
if (m_dwForbidSuspendThread != 0)
{
#if defined(_DEBUG)
// Log diagnostic below 8 times during the i64TimestampTicksMax period
if (i64TimestampCur-i64TimestampStart >= nCnt*(i64TimestampTicksMax>>3) )
{
CONTEXT ctx;
SetIP(&ctx, -1);
ctx.ContextFlags = CONTEXT_CONTROL;
this->GetThreadContext(&ctx);
STRESS_LOG7(LF_SYNC, LL_INFO1000,
"Thread::SuspendThread[%p]: EIP=%p. nCnt=%d. result=%d.\n"
"\t\t\t\t\t\t\t\t\t forbidSuspend=%d. coop=%d. state=%x.\n",
this, GetIP(&ctx), nCnt, dwSuspendCount,
(LONG)this->m_dwForbidSuspendThread, (ULONG)this->m_fPreemptiveGCDisabled, this->GetSnapshotState());
// Enable a preemptive assert in diagnostic mode: before we
// resume the target thread to get its current state in the debugger
if (bDiagSuspend)
{
// triggered after 6 * 250msec
_ASSERTE(nCnt < 6 && "Timing out in Thread::SuspendThread");
}
++nCnt;
}
#endif // _DEBUG
::ResumeThread(hThread);
#if defined(_DEBUG)
// If the suspend diagnostics are enabled we need to spin here in order to avoid
// the case where we Suspend/Resume the target thread without giving it a chance to run.
if ((!fOneTryOnly) && bDiagSuspend)
{
while ( m_dwForbidSuspendThread != 0 &&
CLRGetTickCount64()-i64TimestampStart < nCnt*(i64TimestampTicksMax>>3) )
{
if (g_SystemInfo.dwNumberOfProcessors > 1)
{
if ((tries++) % 20 != 0) {
YieldProcessorNormalized(); // play nice on hyperthreaded CPUs
} else {
__SwitchToThread(0, ++dwSwitchCount);
}
}
else
{
__SwitchToThread(0, ++dwSwitchCount); // don't spin on uniproc machines
}
}
}
#endif // _DEBUG
goto retry;
}
// We suspend the right thread
#ifdef _DEBUG
Thread * pCurThread = GetThread();
if (pCurThread != NULL)
{
pCurThread->dbg_m_cSuspendedThreads ++;
_ASSERTE(pCurThread->dbg_m_cSuspendedThreads > 0);
}
#endif
IncCantAllocCount();
m_ThreadHandleForResume = hThread;
str = STR_Success;
break;
}
else
{
// A thread was switch out but in again.
// We suspend a wrong thread.
::ResumeThread(hThread);
doSwitchToThread = FALSE;
goto retry;
}
}
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.
#ifndef FEATURE_PAL
_ASSERTE(NtCurrentTeb()->LastStatusValue != STATUS_SUSPEND_COUNT_EXCEEDED);
#endif // !FEATURE_PAL
str = STR_Failure;
break;
}
}
retry:
handleHolder.Release();
LogLockHolder.Release();
if (fOneTryOnly)
{
str = STR_Forbidden;
break;
}
#if defined(_DEBUG)
i64TimestampPrev = i64TimestampCur;
i64TimestampCur = CLRGetTickCount64();
// CLRGetTickCount64() is global per machine (not per CPU, like getTimeStamp()).
// Next ASSERT states that CLRGetTickCount64() is increasing, or has wrapped.
// If it wrapped, the last iteration should have executed faster then 0.5 seconds.
_ASSERTE(i64TimestampCur >= i64TimestampPrev || i64TimestampCur <= 500);
if (i64TimestampCur - i64TimestampStart >= i64TimestampTicksMax)
{
dwSuspendCount = ::SuspendThread(hThread);
_ASSERTE(!"It takes too long to suspend a thread");
if ((int)dwSuspendCount >= 0)
::ResumeThread(hThread);
}
#endif // _DEBUG
if (doSwitchToThread)
{
// 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 (g_SystemInfo.dwNumberOfProcessors > 1)
{
if ((tries++) % 20 != 0) {
YieldProcessorNormalized(); // play nice on hyperthreaded CPUs
} else {
__SwitchToThread(0, ++dwSwitchCount);
}
}
else
{
__SwitchToThread(0, ++dwSwitchCount); // don't spin on uniproc machines
}
}
}
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackSuspends());
if (str == STR_Success)
{
g_profControlBlock.pProfInterface->RuntimeThreadSuspended((ThreadID)this);
}
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
if (pdwSuspendCount != NULL)
{
*pdwSuspendCount = dwSuspendCount;
}
_ASSERTE(str != (SuspendThreadResult) -1);
return str;
}
#endif // DISABLE_THREADSUSPEND
// On non-Windows CORECLR platforms remove Thread::ResumeThread support
#ifndef DISABLE_THREADSUSPEND
DWORD Thread::ResumeThread()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE (m_ThreadHandleForResume != INVALID_HANDLE_VALUE);
_ASSERTE (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.IsCurrentThread());
if ((res != (DWORD)-1) && (res != 0))
{
Thread * pCurThread = GetThread();
if (pCurThread != NULL)
{
_ASSERTE(pCurThread->dbg_m_cSuspendedThreads > 0);
pCurThread->dbg_m_cSuspendedThreads --;
_ASSERTE(pCurThread->dbg_m_cSuspendedThreadsWithoutOSLock <= pCurThread->dbg_m_cSuspendedThreads);
}
}
#endif
if (res != (DWORD) -1 && res != 0)
{
DecCantAllocCount();
}
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackSuspends());
if ((res != 0) && (res != (DWORD)-1))
{
g_profControlBlock.pProfInterface->RuntimeThreadResumed((ThreadID)this);
}
END_PIN_PROFILER();
}
#endif
return res;
}
#endif // DISABLE_THREADSUSPEND
#ifdef _DEBUG
void* forceStackA;
// CheckSuspended
// Checks whether the given thread is currently suspended.
// Note that if we cannot determine the true suspension status
// of the thread, we succeed. Intended to be used in asserts
// in operations that require the target thread to be suspended.
// Arguments:
// pThread - The thread to examine.
// Return value:
// FALSE, if the thread is definitely not suspended.
// TRUE, otherwise.
static inline BOOL CheckSuspended(Thread *pThread)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
DEBUG_ONLY;
}
CONTRACTL_END;
_ASSERTE(GetThread() != pThread);
_ASSERTE(CheckPointer(pThread));
#ifndef DISABLE_THREADSUSPEND
// Only perform this test if we're allowed to call back into the host.
// Thread::SuspendThread contains several potential calls into the host.
if (CanThisThreadCallIntoHost())
{
DWORD dwSuspendCount;
Thread::SuspendThreadResult str = pThread->SuspendThread(FALSE, &dwSuspendCount);
forceStackA = &dwSuspendCount;
if (str == Thread::STR_Success)
{
pThread->ResumeThread();
return dwSuspendCount >= 1;
}
}
#endif // !DISABLE_THREADSUSPEND
return TRUE;
}
#endif //_DEBUG
BOOL EEGetThreadContext(Thread *pThread, CONTEXT *pContext)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(CheckSuspended(pThread));
BOOL ret = pThread->GetThreadContext(pContext);
STRESS_LOG6(LF_SYNC, LL_INFO1000, "Got thread context ret = %d EIP = %p ESP = %p EBP = %p, pThread = %p, ContextFlags = 0x%x\n",
ret, GetIP(pContext), GetSP(pContext), GetFP(pContext), pThread, pContext->ContextFlags);
return ret;
}
BOOL EESetThreadContext(Thread *pThread, const CONTEXT *pContext)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef _TARGET_X86_
_ASSERTE(CheckSuspended(pThread));
#endif
BOOL ret = pThread->SetThreadContext(pContext);
STRESS_LOG6(LF_SYNC, LL_INFO1000, "Set thread context ret = %d EIP = %p ESP = %p EBP = %p, pThread = %p, ContextFlags = 0x%x\n",
ret, GetIP((CONTEXT*)pContext), GetSP((CONTEXT*)pContext), GetFP((CONTEXT*)pContext), pThread, pContext->ContextFlags);
return ret;
}
// Context passed down through a stack crawl (see code below).
struct StackCrawlContext
{
enum SCCType
{
SCC_CheckWithinEH = 0x00000001,
SCC_CheckWithinCer = 0x00000002,
};
Thread* pAbortee;
int eType;
BOOL fUnprotectedCode;
BOOL fWithinEHClause;
BOOL fWithinCer;
BOOL fHasManagedCodeOnStack;
BOOL fWriteToStressLog;
BOOL fHaveLatchedCF;
CrawlFrame LatchedCF;
};
// Crawl the stack looking for Thread Abort related information (whether we're executing inside a CER or an error handling clauses
// of some sort).
static StackWalkAction TAStackCrawlCallBackWorker(CrawlFrame* pCf, StackCrawlContext *pData)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(pData->eType & (StackCrawlContext::SCC_CheckWithinCer | StackCrawlContext::SCC_CheckWithinEH));
if(pCf->IsFrameless())
{
IJitManager* pJitManager = pCf->GetJitManager();
_ASSERTE(pJitManager);
if (pJitManager && !pData->fHasManagedCodeOnStack)
{
pData->fHasManagedCodeOnStack = TRUE;
}
}
// Get the method for this frame if it exists (might not be a managed method, so check the explicit frame if that's what we're
// looking at).
MethodDesc *pMD = pCf->GetFunction();
Frame *pFrame = pCf->GetFrame();
if (pMD == NULL && pFrame != NULL)
pMD = pFrame->GetFunction();
// Non-method frames don't interest us.
if (pMD == NULL)
return SWA_CONTINUE;
#if defined(_DEBUG)
#define METHODNAME(pFunc) (pFunc?pFunc->m_pszDebugMethodName:"<n/a>")
#else
#define METHODNAME(pFunc) "<n/a>"
#endif
if (pData->fWriteToStressLog)
{
STRESS_LOG5(LF_EH, LL_INFO100, "TAStackCrawlCallBack: STACKCRAWL method:%pM ('%s'), offset %x, Frame:%p, FrameVtable = %pV\n",
pMD, METHODNAME(pMD), pCf->IsFrameless()?pCf->GetRelOffset():0, pFrame, pCf->IsFrameless()?0:(*(void**)pFrame));
}
#undef METHODNAME
// If we weren't asked about EH clauses then we can return now (stop the stack trace if we have a definitive answer on the CER
// question, move to the next frame otherwise).
if ((pData->eType & StackCrawlContext::SCC_CheckWithinEH) == 0)
return ((pData->fWithinCer || pData->fUnprotectedCode) && pData->fHasManagedCodeOnStack) ? SWA_ABORT : SWA_CONTINUE;
// If we already discovered we're within an EH clause but are still processing (presumably to determine whether we're within a
// CER), then we can just skip to the next frame straight away. Also terminate here if the current frame is not frameless since
// there isn't any useful EH information for non-managed frames.
if (pData->fWithinEHClause || !pCf->IsFrameless())
return SWA_CONTINUE;
IJitManager* pJitManager = pCf->GetJitManager();
_ASSERTE(pJitManager);
EH_CLAUSE_ENUMERATOR pEnumState;
unsigned EHCount = pJitManager->InitializeEHEnumeration(pCf->GetMethodToken(), &pEnumState);
if (EHCount == 0)
// We do not have finally clause here.
return SWA_CONTINUE;
DWORD offs = (DWORD)pCf->GetRelOffset();
if (!pCf->IsActiveFrame())
{
// If we aren't the topmost method, then our IP is a return address and
// we can't use it to directly compare against the EH ranges because we
// may be in an cloned finally which has a call as the last instruction.
offs--;
}
if (pData->fWriteToStressLog)
{
STRESS_LOG1(LF_EH, LL_INFO100, "TAStackCrawlCallBack: STACKCRAWL Offset 0x%x V\n", offs);
}
EE_ILEXCEPTION_CLAUSE EHClause;
StackWalkAction action = SWA_CONTINUE;
#ifndef FEATURE_EH_FUNCLETS
// On X86, the EH encoding for catch clause is completely mess.
// If catch clause is in its own basic block, the end of catch includes everything in the basic block.
// For nested catch, the end of catch may include several jmp instructions after JIT_EndCatch call.
// To better decide if we are inside a nested catch, we check if offs-1 is in more than one catch clause.
DWORD countInCatch = 0;
BOOL fAtJitEndCatch = FALSE;
if (pData->pAbortee == GetThread() &&
pData->pAbortee->ThrewControlForThread() == Thread::InducedThreadRedirectAtEndOfCatch &&
GetControlPC(pCf->GetRegisterSet()) == (PCODE)GetIP(pData->pAbortee->GetAbortContext()))
{
fAtJitEndCatch = TRUE;
offs -= 1;
}
#endif // !FEATURE_EH_FUNCLETS
for(ULONG i=0; i < EHCount; i++)
{
pJitManager->GetNextEHClause(&pEnumState, &EHClause);
_ASSERTE(IsValidClause(&EHClause));
// !!! If this function is called on Aborter thread, we should check for finally only.
// !!! If this function is called on Aborter thread, we should check for finally only.
// !!! Catch and filter clause are skipped. In UserAbort, the first thing after ReadyForAbort
// !!! is to check if the target thread is processing exception.
// !!! If exception is in flight, we don't induce ThreadAbort. Instead at the end of Jit_EndCatch
// !!! we will handle abort.
if (pData->pAbortee != GetThread() && !IsFaultOrFinally(&EHClause))
{
continue;
}
if (offs >= EHClause.HandlerStartPC &&
offs < EHClause.HandlerEndPC)
{
#ifndef FEATURE_EH_FUNCLETS
if (fAtJitEndCatch)
{
// On X86, JIT's EH info may include the instruction after JIT_EndCatch inside the same catch
// clause if it is in the same basic block.
// So for this case, the offs is in at least one catch handler, but since we are at the end of
// catch, this one should not be counted.
countInCatch ++;
if (countInCatch == 1)
{
continue;
}
}
#endif // !FEATURE_EH_FUNCLETS
pData->fWithinEHClause = true;
// We're within an EH clause. If we're asking about CERs too then stop the stack walk if we've reached a conclusive
// result or continue looking otherwise. Else we can stop the stackwalk now.
if (pData->eType & StackCrawlContext::SCC_CheckWithinCer)
{
action = (pData->fWithinCer || pData->fUnprotectedCode) ? SWA_ABORT : SWA_CONTINUE;
}
else
{
action = SWA_ABORT;
}
break;
}
}
#ifndef FEATURE_EH_FUNCLETS
#ifdef _DEBUG
if (fAtJitEndCatch)
{
_ASSERTE (countInCatch > 0);
}
#endif // _DEBUG
#endif // !FEATURE_EH_FUNCLETS
return action;
}
// Wrapper around code:TAStackCrawlCallBackWorker that abstracts away the differences between the reporting order
// of x86 and 64-bit stackwalker implementations, and also deals with interop calls that have an implicit reliability
// contract. If a P/Invoke or CLR->COM call returns SafeHandle or CriticalHandle, the IL stub could be aborted
// before having a chance to store the native handle into the Safe/CriticalHandle object. Therefore such calls are
// treated as unbreakable by convention.
StackWalkAction TAStackCrawlCallBack(CrawlFrame* pCf, void* data)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
StackCrawlContext *pData = (StackCrawlContext *)data;
// We have the current frame in pCf and possibly one latched frame in pData->LatchedCF. This enumeration
// describes which of these should be passed to code:TAStackCrawlCallBackWorker and in what order.
enum LatchedFrameAction
{
DiscardLatchedFrame, // forget the latched frame, report the current one
DiscardCurrentFrame, // ignore the current frame, report the latched one
ProcessLatchedInOrder, // report the latched frame, then report the current frame
ProcessLatchedReversed, // report the current frame, then report the latched frame
LatchCurrentFrame // latch the current frame, don't report anything
}
frameAction = DiscardLatchedFrame;
#ifdef _TARGET_X86_
// On X86 the IL stub method is reported to us before the frame with the actual interop method. We need to
// swap the order because if the worker saw the IL stub - which is a CER root - first, it would terminate the
// stack walk and wouldn't allow the thread to be aborted, regardless of how the interop method is annotated.
if (pData->fHaveLatchedCF)
{
// Does the current and latched frame represent the same call?
if (pCf->pFrame == pData->LatchedCF.pFrame)
{
if (pData->LatchedCF.GetFunction()->AsDynamicMethodDesc()->IsUnbreakable())
{
// Report only the latched IL stub frame which is a CER root.
frameAction = DiscardCurrentFrame;
}
else
{
// Report the interop method (current frame) which may be annotated, then the IL stub.
frameAction = ProcessLatchedReversed;
}
}
else
{
// The two frames are unrelated - process them in order.
frameAction = ProcessLatchedInOrder;
}
pData->fHaveLatchedCF = FALSE;
}
else
{
MethodDesc *pMD = pCf->GetFunction();
if (pMD != NULL && pMD->IsILStub() && InlinedCallFrame::FrameHasActiveCall(pCf->pFrame))
{
// This may be IL stub for an interesting interop call - latch it.
frameAction = LatchCurrentFrame;
}
}
#else // _TARGET_X86_
// On 64-bit the IL stub method is reported after the actual interop method so we don't have to swap them.
// However, we still want to discard the interop method frame if the call is unbreakable by convention.
if (pData->fHaveLatchedCF)
{
MethodDesc *pMD = pCf->GetFunction();
if (pMD != NULL && pMD->IsILStub() &&
pData->LatchedCF.GetFrame()->GetReturnAddress() == GetControlPC(pCf->GetRegisterSet()) &&
pMD->AsDynamicMethodDesc()->IsUnbreakable())
{
// The current and latched frame represent the same call and the IL stub is marked as unbreakable.
// We will discard the interop method and report only the IL stub which is a CER root.
frameAction = DiscardLatchedFrame;
}
else
{
// Otherwise process the two frames in order.
frameAction = ProcessLatchedInOrder;
}
pData->fHaveLatchedCF = FALSE;
}
else
{
MethodDesc *pMD = pCf->GetFunction();
if (pCf->GetFrame() != NULL && pMD != NULL && (pMD->IsNDirect() || pMD->IsComPlusCall()))
{
// This may be interop method of an interesting interop call - latch it.
frameAction = LatchCurrentFrame;
}
}
#endif // _TARGET_X86_
// Execute the "frame action".
StackWalkAction action;
switch (frameAction)
{
case DiscardLatchedFrame:
action = TAStackCrawlCallBackWorker(pCf, pData);
break;
case DiscardCurrentFrame:
action = TAStackCrawlCallBackWorker(&pData->LatchedCF, pData);
break;
case ProcessLatchedInOrder:
action = TAStackCrawlCallBackWorker(&pData->LatchedCF, pData);
if (action == SWA_CONTINUE)
action = TAStackCrawlCallBackWorker(pCf, pData);
break;
case ProcessLatchedReversed:
action = TAStackCrawlCallBackWorker(pCf, pData);
if (action == SWA_CONTINUE)
action = TAStackCrawlCallBackWorker(&pData->LatchedCF, pData);
break;
case LatchCurrentFrame:
pData->LatchedCF = *pCf;
pData->fHaveLatchedCF = TRUE;
action = SWA_CONTINUE;
break;
default:
UNREACHABLE();
}
return action;
}
// Is the current thread currently executing within a constrained execution region?
BOOL Thread::IsExecutingWithinCer()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (!g_fEEStarted)
return FALSE;
Thread *pThread = GetThread();
_ASSERTE (pThread);
StackCrawlContext sContext = { pThread,
StackCrawlContext::SCC_CheckWithinCer,
FALSE,
FALSE,
FALSE,
FALSE,
FALSE,
FALSE};
pThread->StackWalkFrames(TAStackCrawlCallBack, &sContext);
#ifdef STRESS_LOG
if (sContext.fWithinCer && StressLog::StressLogOn(~0u, 0))
{
// If stress log is on, write info to stress log
StackCrawlContext sContext1 = { pThread,
StackCrawlContext::SCC_CheckWithinCer,
FALSE,
FALSE,
FALSE,
FALSE,
TRUE,
FALSE};
pThread->StackWalkFrames(TAStackCrawlCallBack, &sContext1);
}
#endif
return sContext.fWithinCer;
}
// Context structure used during stack walks to determine whether a given method is executing within a CER.
struct CerStackCrawlContext
{
MethodDesc *m_pStartMethod; // First method we crawl (here for debug purposes)
bool m_fFirstFrame; // True for first callback only
bool m_fWithinCer; // The result
};
// Determine whether the method at the given depth in the thread's execution stack is executing within a CER.
BOOL Thread::IsWithinCer(CrawlFrame *pCf)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
return FALSE;
}
#if defined(_TARGET_AMD64_) && defined(FEATURE_HIJACK)
BOOL Thread::IsSafeToInjectThreadAbort(PTR_CONTEXT pContextToCheck)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
PRECONDITION(pContextToCheck != NULL);
}
CONTRACTL_END;
EECodeInfo codeInfo(GetIP(pContextToCheck));
_ASSERTE(codeInfo.IsValid());
// Check if the method uses a frame register. If it does not, then RSP will be used by the OS as the frame register
// and returned as the EstablisherFrame. This is fine at any instruction in the method (including epilog) since there is always a
// difference of stackslot size between the callerSP and the callee SP due to return address having been pushed on the stack.
if (!codeInfo.HasFrameRegister())
{
return TRUE;
}
BOOL fSafeToInjectThreadAbort = TRUE;
if (IsIPInEpilog(pContextToCheck, &codeInfo, &fSafeToInjectThreadAbort))
{
return fSafeToInjectThreadAbort;
}
else
{
return TRUE;
}
}
#endif // defined(_TARGET_AMD64_) && defined(FEATURE_HIJACK)
#ifdef _TARGET_AMD64_
// CONTEXT_CONTROL does not include any nonvolatile registers that might be the frame pointer.