forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexceptionhandling.cpp
8770 lines (7537 loc) · 350 KB
/
exceptionhandling.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"
#ifdef FEATURE_EH_FUNCLETS
#include "exceptionhandling.h"
#include "dbginterface.h"
#include "asmconstants.h"
#include "eetoprofinterfacewrapper.inl"
#include "eedbginterfaceimpl.inl"
#include "eventtrace.h"
#include "virtualcallstub.h"
#include "utilcode.h"
#include "interoplibinterface.h"
#include "corinfo.h"
#include "exceptionhandlingqcalls.h"
#include "exinfo.h"
#include "configuration.h"
#if defined(TARGET_X86)
#define USE_CURRENT_CONTEXT_IN_FILTER
#endif // TARGET_X86
#if defined(TARGET_ARM) || defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
// ARM/ARM64 uses Caller-SP to locate PSPSym in the funclet frame.
#define USE_CALLER_SP_IN_FUNCLET
#endif // TARGET_ARM || TARGET_ARM64 || TARGET_LOONGARCH64 || TARGET_RISCV64
#if defined(TARGET_ARM) || defined(TARGET_ARM64) || defined(TARGET_X86) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
#define ADJUST_PC_UNWOUND_TO_CALL
#define STACK_RANGE_BOUNDS_ARE_CALLER_SP
#define USE_FUNCLET_CALL_HELPER
// For ARM/ARM64, EstablisherFrame is Caller-SP (SP just before executing call instruction).
// This has been confirmed by AaronGi from the kernel team for Windows.
//
// For x86/Linux, RtlVirtualUnwind sets EstablisherFrame as Caller-SP.
#define ESTABLISHER_FRAME_ADDRESS_IS_CALLER_SP
#endif // TARGET_ARM || TARGET_ARM64 || TARGET_X86 || TARGET_LOONGARCH64 || TARGET_RISCV64
#ifndef TARGET_UNIX
void NOINLINE
ClrUnwindEx(EXCEPTION_RECORD* pExceptionRecord,
UINT_PTR ReturnValue,
UINT_PTR TargetIP,
UINT_PTR TargetFrameSp);
#endif // !TARGET_UNIX
#if defined(TARGET_UNIX) && !defined(DACCESS_COMPILE)
VOID UnwindManagedExceptionPass2(PAL_SEHException& ex, CONTEXT* unwindStartContext);
#endif // TARGET_UNIX && !DACCESS_COMPILE
#ifdef USE_CURRENT_CONTEXT_IN_FILTER
inline void CaptureNonvolatileRegisters(PKNONVOLATILE_CONTEXT pNonvolatileContext, PCONTEXT pContext)
{
#define CALLEE_SAVED_REGISTER(reg) pNonvolatileContext->reg = pContext->reg;
ENUM_CALLEE_SAVED_REGISTERS();
#undef CALLEE_SAVED_REGISTER
}
inline void RestoreNonvolatileRegisters(PCONTEXT pContext, PKNONVOLATILE_CONTEXT pNonvolatileContext)
{
#define CALLEE_SAVED_REGISTER(reg) pContext->reg = pNonvolatileContext->reg;
ENUM_CALLEE_SAVED_REGISTERS();
#undef CALLEE_SAVED_REGISTER
}
inline void RestoreNonvolatileRegisterPointers(PT_KNONVOLATILE_CONTEXT_POINTERS pContextPointers, PKNONVOLATILE_CONTEXT pNonvolatileContext)
{
#define CALLEE_SAVED_REGISTER(reg) pContextPointers->reg = &pNonvolatileContext->reg;
ENUM_CALLEE_SAVED_REGISTERS();
#undef CALLEE_SAVED_REGISTER
}
#endif
#ifndef DACCESS_COMPILE
// o Functions and funclets are tightly associated. In fact, they are laid out in contiguous memory.
// They also present some interesting issues with respect to EH because we will see callstacks with
// both functions and funclets, but need to logically treat them as the original single IL function
// described them.
//
// o All funclets are ripped out of line from the main function. Finally clause are pulled out of
// line and replaced by calls to the funclets. Catch clauses, however, are simply pulled out of
// line. !!!This causes a loss of nesting information in clause offsets.!!! A canonical example of
// two different functions which look identical due to clause removal is as shown in the code
// snippets below. The reason they look identical in the face of out-of-line funclets is that the
// region bounds for the "try A" region collapse and become identical to the region bounds for
// region "try B". This will look identical to the region information for Bar because Bar must
// have a separate entry for each catch clause, both of which will have the same try-region bounds.
//
// void Foo() void Bar()
// { {
// try A try C
// { {
// try B BAR_BLK_1
// { }
// FOO_BLK_1 catch C
// } {
// catch B BAR_BLK_2
// { }
// FOO_BLK_2 catch D
// } {
// } BAR_BLK_3
// catch A }
// { }
// FOO_BLK_3
// }
// }
//
// O The solution is to duplicate all clauses that logically cover the funclet in its parent
// method, but with the try-region covering the entire out-of-line funclet code range. This will
// differentiate the canonical example above because the CatchB funclet will have a try-clause
// covering it whose associated handler is CatchA. In Bar, there is no such duplication of any clauses.
//
// o The behavior of the personality routine depends upon the JIT to properly order the clauses from
// inside-out. This allows us to properly handle a situation where our control PC is covered by clauses
// that should not be considered because a more nested clause will catch the exception and resume within
// the scope of the outer clauses.
//
// o This sort of clause duplication for funclets should be done for all clause types, not just catches.
// Unfortunately, I cannot articulate why at the moment.
//
#ifdef _DEBUG
void DumpClauses(IJitManager* pJitMan, const METHODTOKEN& MethToken, UINT_PTR uMethodStartPC, UINT_PTR dwControlPc);
static void DoEHLog(DWORD lvl, _In_z_ const char *fmt, ...);
#define EH_LOG(expr) { DoEHLog expr ; }
#else
#define EH_LOG(expr)
#endif
TrackerAllocator g_theTrackerAllocator;
uint32_t g_exceptionCount;
bool FixNonvolatileRegisters(UINT_PTR uOriginalSP,
Thread* pThread,
CONTEXT* pContextRecord,
bool fAborting
);
void FixContext(PCONTEXT pContextRecord)
{
#define FIXUPREG(reg, value) \
do { \
STRESS_LOG2(LF_GCROOTS, LL_INFO100, "Updating " #reg " %p to %p\n", \
pContextRecord->reg, \
(value)); \
pContextRecord->reg = (value); \
} while (0)
#ifdef TARGET_X86
size_t resumeSp = EECodeManager::GetResumeSp(pContextRecord);
FIXUPREG(Esp, resumeSp);
#endif // TARGET_X86
#undef FIXUPREG
}
MethodDesc * GetUserMethodForILStub(Thread * pThread, UINT_PTR uStubSP, MethodDesc * pILStubMD, Frame ** ppFrameOut);
#ifdef TARGET_UNIX
BOOL HandleHardwareException(PAL_SEHException* ex);
BOOL IsSafeToHandleHardwareException(PCONTEXT contextRecord, PEXCEPTION_RECORD exceptionRecord);
#endif // TARGET_UNIX
static ExceptionTracker* GetTrackerMemory()
{
CONTRACTL
{
GC_TRIGGERS;
NOTHROW;
MODE_ANY;
}
CONTRACTL_END;
return g_theTrackerAllocator.GetTrackerMemory();
}
void FreeTrackerMemory(ExceptionTracker* pTracker, TrackerMemoryType mem)
{
CONTRACTL
{
GC_NOTRIGGER;
NOTHROW;
MODE_ANY;
}
CONTRACTL_END;
if (mem & memManaged)
{
pTracker->ReleaseResources();
}
if (mem & memUnmanaged)
{
g_theTrackerAllocator.FreeTrackerMemory(pTracker);
}
}
static inline void UpdatePerformanceMetrics(CrawlFrame *pcfThisFrame, BOOL bIsRethrownException, BOOL bIsNewException)
{
WRAPPER_NO_CONTRACT;
InterlockedIncrement((LONG*)&g_exceptionCount);
// Fire an exception thrown ETW event when an exception occurs
ETW::ExceptionLog::ExceptionThrown(pcfThisFrame, bIsRethrownException, bIsNewException);
}
#ifdef TARGET_UNIX
static LONG volatile g_termination_triggered = 0;
void HandleTerminationRequest(int terminationExitCode)
{
// We set a non-zero exit code to indicate the process didn't terminate cleanly.
// This value can be changed by the user by setting Environment.ExitCode in the
// ProcessExit event. We only start termination on the first SIGTERM signal
// to ensure we don't overwrite an exit code already set in ProcessExit.
if (InterlockedCompareExchange(&g_termination_triggered, 1, 0) == 0)
{
SetLatchedExitCode(terminationExitCode);
ForceEEShutdown(SCA_ExitProcessWhenShutdownComplete);
}
}
#endif
void InitializeExceptionHandling()
{
EH_LOG((LL_INFO100, "InitializeExceptionHandling(): ExceptionTracker size: 0x%x bytes\n", sizeof(ExceptionTracker)));
CLRAddVectoredHandlers();
g_theTrackerAllocator.Init();
g_isNewExceptionHandlingEnabled = Configuration::GetKnobBooleanValue(W("System.Runtime.LegacyExceptionHandling"), CLRConfig::EXTERNAL_LegacyExceptionHandling ) == 0;
#ifdef TARGET_UNIX
// Register handler of hardware exceptions like null reference in PAL
PAL_SetHardwareExceptionHandler(HandleHardwareException, IsSafeToHandleHardwareException);
// Register handler for determining whether the specified IP has code that is a GC marker for GCCover
PAL_SetGetGcMarkerExceptionCode(GetGcMarkerExceptionCode);
// Register handler for termination requests (e.g. SIGTERM)
PAL_SetTerminationRequestHandler(HandleTerminationRequest);
#endif // TARGET_UNIX
}
struct UpdateObjectRefInResumeContextCallbackState
{
UINT_PTR uResumeSP;
Frame *pHighestFrameWithRegisters;
TADDR uResumeFrameFP;
TADDR uICFCalleeSavedFP;
#ifdef _DEBUG
UINT nFrames;
bool fFound;
#endif
};
// Stack unwind callback for UpdateObjectRefInResumeContext().
StackWalkAction UpdateObjectRefInResumeContextCallback(CrawlFrame* pCF, LPVOID pData)
{
CONTRACTL
{
MODE_ANY;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
UpdateObjectRefInResumeContextCallbackState *pState = (UpdateObjectRefInResumeContextCallbackState*)pData;
CONTEXT* pSrcContext = pCF->GetRegisterSet()->pCurrentContext;
INDEBUG(pState->nFrames++);
// Check to see if we have reached the resume frame.
if (pCF->IsFrameless())
{
// At this point, we are trying to find the managed frame containing the catch handler to be invoked.
// This is done by comparing the SP of the managed frame for which this callback was invoked with the
// SP the OS passed to our personality routine for the current managed frame. If they match, then we have
// reached the target frame.
//
// It is possible that a managed frame may execute a PInvoke after performing a stackalloc:
//
// 1) The ARM JIT will always inline the PInvoke in the managed frame, whether or not the frame
// contains EH. As a result, the ICF will live in the same frame which performs stackalloc.
//
// 2) JIT64 will only inline the PInvoke in the managed frame if the frame *does not* contain EH. If it does,
// then pinvoke will be performed via an ILStub and thus, stackalloc will be performed in a frame different
// from the one (ILStub) that contains the ICF.
//
// Thus, for the scenario where the catch handler lives in the frame that performed stackalloc, in case of
// ARM JIT, the SP returned by the OS will be the SP *after* the stackalloc has happened. However,
// the stackwalker will invoke this callback with the CrawlFrameSP that was initialized at the time ICF was setup, i.e.,
// it will be the SP after the prolog has executed (refer to InlinedCallFrame::UpdateRegDisplay).
//
// Thus, checking only the SP will not work for this scenario when using the ARM JIT.
//
// To address this case, the callback data also contains the frame pointer (FP) passed by the OS. This will
// be the value that is saved in the "CalleeSavedFP" field of the InlinedCallFrame during ICF
// initialization. When the stackwalker sees an ICF and invokes this callback, we copy the value of "CalleeSavedFP" in the data
// structure passed to this callback.
//
// Later, when the stackwalker invokes the callback for the managed frame containing the ICF, and the check
// for SP comaprison fails, we will compare the FP value we got from the ICF with the FP value the OS passed
// to us. If they match, then we have reached the resume frame.
//
// Note: This problem/scenario is not applicable to JIT64 since it does not perform pinvoke inlining if the
// method containing pinvoke also contains EH. Thus, the SP check will never fail for it.
if (pState->uResumeSP == GetSP(pSrcContext))
{
INDEBUG(pState->fFound = true);
return SWA_ABORT;
}
// Perform the FP check, as explained above.
if ((pState->uICFCalleeSavedFP !=0) && (pState->uICFCalleeSavedFP == pState->uResumeFrameFP))
{
// FP from ICF is the one that was also copied to the FP register in InlinedCallFrame::UpdateRegDisplay.
_ASSERTE(pState->uICFCalleeSavedFP == GetFP(pSrcContext));
INDEBUG(pState->fFound = true);
return SWA_ABORT;
}
// Reset the ICF FP in callback data
pState->uICFCalleeSavedFP = 0;
}
else
{
Frame *pFrame = pCF->GetFrame();
if (pFrame->NeedsUpdateRegDisplay())
{
CONSISTENCY_CHECK(pFrame >= pState->pHighestFrameWithRegisters);
pState->pHighestFrameWithRegisters = pFrame;
// Is this an InlinedCallFrame?
if (pFrame->GetVTablePtr() == InlinedCallFrame::GetMethodFrameVPtr())
{
// If we are here, then ICF is expected to be active.
_ASSERTE(InlinedCallFrame::FrameHasActiveCall(pFrame));
// Copy the CalleeSavedFP to the data structure that is passed this callback
// by the stackwalker. This is the value of frame pointer when ICF is setup
// in a managed frame.
//
// Setting this value here is based upon the assumption (which holds true on X64 and ARM) that
// the stackwalker invokes the callback for explicit frames before their
// container/corresponding managed frame.
pState->uICFCalleeSavedFP = ((PTR_InlinedCallFrame)pFrame)->GetCalleeSavedFP();
}
else
{
// For any other frame, simply reset uICFCalleeSavedFP field
pState->uICFCalleeSavedFP = 0;
}
}
}
return SWA_CONTINUE;
}
//
// Locates the locations of the nonvolatile registers. This will be used to
// retrieve the latest values of the object references before we resume
// execution from an exception.
//
//static
bool ExceptionTracker::FindNonvolatileRegisterPointers(Thread* pThread, UINT_PTR uOriginalSP, REGDISPLAY* pRegDisplay, TADDR uResumeFrameFP)
{
CONTRACTL
{
MODE_ANY;
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
//
// Find the highest frame below the resume frame that will update the
// REGDISPLAY. A normal StackWalkFrames will RtlVirtualUnwind through all
// managed frames on the stack, so this avoids some unnecessary work. The
// frame we find will have all of the nonvolatile registers/other state
// needed to start a managed unwind from that point.
//
Frame *pHighestFrameWithRegisters = NULL;
Frame *pFrame = pThread->GetFrame();
while ((UINT_PTR)pFrame < uOriginalSP)
{
if (pFrame->NeedsUpdateRegDisplay())
pHighestFrameWithRegisters = pFrame;
pFrame = pFrame->Next();
}
//
// Do a stack walk from this frame. This may find a higher frame within
// the resume frame (ex. inlined pinvoke frame). This will also update
// the REGDISPLAY pointers if any intervening managed frames saved
// nonvolatile registers.
//
UpdateObjectRefInResumeContextCallbackState state;
state.uResumeSP = uOriginalSP;
state.uResumeFrameFP = uResumeFrameFP;
state.uICFCalleeSavedFP = 0;
state.pHighestFrameWithRegisters = pHighestFrameWithRegisters;
INDEBUG(state.nFrames = 0);
INDEBUG(state.fFound = false);
pThread->StackWalkFramesEx(pRegDisplay, &UpdateObjectRefInResumeContextCallback, &state, 0, pHighestFrameWithRegisters);
// For managed exceptions, we should at least find a HelperMethodFrame (the one we put in IL_Throw()).
// For native exceptions such as AV's, we should at least find the FaultingExceptionFrame.
// If we don't find anything, then we must have hit an SO when we are trying to erect an HMF.
// Bail out in such situations.
//
// Note that pinvoke frames may be inlined in a managed method, so we cannot use the child SP (a.k.a. the current SP)
// to check for explicit frames "higher" on the stack ("higher" here means closer to the leaf frame). The stackwalker
// knows how to deal with inlined pinvoke frames, and it issues callbacks for them before issuing the callback for the
// containing managed method. So we have to do this check after we are done with the stackwalk.
pHighestFrameWithRegisters = state.pHighestFrameWithRegisters;
if (pHighestFrameWithRegisters == NULL)
{
return false;
}
CONSISTENCY_CHECK(state.nFrames);
CONSISTENCY_CHECK(state.fFound);
CONSISTENCY_CHECK(NULL != pHighestFrameWithRegisters);
//
// Now the REGDISPLAY has been unwound to the resume frame. The
// nonvolatile registers will either point into pHighestFrameWithRegisters,
// an inlined pinvoke frame, or into calling managed frames.
//
return true;
}
//static
void ExceptionTracker::UpdateNonvolatileRegisters(CONTEXT *pContextRecord, REGDISPLAY *pRegDisplay, bool fAborting)
{
CONTEXT* pAbortContext = NULL;
if (fAborting)
{
pAbortContext = GetThread()->GetAbortContext();
}
#ifndef TARGET_UNIX
#define HANDLE_NULL_CONTEXT_POINTER _ASSERTE(false)
#else // TARGET_UNIX
#define HANDLE_NULL_CONTEXT_POINTER
#endif // TARGET_UNIX
#define UPDATEREG(reg) \
do { \
if (pRegDisplay->pCurrentContextPointers->reg != NULL) \
{ \
STRESS_LOG3(LF_GCROOTS, LL_INFO100, "Updating " #reg " %p to %p from %p\n", \
pContextRecord->reg, \
*pRegDisplay->pCurrentContextPointers->reg, \
pRegDisplay->pCurrentContextPointers->reg); \
pContextRecord->reg = *pRegDisplay->pCurrentContextPointers->reg; \
} \
else \
{ \
HANDLE_NULL_CONTEXT_POINTER; \
} \
if (pAbortContext) \
{ \
pAbortContext->reg = pContextRecord->reg; \
} \
} while (0)
#if defined(TARGET_X86)
UPDATEREG(Ebx);
UPDATEREG(Esi);
UPDATEREG(Edi);
UPDATEREG(Ebp);
#elif defined(TARGET_AMD64)
UPDATEREG(Rbx);
UPDATEREG(Rbp);
#ifndef UNIX_AMD64_ABI
UPDATEREG(Rsi);
UPDATEREG(Rdi);
#endif
UPDATEREG(R12);
UPDATEREG(R13);
UPDATEREG(R14);
UPDATEREG(R15);
#elif defined(TARGET_ARM)
UPDATEREG(R4);
UPDATEREG(R5);
UPDATEREG(R6);
UPDATEREG(R7);
UPDATEREG(R8);
UPDATEREG(R9);
UPDATEREG(R10);
UPDATEREG(R11);
#elif defined(TARGET_ARM64)
UPDATEREG(X19);
UPDATEREG(X20);
UPDATEREG(X21);
UPDATEREG(X22);
UPDATEREG(X23);
UPDATEREG(X24);
UPDATEREG(X25);
UPDATEREG(X26);
UPDATEREG(X27);
UPDATEREG(X28);
UPDATEREG(Fp);
#elif defined(TARGET_LOONGARCH64)
UPDATEREG(S0);
UPDATEREG(S1);
UPDATEREG(S2);
UPDATEREG(S3);
UPDATEREG(S4);
UPDATEREG(S5);
UPDATEREG(S6);
UPDATEREG(S7);
UPDATEREG(S8);
UPDATEREG(Fp);
#elif defined(TARGET_RISCV64)
UPDATEREG(S1);
UPDATEREG(S2);
UPDATEREG(S3);
UPDATEREG(S4);
UPDATEREG(S5);
UPDATEREG(S6);
UPDATEREG(S7);
UPDATEREG(S8);
UPDATEREG(S9);
UPDATEREG(S10);
UPDATEREG(S11);
UPDATEREG(Fp);
#else
PORTABILITY_ASSERT("ExceptionTracker::UpdateNonvolatileRegisters");
#endif
#undef UPDATEREG
}
#ifndef _DEBUG
#define DebugLogExceptionRecord(pExceptionRecord)
#else // _DEBUG
#define LOG_FLAG(name) \
if (flags & name) \
{ \
LOG((LF_EH, LL_INFO100, "" #name " ")); \
} \
void DebugLogExceptionRecord(EXCEPTION_RECORD* pExceptionRecord)
{
ULONG flags = pExceptionRecord->ExceptionFlags;
EH_LOG((LL_INFO100, ">>exr: %p, code: %08x, addr: %p, flags: 0x%02x ", pExceptionRecord, pExceptionRecord->ExceptionCode, pExceptionRecord->ExceptionAddress, flags));
LOG_FLAG(EXCEPTION_NONCONTINUABLE);
LOG_FLAG(EXCEPTION_UNWINDING);
LOG_FLAG(EXCEPTION_EXIT_UNWIND);
LOG_FLAG(EXCEPTION_STACK_INVALID);
LOG_FLAG(EXCEPTION_NESTED_CALL);
LOG_FLAG(EXCEPTION_TARGET_UNWIND);
LOG_FLAG(EXCEPTION_COLLIDED_UNWIND);
LOG((LF_EH, LL_INFO100, "\n"));
}
LPCSTR DebugGetExceptionDispositionName(EXCEPTION_DISPOSITION disp)
{
switch (disp)
{
case ExceptionContinueExecution: return "ExceptionContinueExecution";
case ExceptionContinueSearch: return "ExceptionContinueSearch";
case ExceptionNestedException: return "ExceptionNestedException";
case ExceptionCollidedUnwind: return "ExceptionCollidedUnwind";
default:
UNREACHABLE_MSG("Invalid EXCEPTION_DISPOSITION!");
}
}
#endif // _DEBUG
bool ExceptionTracker::IsStackOverflowException()
{
if (m_pThread->GetThrowableAsHandle() == g_pPreallocatedStackOverflowException)
{
return true;
}
return false;
}
UINT_PTR ExceptionTracker::CallCatchHandler(CONTEXT* pContextRecord, bool* pfAborting /*= NULL*/)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_TRIGGERS;
THROWS;
PRECONDITION(CheckPointer(pContextRecord, NULL_OK));
}
CONTRACTL_END;
UINT_PTR uResumePC = 0;
ULONG_PTR ulRelOffset;
StackFrame sfStackFp = m_sfResumeStackFrame;
Thread* pThread = m_pThread;
MethodDesc* pMD = m_pMethodDescOfCatcher;
bool fIntercepted = false;
ThreadExceptionState* pExState = pThread->GetExceptionState();
#if defined(DEBUGGING_SUPPORTED)
// If the exception is intercepted, use the information stored in the DebuggerExState to resume the
// exception instead of calling the catch clause (there may not even be one).
if (pExState->GetFlags()->DebuggerInterceptInfo())
{
_ASSERTE(pMD != NULL);
// retrieve the interception information
pExState->GetDebuggerState()->GetDebuggerInterceptInfo(NULL, NULL, (PBYTE*)&(sfStackFp.SP), &ulRelOffset, NULL);
PCODE pStartAddress = pMD->GetNativeCode();
EECodeInfo codeInfo(pStartAddress);
_ASSERTE(codeInfo.IsValid());
// Note that the value returned for ulRelOffset is actually the offset,
// so we need to adjust it to get the actual IP.
_ASSERTE(FitsIn<DWORD>(ulRelOffset));
uResumePC = codeInfo.GetJitManager()->GetCodeAddressForRelOffset(codeInfo.GetMethodToken(), static_cast<DWORD>(ulRelOffset));
// Either we haven't set m_uResumeStackFrame (for unhandled managed exceptions), or we have set it
// and it equals to MemoryStackFp.
_ASSERTE(m_sfResumeStackFrame.IsNull() || m_sfResumeStackFrame == sfStackFp);
fIntercepted = true;
}
#endif // DEBUGGING_SUPPORTED
_ASSERTE(!sfStackFp.IsNull());
m_sfResumeStackFrame.Clear();
m_pMethodDescOfCatcher = NULL;
_ASSERTE(pContextRecord);
//
// call the handler
//
EH_LOG((LL_INFO100, " calling catch at 0x%p\n", m_uCatchToCallPC));
// do not call the catch clause if the exception is intercepted
if (!fIntercepted)
{
_ASSERTE(m_uCatchToCallPC != 0 && m_pClauseForCatchToken != NULL);
uResumePC = CallHandler(m_uCatchToCallPC, sfStackFp, &m_ClauseForCatch, pMD, Catch, pContextRecord);
}
else
{
// Since the exception has been intercepted and we could resuming execution at any
// user-specified arbitrary location, reset the EH clause index and EstablisherFrame
// we may have saved for addressing any potential ThreadAbort raise.
//
// This is done since the saved EH clause index is related to the catch block executed,
// which does not happen in interception. As user specifies where we resume execution,
// we let that behaviour override the index and pretend as if we have no index available.
m_dwIndexClauseForCatch = 0;
m_sfEstablisherOfActualHandlerFrame.Clear();
m_sfCallerOfActualHandlerFrame.Clear();
}
EH_LOG((LL_INFO100, " resume address should be 0x%p\n", uResumePC));
//
// Our tracker may have gone away at this point, don't reference it.
//
return FinishSecondPass(pThread, uResumePC, sfStackFp, pContextRecord, this, pfAborting);
}
// static
UINT_PTR ExceptionTracker::FinishSecondPass(
Thread* pThread,
UINT_PTR uResumePC,
StackFrame sf,
CONTEXT* pContextRecord,
ExceptionTracker* pTracker,
bool* pfAborting /*= NULL*/)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
PRECONDITION(CheckPointer(pThread, NULL_NOT_OK));
PRECONDITION(CheckPointer((void*)uResumePC, NULL_NOT_OK));
PRECONDITION(CheckPointer(pContextRecord, NULL_OK));
}
CONTRACTL_END;
// Between the time when we pop the ExceptionTracker for the current exception and the time
// when we actually resume execution, it is unsafe to start a funclet-skipping stackwalk.
// So we set a flag here to indicate that we are in this time window. The only user of this
// information right now is the profiler.
ThreadExceptionFlagHolder tefHolder(ThreadExceptionState::TEF_InconsistentExceptionState);
#ifdef DEBUGGING_SUPPORTED
// This must be done before we pop the trackers.
BOOL fIntercepted = pThread->GetExceptionState()->GetFlags()->DebuggerInterceptInfo();
#endif // DEBUGGING_SUPPORTED
// Since we may [re]raise ThreadAbort post the catch block execution,
// save the index, and Establisher, of the EH clause corresponding to the handler
// we just executed before we release the tracker. This will be used to ensure that reraise
// proceeds forward and not get stuck in a loop. Refer to
// ExceptionTracker::ProcessManagedCallFrame for details.
DWORD ehClauseCurrentHandlerIndex = pTracker->GetCatchHandlerExceptionClauseIndex();
StackFrame sfEstablisherOfActualHandlerFrame = pTracker->GetEstablisherOfActualHandlingFrame();
EH_LOG((LL_INFO100, "second pass finished\n"));
EH_LOG((LL_INFO100, "cleaning up ExceptionTracker state\n"));
// Release the exception trackers till the current (specified) frame.
ExceptionTracker::PopTrackers(sf, true);
// This will set the last thrown to be either null if we have handled all the exceptions in the nested chain or
// to whatever the current exception is.
//
// In a case when we're nested inside another catch block, the domain in which we're executing may not be the
// same as the one the domain of the throwable that was just made the current throwable above. Therefore, we
// make a special effort to preserve the domain of the throwable as we update the last thrown object.
//
// If an exception is active, we dont want to reset the LastThrownObject to NULL as the active exception
// might be represented by a tracker created in the second pass (refer to
// CEHelper::SetupCorruptionSeverityForActiveExceptionInUnwindPass to understand how exception trackers can be
// created in the 2nd pass on 64bit) that does not have a throwable attached to it. Thus, if this exception
// is caught in the VM and it attempts to get the LastThrownObject using GET_THROWABLE macro, then it should be available.
//
// But, if the active exception tracker remains consistent in the 2nd pass (which will happen if the exception is caught
// in managed code), then the call to SafeUpdateLastThrownObject below will automatically update the LTO as per the
// active exception.
if (!pThread->GetExceptionState()->IsExceptionInProgress())
{
pThread->SafeSetLastThrownObject(NULL);
}
// Sync managed exception state, for the managed thread, based upon any active exception tracker
pThread->SyncManagedExceptionState(false);
//
// If we are aborting, we should not resume execution. Instead, we raise another
// exception. However, we do this by resuming execution at our thread redirecter
// function (RedirectForThrowControl), which is the same process we use for async
// thread stops. This redirecter function will cover the stack frame and register
// stack frame and then throw an exception. When we first see the exception thrown
// by this redirecter, we fixup the context for the thread stackwalk by copying
// pThread->m_OSContext into the dispatcher context and restarting the exception
// dispatch. As a result, we need to save off the "correct" resume context before
// we resume so the exception processing can work properly after redirect. A side
// benefit of this mechanism is that it makes synchronous and async thread abort
// use exactly the same codepaths.
//
UINT_PTR uAbortAddr = 0;
#if defined(DEBUGGING_SUPPORTED)
// Don't honour thread abort requests at this time for intercepted exceptions.
if (fIntercepted)
{
uAbortAddr = 0;
}
else
#endif // !DEBUGGING_SUPPORTED
{
CopyOSContext(pThread->m_OSContext, pContextRecord);
SetIP(pThread->m_OSContext, (PCODE)uResumePC);
#if defined(TARGET_UNIX) && defined(TARGET_X86)
uAbortAddr = NULL;
#else
uAbortAddr = (UINT_PTR)COMPlusCheckForAbort(uResumePC);
#endif
}
if (uAbortAddr)
{
if (pfAborting != NULL)
{
*pfAborting = true;
}
EH_LOG((LL_INFO100, "thread abort in progress, resuming thread under control...\n"));
// We are aborting, so keep the reference to the current EH clause index.
// We will use this when the exception is reraised and we begin commencing
// exception dispatch. This is done in ExceptionTracker::ProcessOSExceptionNotification.
//
// The "if" condition below can be false if the exception has been intercepted (refer to
// ExceptionTracker::CallCatchHandler for details)
if ((ehClauseCurrentHandlerIndex > 0) && (!sfEstablisherOfActualHandlerFrame.IsNull()))
{
pThread->m_dwIndexClauseForCatch = ehClauseCurrentHandlerIndex;
pThread->m_sfEstablisherOfActualHandlerFrame = sfEstablisherOfActualHandlerFrame;
}
CONSISTENCY_CHECK(CheckPointer(pContextRecord));
STRESS_LOG1(LF_EH, LL_INFO10, "resume under control: ip: %p\n", uResumePC);
#ifdef TARGET_AMD64
#ifdef TARGET_UNIX
pContextRecord->Rdi = uResumePC;
pContextRecord->Rsi = GetIP(pThread->GetAbortContext());
#else
pContextRecord->Rcx = uResumePC;
#endif
#elif defined(TARGET_ARM) || defined(TARGET_ARM64)
// On ARM & ARM64, we save off the original PC in Lr. This is the same as done
// in HandleManagedFault for H/W generated exceptions.
pContextRecord->Lr = uResumePC;
#elif defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
pContextRecord->Ra = uResumePC;
#endif
uResumePC = uAbortAddr;
}
CONSISTENCY_CHECK(pThread->DetermineIfGuardPagePresent());
EH_LOG((LL_INFO100, "FinishSecondPass complete, uResumePC = %p, current SP = %p\n", uResumePC, GetCurrentSP()));
return uResumePC;
}
void CleanUpForSecondPass(Thread* pThread, bool fIsSO, LPVOID MemoryStackFpForFrameChain, LPVOID MemoryStackFp);
static void PopExplicitFrames(Thread *pThread, void *targetSp, void *targetCallerSp)
{
Frame* pFrame = pThread->GetFrame();
while (pFrame < targetSp)
{
pFrame->ExceptionUnwind();
pFrame->Pop(pThread);
pFrame = pThread->GetFrame();
}
// Check if the pFrame is an active InlinedCallFrame inside of the target frame. It needs to be popped or inactivated depending
// on the target architecture / ready to run
if ((pFrame < targetCallerSp) && InlinedCallFrame::FrameHasActiveCall(pFrame))
{
InlinedCallFrame* pInlinedCallFrame = (InlinedCallFrame*)pFrame;
// When unwinding an exception in ReadyToRun, the JIT_PInvokeEnd helper which unlinks the ICF from
// the thread will be skipped. This is because unlike jitted code, each pinvoke is wrapped by calls
// to the JIT_PInvokeBegin and JIT_PInvokeEnd helpers, which push and pop the ICF on the thread. The
// ICF is not linked at the method prolog and unlined at the epilog when running R2R code. Since the
// JIT_PInvokeEnd helper will be skipped, we need to unlink the ICF here. If the executing method
// has another pinvoke, it will re-link the ICF again when the JIT_PInvokeBegin helper is called.
TADDR returnAddress = pInlinedCallFrame->m_pCallerReturnAddress;
#ifdef USE_PER_FRAME_PINVOKE_INIT
// If we're setting up the frame for each P/Invoke for the given platform,
// then we do this for all P/Invokes except ones in IL stubs.
// IL stubs link the frame in for the whole stub, so if an exception is thrown during marshalling,
// the ICF will be on the frame chain and inactive.
if (!ExecutionManager::GetCodeMethodDesc(returnAddress)->IsILStub())
#else
// If we aren't setting up the frame for each P/Invoke (instead setting up once per method),
// then ReadyToRun code is the only code using the per-P/Invoke logic.
if (ExecutionManager::IsReadyToRunCode(returnAddress))
#endif
{
pFrame->ExceptionUnwind();
pFrame->Pop(pThread);
}
else
{
pInlinedCallFrame->Reset();
}
}
GCFrame* pGCFrame = pThread->GetGCFrame();
while (pGCFrame && pGCFrame < targetSp)
{
pGCFrame->Pop();
pGCFrame = pThread->GetGCFrame();
}
}
EXTERN_C EXCEPTION_DISPOSITION
ProcessCLRExceptionNew(IN PEXCEPTION_RECORD pExceptionRecord,
IN PVOID pEstablisherFrame,
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
//
// This method doesn't always return, so it will leave its
// state on the thread if using dynamic contracts.
//
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_THROWS;
Thread* pThread = GetThread();
if (pThread->HasThreadStateNC(Thread::TSNC_ProcessedUnhandledException))
{
if ((pExceptionRecord->ExceptionFlags & EXCEPTION_UNWINDING))
{
GCX_COOP();
PopExplicitFrames(pThread, (void*)pDispatcherContext->EstablisherFrame, (void*)GetSP(pDispatcherContext->ContextRecord));
ExInfo::PopExInfos(pThread, (void*)pDispatcherContext->EstablisherFrame);
}
return ExceptionContinueSearch;
}
#ifndef HOST_UNIX
if (!(pExceptionRecord->ExceptionFlags & EXCEPTION_UNWINDING))
{
// Failfast if exception indicates corrupted process state
if (IsProcessCorruptedStateException(pExceptionRecord->ExceptionCode, /* throwable */ NULL))
{
EEPOLICY_HANDLE_FATAL_ERROR(pExceptionRecord->ExceptionCode);
}
ClrUnwindEx(pExceptionRecord,
(UINT_PTR)pThread,
INVALID_RESUME_ADDRESS,
pDispatcherContext->EstablisherFrame);
}
else
{
GCX_COOP();
ThreadExceptionState* pExState = pThread->GetExceptionState();
ExInfo *pPrevExInfo = (ExInfo*)pExState->GetCurrentExceptionTracker();
if (pPrevExInfo != NULL && pPrevExInfo->m_DebuggerExState.GetDebuggerInterceptContext() != NULL)
{
ContinueExceptionInterceptionUnwind();
UNREACHABLE();
}
else
{
OBJECTREF oref = ExceptionTracker::CreateThrowable(pExceptionRecord, FALSE);
DispatchManagedException(oref, pContextRecord, pExceptionRecord);
}
}
#endif // !HOST_UNIX
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, _T("SEH exception leaked into managed code"));
UNREACHABLE();
}
EXTERN_C EXCEPTION_DISPOSITION
ProcessCLRException(IN PEXCEPTION_RECORD pExceptionRecord,
IN PVOID pEstablisherFrame,
IN OUT PCONTEXT pContextRecord,
IN OUT PDISPATCHER_CONTEXT pDispatcherContext
)
{
//
// This method doesn't always return, so it will leave its
// state on the thread if using dynamic contracts.
//
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_THROWS;
if (g_isNewExceptionHandlingEnabled)
{
return ProcessCLRExceptionNew(pExceptionRecord, pEstablisherFrame, pContextRecord, pDispatcherContext);
}