-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
thread.cpp
1404 lines (1169 loc) · 46 KB
/
thread.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.
#include "common.h"
#include "CommonTypes.h"
#include "CommonMacros.h"
#include "daccess.h"
#include "PalRedhawkCommon.h"
#include "PalRedhawk.h"
#include "rhassert.h"
#include "slist.h"
#include "gcrhinterface.h"
#include "varint.h"
#include "regdisplay.h"
#include "StackFrameIterator.h"
#include "thread.h"
#include "holder.h"
#include "Crst.h"
#include "event.h"
#include "threadstore.h"
#include "threadstore.inl"
#include "thread.inl"
#include "RuntimeInstance.h"
#include "shash.h"
#include "rhbinder.h"
#include "stressLog.h"
#include "RhConfig.h"
#include "RhVolatile.h"
#ifndef DACCESS_COMPILE
EXTERN_C NATIVEAOT_API void* REDHAWK_CALLCONV RhpHandleAlloc(void* pObject, int type);
EXTERN_C NATIVEAOT_API void REDHAWK_CALLCONV RhHandleSet(void* handle, void* pObject);
EXTERN_C NATIVEAOT_API void REDHAWK_CALLCONV RhHandleFree(void* handle);
static int (*g_RuntimeInitializationCallback)();
static Thread* g_RuntimeInitializingThread;
#endif //!DACCESS_COMPILE
PInvokeTransitionFrame* Thread::GetTransitionFrame()
{
if (ThreadStore::GetSuspendingThread() == this)
{
// This thread is in cooperative mode, so we grab the deferred frame
// which is the frame from the most
// recent 'cooperative pinvoke' transition that brought us here.
ASSERT(m_pDeferredTransitionFrame != NULL);
return m_pDeferredTransitionFrame;
}
ASSERT(m_pCachedTransitionFrame != NULL);
return m_pCachedTransitionFrame;
}
#ifndef DACCESS_COMPILE
PInvokeTransitionFrame* Thread::GetTransitionFrameForStackTrace()
{
ASSERT_MSG(this == ThreadStore::GetCurrentThread(), "Only supported for current thread.");
ASSERT(Thread::IsCurrentThreadInCooperativeMode());
ASSERT(m_pDeferredTransitionFrame != NULL);
return m_pDeferredTransitionFrame;
}
void Thread::WaitForGC(PInvokeTransitionFrame* pTransitionFrame)
{
ASSERT(!IsDoNotTriggerGcSet());
// The wait operation below may trash the last win32 error. We save the error here so that it can be
// restored after the wait operation;
int32_t lastErrorOnEntry = PalGetLastError();
do
{
// set preemptive mode
VolatileStoreWithoutBarrier(&m_pTransitionFrame, pTransitionFrame);
#ifdef FEATURE_SUSPEND_REDIRECTION
ClearState(TSF_Redirected);
#endif //FEATURE_SUSPEND_REDIRECTION
RedhawkGCInterface::WaitForGCCompletion();
// must be in cooperative mode when checking the trap flag
VolatileStoreWithoutBarrier(&m_pTransitionFrame, NULL);
}
while (ThreadStore::IsTrapThreadsRequested());
// Restore the saved error
PalSetLastError(lastErrorOnEntry);
}
//
// This is used by the suspension code when driving all threads to unmanaged code. It is performed after
// the FlushProcessWriteBuffers call so that we know that once the thread reaches unmanaged code, it won't
// reenter managed code. Therefore, the m_pTransitionFrame is stable. Except that it isn't. The return-to-
// managed sequence will temporarily overwrite the m_pTransitionFrame to be 0. As a result, we need to cache
// the non-zero m_pTransitionFrame value that we saw during suspend so that stackwalks can read this value
// without concern of sometimes reading a 0, as would be the case if they read m_pTransitionFrame directly.
//
// Returns true if it successfully cached the transition frame (i.e. the thread was in unmanaged).
// Returns false otherwise.
//
// WARNING: This method is called by suspension while one thread is interrupted
// in a random location, possibly holding random locks.
// It is unsafe to use blocking APIs or allocate in this method.
// Please ensure that all methods called by this one also have this warning.
bool Thread::CacheTransitionFrameForSuspend()
{
if (m_pCachedTransitionFrame != NULL)
return true;
// Once we see a thread posted a transition frame we can assume it will not enter cooperative mode.
// It may temporarily set the frame to NULL when checking the trap flag, but will revert.
// We can safely return true here and ache the frame.
// Make sure compiler emits only one read.
PInvokeTransitionFrame* temp = VolatileLoadWithoutBarrier(&m_pTransitionFrame);
if (temp == NULL)
return false;
m_pCachedTransitionFrame = temp;
return true;
}
void Thread::ResetCachedTransitionFrame()
{
m_pCachedTransitionFrame = NULL;
}
// This function simulates a PInvoke transition using a frame pointer from somewhere further up the stack that
// was passed in via the m_pDeferredTransitionFrame field. It is used to allow us to grandfather-in the set of GC
// code that runs in cooperative mode without having to rewrite it in managed code. The result is that the
// code that calls into this special mode must spill preserved registers as if it's going to PInvoke, but
// record its transition frame pointer in m_pDeferredTransitionFrame and leave the thread in the cooperative
// mode. Later on, when this function is called, we effect the state transition to 'unmanaged' using the
// previously setup transition frame.
void Thread::EnablePreemptiveMode()
{
ASSERT(ThreadStore::GetCurrentThread() == this);
#if !defined(HOST_WASM)
ASSERT(m_pDeferredTransitionFrame != NULL);
#endif
// set preemptive mode
VolatileStoreWithoutBarrier(&m_pTransitionFrame, m_pDeferredTransitionFrame);
}
void Thread::DisablePreemptiveMode()
{
ASSERT(ThreadStore::GetCurrentThread() == this);
// must be in cooperative mode when checking the trap flag
VolatileStoreWithoutBarrier(&m_pTransitionFrame, NULL);
if (ThreadStore::IsTrapThreadsRequested() && (this != ThreadStore::GetSuspendingThread()))
{
WaitForGC(m_pDeferredTransitionFrame);
}
}
#endif // !DACCESS_COMPILE
bool Thread::IsCurrentThreadInCooperativeMode()
{
#ifndef DACCESS_COMPILE
ASSERT(ThreadStore::GetCurrentThread() == this);
#endif // !DACCESS_COMPILE
return (m_pTransitionFrame == NULL);
}
//
// This is used by the EH system to find the place where execution left managed code when an exception leaks out of a
// pinvoke and we need to FailFast via the appropriate class library.
//
// May only be used from the same thread and while in preemptive mode with an active pinvoke on the stack.
//
#ifndef DACCESS_COMPILE
void * Thread::GetCurrentThreadPInvokeReturnAddress()
{
ASSERT(ThreadStore::GetCurrentThread() == this);
ASSERT(!IsCurrentThreadInCooperativeMode());
return ((PInvokeTransitionFrame*)m_pTransitionFrame)->m_RIP;
}
#endif // !DACCESS_COMPILE
#if defined(FEATURE_GC_STRESS) & !defined(DACCESS_COMPILE)
void Thread::SetRandomSeed(uint32_t seed)
{
ASSERT(!IsStateSet(TSF_IsRandSeedSet));
m_uRand = seed;
SetState(TSF_IsRandSeedSet);
}
// Generates pseudo random numbers in the range [0, 2^31)
// using only multiplication and addition
uint32_t Thread::NextRand()
{
// Uses Carta's algorithm for Park-Miller's PRNG:
// x_{k+1} = 16807 * x_{k} mod (2^31-1)
uint32_t hi,lo;
// (high word of seed) * 16807 - at most 31 bits
hi = 16807 * (m_uRand >> 16);
// (low word of seed) * 16807 - at most 31 bits
lo = 16807 * (m_uRand & 0xFFFF);
// Proof that below operations (multiplication and addition only)
// are equivalent to the original formula:
// x_{k+1} = 16807 * x_{k} mod (2^31-1)
// We denote hi2 as the low 15 bits in hi,
// and hi1 as the remaining 16 bits in hi:
// (hi * 2^16 + lo) mod (2^31-1) =
// ((hi1 * 2^15 + hi2) * 2^16 + lo) mod (2^31-1) =
// ( hi1 * 2^31 + hi2 * 2^16 + lo) mod (2^31-1) =
// ( hi1 * (2^31-1) + hi1 + hi2 * 2^16 + lo) mod (2^31-1) =
// ( hi2 * 2^16 + hi1 + lo ) mod (2^31-1)
// lo + (hi2 * 2^16)
lo += (hi & 0x7FFF) << 16;
// lo + (hi2 * 2^16) + hi1
lo += (hi >> 15);
// modulo (2^31-1)
if (lo > 0x7fffFFFF)
lo -= 0x7fffFFFF;
m_uRand = lo;
return m_uRand;
}
bool Thread::IsRandInited()
{
return IsStateSet(TSF_IsRandSeedSet);
}
#endif // FEATURE_GC_STRESS & !DACCESS_COMPILE
PTR_ExInfo Thread::GetCurExInfo()
{
ValidateExInfoStack();
return m_pExInfoStackHead;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef DACCESS_COMPILE
void Thread::Construct()
{
#ifndef USE_PORTABLE_HELPERS
C_ASSERT(OFFSETOF__Thread__m_pTransitionFrame ==
(offsetof(Thread, m_pTransitionFrame)));
#endif // USE_PORTABLE_HELPERS
// NOTE: We do not explicitly defer to the GC implementation to initialize the alloc_context. The
// alloc_context will be initialized to 0 via the static initialization of tls_CurrentThread. If the
// alloc_context ever needs different initialization, a matching change to the tls_CurrentThread
// static initialization will need to be made.
m_pTransitionFrame = TOP_OF_STACK_MARKER;
m_pDeferredTransitionFrame = TOP_OF_STACK_MARKER;
m_hPalThread = INVALID_HANDLE_VALUE;
m_threadId.SetToCurrentThread();
HANDLE curProcessPseudo = PalGetCurrentProcess();
HANDLE curThreadPseudo = PalGetCurrentThread();
// This can fail! Users of m_hPalThread must be able to handle INVALID_HANDLE_VALUE!!
PalDuplicateHandle(curProcessPseudo, curThreadPseudo, curProcessPseudo, &m_hPalThread,
0, // ignored
FALSE, // inherit
DUPLICATE_SAME_ACCESS);
if (!PalGetMaximumStackBounds(&m_pStackLow, &m_pStackHigh))
RhFailFast();
#ifdef STRESS_LOG
if (StressLog::StressLogOn(~0u, 0))
m_pThreadStressLog = StressLog::CreateThreadStressLog(this);
#endif // STRESS_LOG
// Everything else should be initialized to 0 via the static initialization of tls_CurrentThread.
ASSERT(m_pThreadLocalModuleStatics == NULL);
ASSERT(m_numThreadLocalModuleStatics == 0);
ASSERT(m_pGCFrameRegistrations == NULL);
ASSERT(m_threadAbortException == NULL);
#ifdef FEATURE_SUSPEND_REDIRECTION
ASSERT(m_redirectionContextBuffer == NULL);
#endif //FEATURE_SUSPEND_REDIRECTION
ASSERT(m_interruptedContext == NULL);
}
bool Thread::IsInitialized()
{
return (m_ThreadStateFlags != TSF_Unknown);
}
// -----------------------------------------------------------------------------------------------------------
// GC support APIs - do not use except from GC itself
//
void Thread::SetGCSpecial()
{
if (!IsInitialized())
Construct();
SetState(TSF_IsGcSpecialThread);
}
bool Thread::IsGCSpecial()
{
return IsStateSet(TSF_IsGcSpecialThread);
}
bool Thread::CatchAtSafePoint()
{
// This is only called by the GC on a background GC worker thread that's explicitly interested in letting
// a foreground GC proceed at that point. So it's always safe to return true.
ASSERT(IsGCSpecial());
return true;
}
uint64_t Thread::GetPalThreadIdForLogging()
{
return *(uint64_t*)&m_threadId;
}
bool Thread::IsCurrentThread()
{
return m_threadId.IsCurrentThread();
}
void Thread::Detach()
{
RedhawkGCInterface::ReleaseAllocContext(GetAllocContext());
SetDetached();
}
void Thread::Destroy()
{
ASSERT(IsDetached());
if (m_hPalThread != INVALID_HANDLE_VALUE)
PalCloseHandle(m_hPalThread);
if (m_pThreadLocalModuleStatics != NULL)
{
for (uint32_t i = 0; i < m_numThreadLocalModuleStatics; i++)
{
if (m_pThreadLocalModuleStatics[i] != NULL)
{
RhHandleFree(m_pThreadLocalModuleStatics[i]);
}
}
delete[] m_pThreadLocalModuleStatics;
}
#ifdef STRESS_LOG
ThreadStressLog* ptsl = reinterpret_cast<ThreadStressLog*>(GetThreadStressLog());
StressLog::ThreadDetach(ptsl);
#endif // STRESS_LOG
#ifdef FEATURE_SUSPEND_REDIRECTION
if (m_redirectionContextBuffer != NULL)
{
delete[] m_redirectionContextBuffer;
}
#endif //FEATURE_SUSPEND_REDIRECTION
ASSERT(m_pGCFrameRegistrations == NULL);
}
#ifdef HOST_WASM
extern RtuObjectRef * t_pShadowStackTop;
extern RtuObjectRef * t_pShadowStackBottom;
void GcScanWasmShadowStack(void * pfnEnumCallback, void * pvCallbackData)
{
// Wasm does not permit iteration of stack frames so is uses a shadow stack instead
RedhawkGCInterface::EnumGcRefsInRegionConservatively(t_pShadowStackBottom, t_pShadowStackTop, pfnEnumCallback, pvCallbackData);
}
#endif
void Thread::GcScanRoots(void * pfnEnumCallback, void * pvCallbackData)
{
this->CrossThreadUnhijack();
#ifdef HOST_WASM
GcScanWasmShadowStack(pfnEnumCallback, pvCallbackData);
#else
StackFrameIterator frameIterator(this, GetTransitionFrame());
GcScanRootsWorker(pfnEnumCallback, pvCallbackData, frameIterator);
#endif
}
#endif // !DACCESS_COMPILE
#ifdef DACCESS_COMPILE
// A trivial wrapper that unpacks the DacScanCallbackData and calls the callback provided to GcScanRoots
void GcScanRootsCallbackWrapper(PTR_RtuObjectRef ppObject, DacScanCallbackData* callbackData, uint32_t flags)
{
Thread::GcScanRootsCallbackFunc * pfnUserCallback = (Thread::GcScanRootsCallbackFunc *)callbackData->pfnUserCallback;
pfnUserCallback(ppObject, callbackData->token, flags);
}
bool Thread::GcScanRoots(GcScanRootsCallbackFunc * pfnEnumCallback, void * token, PTR_PAL_LIMITED_CONTEXT pInitialContext)
{
DacScanCallbackData callbackDataWrapper;
callbackDataWrapper.thread_under_crawl = this;
callbackDataWrapper.promotion = true;
callbackDataWrapper.token = token;
callbackDataWrapper.pfnUserCallback = pfnEnumCallback;
//When debugging we might be trying to enumerate with or without a transition frame
//on top of the stack. If there is one use it, otherwise the debugger provides a set of initial registers
//to use.
PInvokeTransitionFrame* pTransitionFrame = GetTransitionFrame();
if(pTransitionFrame != NULL)
{
StackFrameIterator frameIterator(this, pTransitionFrame);
GcScanRootsWorker(&GcScanRootsCallbackWrapper, &callbackDataWrapper, frameIterator);
}
else
{
if(pInitialContext == NULL)
return false;
StackFrameIterator frameIterator(this, pInitialContext);
GcScanRootsWorker(&GcScanRootsCallbackWrapper, &callbackDataWrapper, frameIterator);
}
return true;
}
#endif //DACCESS_COMPILE
void Thread::GcScanRootsWorker(void * pfnEnumCallback, void * pvCallbackData, StackFrameIterator & frameIterator)
{
PTR_RtuObjectRef pHijackedReturnValue = NULL;
GCRefKind returnValueKind = GCRK_Unknown;
if (frameIterator.GetHijackedReturnValueLocation(&pHijackedReturnValue, &returnValueKind))
{
GCRefKind reg0Kind = ExtractReg0ReturnKind(returnValueKind);
if (reg0Kind != GCRK_Scalar)
{
RedhawkGCInterface::EnumGcRef(pHijackedReturnValue, reg0Kind, pfnEnumCallback, pvCallbackData);
}
#if defined(TARGET_ARM64) || defined(TARGET_UNIX)
GCRefKind reg1Kind = ExtractReg1ReturnKind(returnValueKind);
if (reg1Kind != GCRK_Scalar)
{
// X0/X1 or RAX/RDX are saved in hijack frame next to each other in this order
RedhawkGCInterface::EnumGcRef(pHijackedReturnValue + 1, reg1Kind, pfnEnumCallback, pvCallbackData);
}
#endif // TARGET_ARM64 || TARGET_UNIX
}
#ifndef DACCESS_COMPILE
if (GetRuntimeInstance()->IsConservativeStackReportingEnabled())
{
if (frameIterator.IsValid())
{
PTR_VOID pLowerBound = dac_cast<PTR_VOID>(frameIterator.GetRegisterSet()->GetSP());
// Transition frame may contain callee saved registers that need to be reported as well
PInvokeTransitionFrame* pTransitionFrame = GetTransitionFrame();
ASSERT(pTransitionFrame != NULL);
if (pTransitionFrame == INTERRUPTED_THREAD_MARKER)
{
GetInterruptedContext()->ForEachPossibleObjectRef
(
[&](size_t* pRef)
{
RedhawkGCInterface::EnumGcRefConservatively((PTR_RtuObjectRef)pRef, pfnEnumCallback, pvCallbackData);
}
);
}
if (pTransitionFrame < pLowerBound)
pLowerBound = pTransitionFrame;
PTR_VOID pUpperBound = m_pStackHigh;
RedhawkGCInterface::EnumGcRefsInRegionConservatively(
dac_cast<PTR_RtuObjectRef>(pLowerBound),
dac_cast<PTR_RtuObjectRef>(pUpperBound),
pfnEnumCallback,
pvCallbackData);
}
}
else
#endif // !DACCESS_COMPILE
{
while (frameIterator.IsValid())
{
frameIterator.CalculateCurrentMethodState();
STRESS_LOG1(LF_GCROOTS, LL_INFO1000, "Scanning method %pK\n", (void*)frameIterator.GetRegisterSet()->IP);
if (!frameIterator.ShouldSkipRegularGcReporting())
{
RedhawkGCInterface::EnumGcRefs(frameIterator.GetCodeManager(),
frameIterator.GetMethodInfo(),
frameIterator.GetEffectiveSafePointAddress(),
frameIterator.GetRegisterSet(),
pfnEnumCallback,
pvCallbackData,
frameIterator.IsActiveStackFrame());
}
// Each enumerated frame (including the first one) may have an associated stack range we need to
// report conservatively (every pointer aligned value that looks like it might be a GC reference is
// reported as a pinned interior reference). This occurs in an edge case where a managed method whose
// signature the runtime is not aware of calls into the runtime which subsequently calls back out
// into managed code (allowing the possibility of a garbage collection). This can happen in certain
// interface invocation slow paths for instance. Since the original managed call may have passed GC
// references which are unreported by any managed method on the stack at the time of the GC we
// identify (again conservatively) the range of the stack that might contain these references and
// report everything. Since it should be a very rare occurrence indeed that we actually have to do
// this, it's considered a better trade-off than storing signature metadata for every potential
// callsite of the type described above.
if (frameIterator.HasStackRangeToReportConservatively())
{
PTR_RtuObjectRef pLowerBound;
PTR_RtuObjectRef pUpperBound;
frameIterator.GetStackRangeToReportConservatively(&pLowerBound, &pUpperBound);
RedhawkGCInterface::EnumGcRefsInRegionConservatively(pLowerBound,
pUpperBound,
pfnEnumCallback,
pvCallbackData);
}
frameIterator.Next();
}
}
// ExInfos hold exception objects that are not reported by anyone else. In fact, sometimes they are in
// logically dead parts of the stack that the typical GC stackwalk skips. (This happens in the case where
// one exception dispatch superseded a previous one.) We keep them alive as long as they are in the
// ExInfo chain to aid in post-mortem debugging. SOS will access them through the DAC and the exported
// API, RhGetExceptionsForCurrentThread, will access them at runtime to gather additional information to
// add to a dump file during FailFast.
for (PTR_ExInfo curExInfo = GetCurExInfo(); curExInfo != NULL; curExInfo = curExInfo->m_pPrevExInfo)
{
PTR_RtuObjectRef pExceptionObj = dac_cast<PTR_RtuObjectRef>(&curExInfo->m_exception);
RedhawkGCInterface::EnumGcRef(pExceptionObj, GCRK_Object, pfnEnumCallback, pvCallbackData);
}
for (GCFrameRegistration* pCurGCFrame = m_pGCFrameRegistrations; pCurGCFrame != NULL; pCurGCFrame = pCurGCFrame->m_pNext)
{
ASSERT(pCurGCFrame->m_pThread == this);
for (uint32_t i = 0; i < pCurGCFrame->m_numObjRefs; i++)
{
RedhawkGCInterface::EnumGcRef(dac_cast<PTR_RtuObjectRef>(pCurGCFrame->m_pObjRefs + i),
pCurGCFrame->m_MaybeInterior ? GCRK_Byref : GCRK_Object, pfnEnumCallback, pvCallbackData);
}
}
// Keep alive the ThreadAbortException that's stored in the target thread during thread abort
PTR_RtuObjectRef pThreadAbortExceptionObj = dac_cast<PTR_RtuObjectRef>(&m_threadAbortException);
RedhawkGCInterface::EnumGcRef(pThreadAbortExceptionObj, GCRK_Object, pfnEnumCallback, pvCallbackData);
}
#ifndef DACCESS_COMPILE
EXTERN_C void FASTCALL RhpSuspendRedirected();
EXTERN_C void FASTCALL RhpGcProbeHijack();
EXTERN_C void FASTCALL RhpGcStressHijack();
// static
bool Thread::IsHijackTarget(void* address)
{
if (&RhpGcProbeHijack == address)
return true;
#ifdef FEATURE_GC_STRESS
if (&RhpGcStressHijack == address)
return true;
#endif // FEATURE_GC_STRESS
return false;
}
void Thread::Hijack()
{
ASSERT(ThreadStore::GetCurrentThread() == ThreadStore::GetSuspendingThread());
ASSERT_MSG(ThreadStore::GetSuspendingThread() != this, "You may not hijack a thread from itself.");
if (m_hPalThread == INVALID_HANDLE_VALUE)
{
// cannot proceed
return;
}
if (IsGCSpecial())
{
// GC threads can not be forced to run preemptively, so we will not try.
return;
}
#ifdef FEATURE_SUSPEND_REDIRECTION
// if the thread is redirected, leave it as-is.
if (IsStateSet(TSF_Redirected))
{
return;
}
#endif //FEATURE_SUSPEND_REDIRECTION
// PalHijack will call HijackCallback or make the target thread call it.
// It may also do nothing if the target thread is in inconvenient state.
PalHijack(m_hPalThread, this);
}
void Thread::HijackCallback(NATIVE_CONTEXT* pThreadContext, void* pThreadToHijack)
{
// If we are no longer trying to suspend, no need to do anything.
// This is just an optimization. It is ok to race with the setting the trap flag here.
// If we need to suspend, we will be called again.
if (!ThreadStore::IsTrapThreadsRequested())
return;
Thread* pThread = (Thread*) pThreadToHijack;
if (pThread == NULL)
{
pThread = ThreadStore::GetCurrentThreadIfAvailable();
if (pThread == NULL)
{
ASSERT(!"a not attached thread got signaled");
// perhaps we share the signal with something else?
return;
}
if (pThread == ThreadStore::GetSuspendingThread())
{
ASSERT(!"trying to suspend suspending thread");
// perhaps we share the signal with something else?
return;
}
}
// we have a thread stopped, and we do not know where exactly.
// it could be in a system call or in our own runtime holding locks
// current thread should not block or allocate while we determine whether the location is in managed code.
if (pThread->m_pTransitionFrame != NULL)
{
// This thread has already made it to preemptive (posted a transition frame)
// we do not need to hijack it
return;
}
void* pvAddress = (void*)pThreadContext->GetIp();
RuntimeInstance* runtime = GetRuntimeInstance();
if (!runtime->IsManaged(pvAddress))
{
// Running in cooperative mode, but not managed.
// We cannot continue.
return;
}
if (pThread->IsDoNotTriggerGcSet())
{
return;
}
// we may be able to do GC stack walk right where the threads is now,
// as long as the location is a GC safe point.
ICodeManager* codeManager = runtime->GetCodeManagerForAddress(pvAddress);
if (runtime->IsConservativeStackReportingEnabled() ||
codeManager->IsSafePoint(pvAddress))
{
// we may not be able to unwind in some locations, such as epilogs.
// such locations should not contain safe points.
// when scanning conservatively we do not need to unwind
ASSERT(codeManager->IsUnwindable(pvAddress) || runtime->IsConservativeStackReportingEnabled());
// if we are not given a thread to hijack
// perform in-line wait on the current thread
if (pThreadToHijack == NULL)
{
ASSERT(pThread->m_interruptedContext == NULL);
pThread->InlineSuspend(pThreadContext);
return;
}
#ifdef FEATURE_SUSPEND_REDIRECTION
if (pThread->Redirect())
{
return;
}
#endif //FEATURE_SUSPEND_REDIRECTION
}
pThread->HijackReturnAddress(pThreadContext, &RhpGcProbeHijack);
}
#ifdef FEATURE_GC_STRESS
// This is a helper called from RhpHijackForGcStress which will place a GC Stress
// hijack on this thread's call stack. This is never called from another thread.
// static
void Thread::HijackForGcStress(PAL_LIMITED_CONTEXT * pSuspendCtx)
{
Thread * pCurrentThread = ThreadStore::GetCurrentThread();
// don't hijack for GC stress if we're in a "no GC stress" region
if (pCurrentThread->IsSuppressGcStressSet())
return;
RuntimeInstance * pInstance = GetRuntimeInstance();
uintptr_t ip = pSuspendCtx->GetIp();
bool bForceGC = g_pRhConfig->GetGcStressThrottleMode() == 0;
// we enable collecting statistics by callsite even for stochastic-only
// stress mode. this will force a stack walk, but it's worthwhile for
// collecting data (we only actually need the IP when
// (g_pRhConfig->GetGcStressThrottleMode() & 1) != 0)
if (!bForceGC)
{
StackFrameIterator sfi(pCurrentThread, pSuspendCtx);
if (sfi.IsValid())
{
pCurrentThread->Unhijack();
sfi.CalculateCurrentMethodState();
// unwind to method below the one whose epilog set up the hijack
sfi.Next();
if (sfi.IsValid())
{
ip = sfi.GetRegisterSet()->GetIP();
}
}
}
if (bForceGC || pInstance->ShouldHijackCallsiteForGcStress(ip))
{
pCurrentThread->HijackReturnAddress(pSuspendCtx, &RhpGcStressHijack);
}
}
#endif // FEATURE_GC_STRESS
// This function is called from a thread to place a return hijack onto its own stack for GC stress cases
// via Thread::HijackForGcStress above. The only constraint on the suspension is that the
// stack be crawlable enough to yield the location of the return address.
void Thread::HijackReturnAddress(PAL_LIMITED_CONTEXT* pSuspendCtx, HijackFunc* pfnHijackFunction)
{
if (IsDoNotTriggerGcSet())
return;
StackFrameIterator frameIterator(this, pSuspendCtx);
if (!frameIterator.IsValid())
{
return;
}
HijackReturnAddressWorker(&frameIterator, pfnHijackFunction);
}
// This function is called in one of two scenarios:
// 1) from another thread to place a return hijack onto this thread's stack. In this case the target
// thread is OS suspended at pSuspendCtx in managed code.
// 2) from a thread to place a return hijack onto its own stack for GC suspension. In this case the target
// thread is interrupted at pSuspendCtx in managed code via a signal or similar.
void Thread::HijackReturnAddress(NATIVE_CONTEXT* pSuspendCtx, HijackFunc* pfnHijackFunction)
{
ASSERT(!IsDoNotTriggerGcSet());
StackFrameIterator frameIterator(this, pSuspendCtx);
ASSERT(frameIterator.IsValid());
HijackReturnAddressWorker(&frameIterator, pfnHijackFunction);
}
void Thread::HijackReturnAddressWorker(StackFrameIterator* frameIterator, HijackFunc* pfnHijackFunction)
{
void** ppvRetAddrLocation;
GCRefKind retValueKind;
frameIterator->CalculateCurrentMethodState();
if (frameIterator->GetCodeManager()->GetReturnAddressHijackInfo(frameIterator->GetMethodInfo(),
frameIterator->GetRegisterSet(),
&ppvRetAddrLocation,
&retValueKind))
{
ASSERT(ppvRetAddrLocation != NULL);
// if the new hijack location is the same, we do nothing
if (m_ppvHijackedReturnAddressLocation == ppvRetAddrLocation)
return;
// we only unhijack if we are going to install a new or better hijack.
CrossThreadUnhijack();
void* pvRetAddr = *ppvRetAddrLocation;
ASSERT(pvRetAddr != NULL);
ASSERT(StackFrameIterator::IsValidReturnAddress(pvRetAddr));
m_ppvHijackedReturnAddressLocation = ppvRetAddrLocation;
m_pvHijackedReturnAddress = pvRetAddr;
m_uHijackedReturnValueFlags = ReturnKindToTransitionFrameFlags(retValueKind);
*ppvRetAddrLocation = (void*)pfnHijackFunction;
STRESS_LOG2(LF_STACKWALK, LL_INFO10000, "InternalHijack: TgtThread = %llx, IP = %p\n",
GetPalThreadIdForLogging(), frameIterator->GetRegisterSet()->GetIP());
}
}
NATIVE_CONTEXT* Thread::GetInterruptedContext()
{
ASSERT(m_interruptedContext != NULL);
return m_interruptedContext;
}
#ifdef FEATURE_SUSPEND_REDIRECTION
NATIVE_CONTEXT* Thread::EnsureRedirectionContext()
{
if (m_redirectionContextBuffer == NULL)
{
m_interruptedContext = PalAllocateCompleteOSContext(&m_redirectionContextBuffer);
}
return m_interruptedContext;
}
bool Thread::Redirect()
{
ASSERT(!IsDoNotTriggerGcSet());
NATIVE_CONTEXT* redirectionContext = EnsureRedirectionContext();
if (redirectionContext == NULL)
return false;
if (!PalGetCompleteThreadContext(m_hPalThread, redirectionContext))
return false;
uintptr_t origIP = redirectionContext->GetIp();
redirectionContext->SetIp((uintptr_t)RhpSuspendRedirected);
if (!PalSetThreadContext(m_hPalThread, redirectionContext))
return false;
// the thread will now inevitably try to suspend
SetState(TSF_Redirected);
redirectionContext->SetIp(origIP);
STRESS_LOG2(LF_STACKWALK, LL_INFO10000, "InternalRedirect: TgtThread = %llx, IP = %p\n",
GetPalThreadIdForLogging(), origIP);
return true;
}
#endif //FEATURE_SUSPEND_REDIRECTION
bool Thread::InlineSuspend(NATIVE_CONTEXT* interruptedContext)
{
ASSERT(!IsDoNotTriggerGcSet());
Unhijack();
m_interruptedContext = interruptedContext;
WaitForGC(INTERRUPTED_THREAD_MARKER);
m_interruptedContext = NULL;
return true;
}
// This is the standard Unhijack, which is only allowed to be called on your own thread.
// Note that all the asm-implemented Unhijacks should also only be operating on their
// own thread.
void Thread::Unhijack()
{
ASSERT(ThreadStore::GetCurrentThread() == this);
ASSERT(IsCurrentThreadInCooperativeMode());
UnhijackWorker();
}
// This unhijack routine is called to undo a hijack, that is potentially on a different thread.
//
// Although there are many code sequences (here and in asm) to
// perform an unhijack operation, they will never execute concurrently:
//
// - A thread may unhijack itself at any time so long as it does that from unmanaged code while in coop mode.
// This ensures that coop thread can access its stack synchronously.
// Unhijacking from unmanaged code ensures that another thread will not attempt to hijack it,
// since we only hijack threads that are executing managed code.
//
// - A GC thread may access a thread asynchronously, including unhijacking it.
// Asynchronously accessed thread must be in preemptive mode and should not
// access the managed portion of its stack.
//
// - A thread that owns the suspension can access another thread as long as the other thread is
// in preemptive mode or suspended in managed code.
// Either way the other thread cannot be accessing its hijack.
//
void Thread::CrossThreadUnhijack()
{
ASSERT(((ThreadStore::GetCurrentThread() == this) && IsCurrentThreadInCooperativeMode()) ||
ThreadStore::GetCurrentThread()->IsGCSpecial() ||
ThreadStore::GetCurrentThread() == ThreadStore::GetSuspendingThread()
);
UnhijackWorker();
}
// This is the hijack worker routine which merely implements the hijack mechanism.
// DO NOT USE DIRECTLY. Use Unhijack() or CrossThreadUnhijack() instead.
void Thread::UnhijackWorker()
{
if (m_pvHijackedReturnAddress == NULL)
{
ASSERT(m_ppvHijackedReturnAddressLocation == NULL);
return;
}
// Restore the original return address.
ASSERT(m_ppvHijackedReturnAddressLocation != NULL);
*m_ppvHijackedReturnAddressLocation = m_pvHijackedReturnAddress;
// Clear the hijack state.
m_ppvHijackedReturnAddressLocation = NULL;
m_pvHijackedReturnAddress = NULL;
m_uHijackedReturnValueFlags = 0;
}
bool Thread::IsHijacked()
{
ASSERT(((ThreadStore::GetCurrentThread() == this) && IsCurrentThreadInCooperativeMode()) ||
ThreadStore::GetCurrentThread()->IsGCSpecial() ||
ThreadStore::GetCurrentThread() == ThreadStore::GetSuspendingThread()
);
return m_pvHijackedReturnAddress != NULL;
}
void Thread::SetState(ThreadStateFlags flags)
{
PalInterlockedOr(&m_ThreadStateFlags, flags);
}
void Thread::ClearState(ThreadStateFlags flags)
{
PalInterlockedAnd(&m_ThreadStateFlags, ~flags);
}
bool Thread::IsStateSet(ThreadStateFlags flags)
{
return ((m_ThreadStateFlags & flags) == (uint32_t) flags);
}
bool Thread::IsSuppressGcStressSet()
{
return IsStateSet(TSF_SuppressGcStress);
}
void Thread::SetSuppressGcStress()
{
ASSERT(!IsStateSet(TSF_SuppressGcStress));
SetState(TSF_SuppressGcStress);
}
void Thread::ClearSuppressGcStress()
{
ASSERT(IsStateSet(TSF_SuppressGcStress));
ClearState(TSF_SuppressGcStress);
}
#endif //!DACCESS_COMPILE
#ifndef DACCESS_COMPILE
#ifdef FEATURE_GC_STRESS
#ifdef HOST_X86 // the others are implemented in assembly code to avoid trashing the argument registers
EXTERN_C void FASTCALL RhpSuppressGcStress()
{
ThreadStore::GetCurrentThread()->SetSuppressGcStress();
}
#endif // HOST_X86
EXTERN_C void FASTCALL RhpUnsuppressGcStress()
{
ThreadStore::GetCurrentThread()->ClearSuppressGcStress();
}
#else
EXTERN_C void FASTCALL RhpSuppressGcStress()
{
}
EXTERN_C void FASTCALL RhpUnsuppressGcStress()
{
}
#endif // FEATURE_GC_STRESS
// Standard calling convention variant and actual implementation for RhpWaitForGC
EXTERN_C NOINLINE void FASTCALL RhpWaitForGC2(PInvokeTransitionFrame * pFrame)
{
Thread * pThread = pFrame->m_pThread;
if (pThread->IsDoNotTriggerGcSet())
return;