forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexceptionhandling.cpp
More file actions
4466 lines (3775 loc) · 164 KB
/
exceptionhandling.cpp
File metadata and controls
4466 lines (3775 loc) · 164 KB
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 "exceptionhandling.h"
#include "dbginterface.h"
#include "asmconstants.h"
#include "eetoprofinterfacewrapper.inl"
#include "eedbginterfaceimpl.inl"
#include "eventtrace.h"
#include "virtualcallstub.h"
#include "utilcode.h"
#include "corelib.h"
#include "interoplibinterface.h"
#include "corinfo.h"
#include "exceptionhandlingqcalls.h"
#include "exinfo.h"
#include "configuration.h"
extern MethodDesc* g_pThreadStartCallbackMethodDesc;
extern MethodDesc* g_pGCRunFinalizersMethodDesc;
#if defined(TARGET_X86)
#define USE_CURRENT_CONTEXT_IN_FILTER
#endif // TARGET_X86
#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
// 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);
#ifdef TARGET_X86
EXTERN_C BOOL CallRtlUnwind(EXCEPTION_REGISTRATION_RECORD *pEstablisherFrame, PVOID callback, EXCEPTION_RECORD *pExceptionRecord, PVOID retval);
#endif
#endif // !TARGET_UNIX
#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
uint32_t g_exceptionCount;
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
}
#ifdef TARGET_UNIX
BOOL HandleHardwareException(PAL_SEHException* ex);
BOOL IsSafeToHandleHardwareException(PCONTEXT contextRecord, PEXCEPTION_RECORD exceptionRecord);
#endif // TARGET_UNIX
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);
}
void InitializeExceptionHandling()
{
EH_LOG((LL_INFO100, "InitializeExceptionHandling(): ExInfo size: 0x%x bytes\n", sizeof(ExInfo)));
CLRAddVectoredHandlers();
#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);
#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->GetFrameIdentifier() == FrameIdentifier::InlinedCallFrame)
{
// 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;
}
//static
void ExInfo::UpdateNonvolatileRegisters(CONTEXT *pContextRecord, REGDISPLAY *pRegDisplay, bool fAborting)
{
CONTEXT* pAbortContext = NULL;
if (fAborting)
{
pAbortContext = GetThread()->GetAbortContext();
}
// Windows/x86 doesn't have unwinding mechanism for native code. RtlUnwind in
// ProcessCLRException leaves us with the original exception context. Thus we
// rely solely on our frames and managed code unwinding. This also means that
// if we pass through InlinedCallFrame we end up with empty context pointers.
// With the interpreter enabled, we may also get NULL context pointers.
#if defined(TARGET_UNIX) || defined(TARGET_X86) || defined(FEATURE_INTERPRETER)
#define HANDLE_NULL_CONTEXT_POINTER
#else // TARGET_UNIX || TARGET_X86
#define HANDLE_NULL_CONTEXT_POINTER _ASSERTE(false)
#endif // TARGET_UNIX || TARGET_X86
#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);
#elif defined(TARGET_WASM)
// nothing to do, wasm doesn't have registers
#else
PORTABILITY_ASSERT("ExInfo::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
void CleanUpForSecondPass(Thread* pThread, bool fIsSO, LPVOID MemoryStackFpForFrameChain, LPVOID MemoryStackFp);
static void PopExplicitFrames(Thread *pThread, void *targetSp, void *targetCallerSp, bool popGCFrames = true)
{
#if defined(TARGET_X86) && defined(TARGET_WINDOWS)
PopSEHRecords((void*)targetSp);
#endif
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();
}
}
if (popGCFrames)
{
GCFrame* pGCFrame = pThread->GetGCFrame();
while ((pGCFrame != GCFRAME_TOP) && pGCFrame->GetOSStackLocation() < targetSp)
{
pGCFrame->Pop();
pGCFrame = pThread->GetGCFrame();
}
}
}
#if defined(HOST_WINDOWS) && defined(HOST_X86)
static void DispatchLongJmp(IN PEXCEPTION_RECORD pExceptionRecord,
IN PVOID pEstablisherFrame,
IN OUT PCONTEXT pContextRecord)
{
// Pop all the SEH frames including the one that is currently called
// to prevent setjmp from trying to unwind it again when we inject our
// longjmp.
SetCurrentSEHRecord(((PEXCEPTION_REGISTRATION_RECORD)pEstablisherFrame)->Next);
#pragma warning(push)
#pragma warning(disable:4611) // interaction between 'function' and C++ object destruction is non-portable
jmp_buf jumpBuffer;
if (setjmp(jumpBuffer))
{
// We reach this point after the finally handlers were called and
// the unwinding should continue below the managed frame.
return;
}
#pragma warning(pop)
// Emulate the parameters that are passed on 64-bit systems and expected by
// DispatchManagedException.
EXCEPTION_RECORD newExceptionRecord = *pExceptionRecord;
newExceptionRecord.NumberParameters = 2;
newExceptionRecord.ExceptionInformation[0] = (DWORD_PTR)&jumpBuffer;
newExceptionRecord.ExceptionInformation[1] = 1;
OBJECTREF oref = ExInfo::CreateThrowable(&newExceptionRecord, FALSE);
DispatchManagedException(oref, pContextRecord, &newExceptionRecord);
UNREACHABLE();
}
#endif
EXTERN_C EXCEPTION_DISPOSITION __cdecl
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;
Thread* pThread = GetThread();
// On x86 we don't have dispatcher context
#ifndef TARGET_X86
// Skip native frames of asm helpers that have the ProcessCLRException set as their personality routine.
// There is nothing to do for those with the new exception handling.
if (!ExecutionManager::IsManagedCode((PCODE)pDispatcherContext->ControlPc))
{
return ExceptionContinueSearch;
}
#endif
// Also skip all frames when processing unhandled exceptions. That allows them to reach the host app
// level and let 3rd party the chance to handle them.
if (pThread->HasThreadStateNC(Thread::TSNC_SkipManagedPersonalityRoutine))
{
if (pExceptionRecord->ExceptionFlags & EXCEPTION_UNWINDING)
{
// The 3rd argument passes to PopExplicitFrame is normally the parent SP to correctly handle InlinedCallFrame embbeded
// in parent managed frame. But at this point there are no further managed frames are on the stack, so we can pass NULL.
// Also don't pop the GC frames, their destructor will pop them as the exception propagates.
// NOTE: this needs to be popped in the 2nd pass to ensure that crash dumps and Watson get the dump with these still
// present.
ExInfo *pExInfo = (ExInfo*)pThread->GetExceptionState()->GetCurrentExceptionTracker();
if (pExInfo != NULL)
{
GCX_COOP();
void *sp = (void*)GetRegdisplaySP(pExInfo->m_frameIter.m_crawl.GetRegisterSet());
PopExplicitFrames(pThread, sp, NULL /* targetCallerSp */, false /* popGCFrames */);
ExInfo::PopExInfos(pThread, sp);
}
}
return ExceptionContinueSearch;
}
#ifndef HOST_UNIX
// First pass (searching)
if (!(pExceptionRecord->ExceptionFlags & EXCEPTION_UNWINDING))
{
// If the exception is a breakpoint, let it go. The managed exception handling
// doesn't process breakpoints.
if ((pExceptionRecord->ExceptionCode == STATUS_BREAKPOINT) ||
(pExceptionRecord->ExceptionCode == STATUS_SINGLE_STEP))
{
return ExceptionContinueSearch;
}
// Failfast if exception indicates corrupted process state
if (IsProcessCorruptedStateException(pExceptionRecord->ExceptionCode, /* throwable */ NULL))
{
EEPOLICY_HANDLE_FATAL_ERROR(pExceptionRecord->ExceptionCode);
}
#ifdef TARGET_X86
CallRtlUnwind((PEXCEPTION_REGISTRATION_RECORD)pEstablisherFrame, NULL, pExceptionRecord, 0);
#else
ClrUnwindEx(pExceptionRecord,
(UINT_PTR)pThread,
INVALID_RESUME_ADDRESS,
pDispatcherContext->EstablisherFrame);
UNREACHABLE();
#endif
}
// Second pass (unwinding)
GCX_COOP_NO_DTOR();
ThreadExceptionState* pExState = pThread->GetExceptionState();
ExInfo *pPrevExInfo = (ExInfo*)pExState->GetCurrentExceptionTracker();
if (pPrevExInfo != NULL && pPrevExInfo->m_DebuggerExState.GetDebuggerInterceptContext() != NULL)
{
ContinueExceptionInterceptionUnwind();
UNREACHABLE();
}
#if defined(HOST_WINDOWS) && defined(HOST_X86)
else if (pExceptionRecord->ExceptionCode == STATUS_LONGJUMP)
{
DispatchLongJmp(pExceptionRecord, pEstablisherFrame, pContextRecord);
GCX_COOP_NO_DTOR_END();
return ExceptionContinueSearch;
}
#endif
else
{
OBJECTREF oref = ExInfo::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();
}
#if defined(DEBUGGING_SUPPORTED)
BOOL NotifyDebuggerOfStub(Thread* pThread, Frame* pCurrentFrame)
{
LIMITED_METHOD_CONTRACT;
BOOL fDeliveredFirstChanceNotification = FALSE;
_ASSERTE(GetThreadNULLOk() == pThread);
GCX_COOP();
// For debugger, we may want to notify 1st chance exceptions if they're coming out of a stub.
// We recognize stubs as Frames with a M2U transition type. The debugger's stackwalker also
// recognizes these frames and publishes ICorDebugInternalFrames in the stackwalk. It's
// important to use pFrame as the stack address so that the Exception callback matches up
// w/ the ICorDebugInternalFrame stack range.
if (CORDebuggerAttached())
{
if (pCurrentFrame->GetTransitionType() == Frame::TT_M2U)
{
// Use -1 for the backing store pointer whenever we use the address of a frame as the stack pointer.
EEToDebuggerExceptionInterfaceWrapper::FirstChanceManagedException(pThread,
(SIZE_T)0,
(SIZE_T)pCurrentFrame);
fDeliveredFirstChanceNotification = TRUE;
}
}
return fDeliveredFirstChanceNotification;
}
#endif // DEBUGGING_SUPPORTED
#undef OPTIONAL_SO_CLEANUP_UNWIND
#define OPTIONAL_SO_CLEANUP_UNWIND(pThread, pFrame) if (pThread->GetFrame() < pFrame) { UnwindFrameChain(pThread, pFrame); }
#undef OPTIONAL_SO_CLEANUP_UNWIND
#define OPTIONAL_SO_CLEANUP_UNWIND(pThread, pFrame)
//
// this must be done after the second pass has run, it does not
// reference anything on the stack, so it is safe to run in an
// SEH __except clause as well as a C++ catch clause.
//
// static
void ExInfo::PopTrackers(
void* pStackFrameSP
)
{
CONTRACTL
{
MODE_ANY;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
StackFrame sf((UINT_PTR)pStackFrameSP);
// Only call into PopTrackers if we have a managed thread and we have an exception progress.
// Otherwise, the call below (to PopTrackers) is a noop. If this ever changes, then this short-circuit needs to be fixed.
Thread *pCurThread = GetThreadNULLOk();
if ((pCurThread != NULL) && (pCurThread->GetExceptionState()->IsExceptionInProgress()))
{
// Refer to the comment around ExInfo::HasFrameBeenUnwoundByAnyActiveException
// for details on the usage of this COOP switch.
GCX_COOP();
PopTrackers(sf, false);
}
}
//
// static
void ExInfo::PopTrackers(
StackFrame sfResumeFrame,
bool fPopWhenEqual
)
{
CONTRACTL
{
// Refer to the comment around ExInfo::HasFrameBeenUnwoundByAnyActiveException
// for details on the mode being COOP here.
MODE_COOPERATIVE;
GC_NOTRIGGER;
NOTHROW;
}
CONTRACTL_END;
return;
}
//
// static
OBJECTREF ExInfo::CreateThrowable(
PEXCEPTION_RECORD pExceptionRecord,
BOOL bAsynchronousThreadStop
)
{
CONTRACTL
{
MODE_COOPERATIVE;
GC_TRIGGERS;
NOTHROW;
}
CONTRACTL_END;
OBJECTREF oThrowable = NULL;
Thread* pThread = GetThread();
if ((!bAsynchronousThreadStop) && IsComPlusException(pExceptionRecord))
{
oThrowable = pThread->LastThrownObject();
}
else
{
oThrowable = CreateCOMPlusExceptionObject(pThread, pExceptionRecord, bAsynchronousThreadStop);
}
return oThrowable;
}
#ifdef _DEBUG
//
// static
UINT_PTR ExInfo::DebugComputeNestingLevel()
{
UINT_PTR uNestingLevel = 0;
Thread* pThread = GetThreadNULLOk();
if (pThread)
{
PTR_ExInfo pTracker;
pTracker = pThread->GetExceptionState()->GetCurrentExceptionTracker();
while (pTracker)
{
uNestingLevel++;
pTracker = pTracker->m_pPrevNestedInfo;
};
}
return uNestingLevel;
}
void DumpClauses(IJitManager* pJitMan, const METHODTOKEN& MethToken, UINT_PTR uMethodStartPC, UINT_PTR dwControlPc)
{
EH_CLAUSE_ENUMERATOR EnumState;
unsigned EHCount;
EH_LOG((LL_INFO1000, " | uMethodStartPC: %p, ControlPc at offset %x\n", uMethodStartPC, dwControlPc - uMethodStartPC));
EHCount = pJitMan->InitializeEHEnumeration(MethToken, &EnumState);
for (unsigned i = 0; i < EHCount; i++)
{
EE_ILEXCEPTION_CLAUSE EHClause;
pJitMan->GetNextEHClause(&EnumState, &EHClause);
EH_LOG((LL_INFO1000, " | %s clause [%x, %x], handler: [%x, %x]",
(IsFault(&EHClause) ? "fault" :
(IsFinally(&EHClause) ? "finally" :
(IsFilterHandler(&EHClause) ? "filter" :
(IsTypedHandler(&EHClause) ? "typed" : "unknown")))),
EHClause.TryStartPC , // + uMethodStartPC,
EHClause.TryEndPC , // + uMethodStartPC,
EHClause.HandlerStartPC , // + uMethodStartPC,
EHClause.HandlerEndPC // + uMethodStartPC
));
if (IsFilterHandler(&EHClause))
{
LOG((LF_EH, LL_INFO1000, " filter: [%x, ...]",
EHClause.FilterOffset));// + uMethodStartPC
}
LOG((LF_EH, LL_INFO1000, "\n"));
}
}
#define STACK_ALLOC_ARRAY(numElements, type) \
((type *)_alloca((numElements)*(sizeof(type))))
static void DoEHLog(
DWORD lvl,
_In_z_ const char *fmt,
...
)
{
if (!LoggingOn(LF_EH, lvl))
return;
va_list args;
va_start(args, fmt);
UINT_PTR nestinglevel = ExInfo::DebugComputeNestingLevel();
if (nestinglevel)
{
_ASSERTE(FitsIn<UINT_PTR>(2 * nestinglevel));
UINT_PTR cch = 2 * nestinglevel;
char* pPadding = STACK_ALLOC_ARRAY(cch + 1, char);
memset(pPadding, '.', cch);
pPadding[cch] = 0;
LOG((LF_EH, lvl, pPadding));
}
LogSpewValist(LF_EH, lvl, fmt, args);
va_end(args);
}
#endif // _DEBUG
#ifdef TARGET_UNIX
//---------------------------------------------------------------------------------------
//
// Function to update the current context for exception propagation.
//
// Arguments:
// callback - the exception propagation callback
// callbackCtx - the exception propagation callback context
// currentContext - the current context to update.
//
static VOID UpdateContextForPropagationCallback(
Interop::ManagedToNativeExceptionCallback callback,
void *callbackCtx,
CONTEXT* startContext)
{
_ASSERTE(callback != NULL);
#ifdef TARGET_AMD64
// Don't restore the stack pointer to exact same context. Leave the
// return IP on the stack to let the unwinder work if the callback throws
// an exception as opposed to failing fast.
startContext->Rsp -= sizeof(void*);
// Pass the context for the callback as the first argument.
startContext->Rdi = (DWORD64)callbackCtx;
#elif defined(TARGET_ARM64)
// Reset the linked return register to the current function to let the
// unwinder work if the callback throws an exception as opposed to failing fast.
startContext->Lr = GetIP(startContext);
// Pass the context for the callback as the first argument.
startContext->X0 = (DWORD64)callbackCtx;
#elif defined(TARGET_ARM)
// Reset the linked return register to the current function to let the
// unwinder work if the callback throws an exception as opposed to failing fast.
startContext->Lr = GetIP(startContext);
// Pass the context for the callback as the first argument.
startContext->R0 = (DWORD)callbackCtx;
#else
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(
COR_E_FAILFAST,
W("Managed exception propagation not supported for platform."));
#endif
// The last thing to do is set the supplied callback function.
SetIP(startContext, (PCODE)callback);
}
//---------------------------------------------------------------------------------------
//
// Function to update the current context for exception propagation.
//
// Arguments:
// exception - the PAL_SEHException representing the propagating exception.
// currentContext - the current context to update.
//
static VOID UpdateContextForPropagationCallback(
PAL_SEHException& ex,
CONTEXT* startContext)
{
UpdateContextForPropagationCallback(ex.ManagedToNativeExceptionCallback, ex.ManagedToNativeExceptionCallbackContext, startContext);
}
extern void* g_hostingApiReturnAddress;
VOID DECLSPEC_NORETURN DispatchManagedException(PAL_SEHException& ex, bool isHardwareException)
{
if (!isHardwareException)
{
RtlCaptureContext(ex.GetContextRecord());
}
GCX_COOP();
OBJECTREF throwable = ExInfo::CreateThrowable(ex.GetExceptionRecord(), FALSE);
DispatchManagedException(throwable, ex.GetContextRecord());
}
#if defined(TARGET_AMD64) || defined(TARGET_X86)
/*++
Function :
GetRegisterAddressByIndex
Get address of a register in a context
Parameters:
PCONTEXT pContext : context containing the registers
UINT index : index of the register (Rax=0 .. R15=15)
Return value :
Pointer to the context member represetting the register
--*/
VOID* GetRegisterAddressByIndex(PCONTEXT pContext, UINT index)
{
return getRegAddr(index, pContext);
}
/*++
Function :
GetRegisterValueByIndex
Get value of a register in a context
Parameters:
PCONTEXT pContext : context containing the registers
UINT index : index of the register (Rax=0 .. R15=15)
Return value :
Value of the context member represetting the register
--*/
DWORD64 GetRegisterValueByIndex(PCONTEXT pContext, UINT index)
{