forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheepolicy.cpp
More file actions
930 lines (788 loc) · 35.4 KB
/
eepolicy.cpp
File metadata and controls
930 lines (788 loc) · 35.4 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ---------------------------------------------------------------------------
// EEPolicy.cpp
// ---------------------------------------------------------------------------
#include "common.h"
#include "eepolicy.h"
#include "corhost.h"
#include "dbginterface.h"
#include "eventreporter.h"
#include "finalizerthread.h"
#include "threadsuspend.h"
#include "typestring.h"
#ifndef TARGET_UNIX
#include "dwreport.h"
#endif // !TARGET_UNIX
#include "eventtrace.h"
#undef ExitProcess
void SafeExitProcess(UINT exitCode, ShutdownCompleteAction sca = SCA_ExitProcessWhenShutdownComplete)
{
STRESS_LOG2(LF_SYNC, LL_INFO10, "SafeExitProcess: exitCode = %d sca = %d\n", exitCode, sca);
CONTRACTL
{
DISABLED(GC_TRIGGERS);
NOTHROW;
}
CONTRACTL_END;
// The runtime must be in the appropriate thread mode when we exit, so that we
// aren't surprised by the thread mode when our DLL_PROCESS_DETACH occurs, or when
// other DLLs call Release() on us in their detach [dangerous!], etc.
GCX_PREEMP_NO_DTOR();
// Note that for free and retail builds StressLog must also be enabled
if (g_pConfig && g_pConfig->StressLog())
{
if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_BreakOnBadExit))
{
unsigned goodExit = CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_SuccessExit);
if (exitCode != goodExit)
{
_ASSERTE(!"Bad Exit value");
FAULT_NOT_FATAL(); // if we OOM we can simply give up
minipal_log_print_error("Error 0x%08x.\n\nBreakOnBadExit: returning bad exit code.", exitCode);
DebugBreak();
}
}
}
if (sca == SCA_TerminateProcessWhenShutdownComplete)
{
// disabled because if we fault in this code path we will trigger our Watson code
CONTRACT_VIOLATION(ThrowsViolation);
CrashDumpAndTerminateProcess(exitCode);
}
else if (sca == SCA_ExitProcessWhenShutdownComplete)
{
// disabled because if we fault in this code path we will trigger our Watson code
CONTRACT_VIOLATION(ThrowsViolation);
ExitProcess(exitCode);
}
}
//---------------------------------------------------------------------------------------
// HandleExitProcessHelper is used to shutdown the runtime as specified by the given
// action, then to exit the process. Note, however, that the process will not exit if
// sca is SCA_ReturnWhenShutdownComplete. In that case, this method will simply return after
// performing the shutdown actions.
//---------------------------------------------------------------------------------------
// If g_fFastExitProcess is 0, normal shutdown
// If g_fFastExitProcess is 1, fast shutdown. Only doing log.
// If g_fFastExitProcess is 2, do not run EEShutDown.
DWORD g_fFastExitProcess = 0;
extern void STDMETHODCALLTYPE EEShutDown(BOOL fIsDllUnloading);
//---------------------------------------------------------------------------------------
//
// EEPolicy::HandleStackOverflow - Handle stack overflow according to policy
//
// Return Value:
// None.
//
// How is stack overflow handled?
// If stack overflows, we terminate the process.
void EEPolicy::HandleStackOverflow()
{
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleStackOverflow\n");
Thread *pThread = GetThreadNULLOk();
if (pThread == NULL)
{
// For security reason, it is not safe to continue execution if stack overflow happens
return;
}
EXCEPTION_POINTERS exceptionInfo;
GetCurrentExceptionPointers(&exceptionInfo DEBUG_ARG(!pThread->IsExecutingOnAltStack()));
_ASSERTE(exceptionInfo.ExceptionRecord);
EEPolicy::HandleFatalStackOverflow(&exceptionInfo);
}
// We provide WatsonLastChance with a SO exception record. The ExceptionAddress is set to 0
// here. This ExceptionPointers struct is handed off to the debugger as is. A copy of this struct
// is made before invoking Watson and the ExceptionAddress is set by inspecting the stack. Note
// that the ExceptionContext member is unused and so it's ok to set it to NULL.
static EXCEPTION_RECORD g_SOExceptionRecord = {
STATUS_STACK_OVERFLOW, // ExceptionCode
0, // ExceptionFlags
NULL, // ExceptionRecord
0, // ExceptionAddress
0, // NumberOfParameters
{} }; // ExceptionInformation
EXCEPTION_POINTERS g_SOExceptionPointers = {&g_SOExceptionRecord, NULL};
//---------------------------------------------------------------------------------------
// HandleExitProcess is used to shutdown the runtime, based on policy previously set,
// then to exit the process. Note, however, that the process will not exit if
// sca is SCA_ReturnWhenShutdownComplete. In that case, this method will simply return after
// performing the shutdown actions.
//---------------------------------------------------------------------------------------
void EEPolicy::HandleExitProcess(ShutdownCompleteAction sca)
{
WRAPPER_NO_CONTRACT;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleExitProcess\n");
if (g_fEEStarted)
{
EEShutDown(FALSE);
}
SafeExitProcess(GetLatchedExitCode(), sca);
}
//---------------------------------------------------------------------------------------
// This class is responsible for displaying a stack trace. It uses a condensed way for
// stack overflow stack traces where there are possibly many repeated frames.
// It displays a count and a repeated sequence of frames at the top of the stack in
// such a case, instead of displaying possibly thousands of lines with the same
// method.
//---------------------------------------------------------------------------------------
class CallStackLogger
{
PEXCEPTION_POINTERS m_pExceptionInfo;
// MethodDescs of the stack frames, the TOS is at index 0
CDynArray<MethodDesc*> m_frames;
StackWalkAction LogCallstackForLogCallbackWorker(CrawlFrame *pCF)
{
WRAPPER_NO_CONTRACT;
if (m_pExceptionInfo != NULL)
{
// Skip managed frames that are not part of the stack that caused the exception
// (they are part of the stack that is unwinding the exception)
if (GetRegdisplaySP(pCF->GetRegisterSet()) < GetSP(m_pExceptionInfo->ContextRecord))
{
return SWA_CONTINUE;
}
}
MethodDesc* pMD = pCF->GetFunction();
// Skip Environment.CallEntryPoint so it doesn't appear in
// unhandled exception experiences.
if (pMD != nullptr && pMD == g_pEnvironmentCallEntryPointMethodDesc)
{
return SWA_CONTINUE;
}
MethodDesc** itemPtr = m_frames.Append();
if (itemPtr == nullptr)
{
// Memory allocation failure
return SWA_ABORT;
}
*itemPtr = pMD;
return SWA_CONTINUE;
}
void PrintFrame(int index, const WCHAR* pWordAt)
{
WRAPPER_NO_CONTRACT;
SString str(pWordAt);
MethodDesc* pMD = m_frames[index];
TypeString::AppendMethodInternal(str, pMD, TypeString::FormatNamespace|TypeString::FormatFullInst|TypeString::FormatSignature);
str.Append(W("\n"));
PrintToStdErrW(str.GetUnicode());
}
public:
CallStackLogger(PEXCEPTION_POINTERS pExceptionInfo)
{
WRAPPER_NO_CONTRACT;
m_pExceptionInfo = pExceptionInfo;
}
// Callback called by the stack walker for each frame on the stack
static StackWalkAction LogCallstackForLogCallback(CrawlFrame *pCF, VOID* pData)
{
WRAPPER_NO_CONTRACT;
CallStackLogger* logger = (CallStackLogger*)pData;
return logger->LogCallstackForLogCallbackWorker(pCF);
}
void PrintStackTrace(const WCHAR* pWordAt)
{
WRAPPER_NO_CONTRACT;
// Length of the largest found repeated sequence of frames
int largestCommonLength = 0;
// Number of repetitions of the largest repeated sequence of frames
int largestCommonRepeat = 0;
// NOTE: the algorithm below is O(n^2) but we limit the depth of the search for
// the start of the repetition to a maximum of 1000 frames.
// Even on macOS M1 where the minimal stack frames are smaller than on Intel
// and the default stack size is larger than on Windows and stack overflow in
// a tight loop produces a stack trace with ~350000 frames, the search in case
// we would not find any repetitions at all would take around 130ms.
const int MaxRepetitionStartOffsetSearch = 1000;
int repetitionSearchLimit = min(m_frames.Count(), MaxRepetitionStartOffsetSearch);
// Start index of the repetition
int largestCommonStartOffset;
for (largestCommonStartOffset = 0; largestCommonStartOffset < repetitionSearchLimit; largestCommonStartOffset++)
{
// Index of a stack frame where a possible repetition of frames starts
int commonStartIndex = -1;
largestCommonLength = 0;
largestCommonRepeat = 0;
for (int i = largestCommonStartOffset; i < m_frames.Count(); i++)
{
MethodDesc* pMD = m_frames[i];
if (commonStartIndex != -1)
{
// Some common frames were already found
int commonLength = commonStartIndex - largestCommonStartOffset;
if (m_frames[i - commonLength] != pMD)
{
// The frame being added is not part of the repeated sequence
int commonRepeat = (i - largestCommonStartOffset) / commonLength;
if (commonRepeat >= 2)
{
// A sequence repeated at least twice was found. It is the largest one that was found so far
largestCommonLength = commonLength;
largestCommonRepeat = commonRepeat;
}
commonStartIndex = -1;
}
}
if (commonStartIndex == -1)
{
if ((i != largestCommonStartOffset) && (pMD == m_frames[largestCommonStartOffset]))
{
// We have found a frame with the same MethodDesc as the frame at the start of the repetition search (index largestCommonStartOffset),
// possibly a new repeated sequence is starting.
commonStartIndex = i;
}
}
}
if (largestCommonRepeat != 0)
{
// A repeated sequence of frames was identified
break;
}
}
// Skip special formatting if it would make the output more verbose (add more lines)
if (largestCommonRepeat * largestCommonLength < 4)
{
largestCommonLength = 0;
}
for (int i = 0; i < largestCommonStartOffset; i++)
{
PrintFrame(i, pWordAt);
}
if (largestCommonLength != 0)
{
SmallStackSString repeatStr;
repeatStr.AppendPrintf("Repeated %d times:\n", largestCommonRepeat);
PrintToStdErrW(repeatStr.GetUnicode());
PrintToStdErrA("--------------------------------\n");
for (int i = largestCommonStartOffset; i < largestCommonStartOffset + largestCommonLength; i++)
{
PrintFrame(i, pWordAt);
}
PrintToStdErrA("--------------------------------\n");
}
for (int i = largestCommonLength * largestCommonRepeat + largestCommonStartOffset; i < m_frames.Count(); i++)
{
PrintFrame(i, pWordAt);
}
}
};
#ifdef _DEBUG
// Temporarilly added flag to enable extra verbose printing of progress of stack overflow handling
// to catch a bug that is not reproducible locally.
static bool g_LogStackOverflowExit = false;
#endif // _DEBUG
//---------------------------------------------------------------------------------------
//
// A worker to save managed stack trace.
//
// Arguments:
// None
//
// Return Value:
// None
//
inline void LogCallstackForLogWorker(Thread* pThread, PEXCEPTION_POINTERS pExceptionInfo)
{
WRAPPER_NO_CONTRACT;
SmallStackSString WordAt;
if (!WordAt.LoadResource(IDS_ER_WORDAT))
{
WordAt.Set(W(" at"));
}
else
{
WordAt.Insert(WordAt.Begin(), W(" "));
}
WordAt.Append(W(" "));
CallStackLogger logger(pExceptionInfo);
pThread->StackWalkFrames(&CallStackLogger::LogCallstackForLogCallback, &logger, QUICKUNWIND | FUNCTIONSONLY | ALLOW_ASYNC_STACK_WALK);
logger.PrintStackTrace(WordAt.GetUnicode());
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Exiting stack trace printing thread.\n");
#endif
}
//---------------------------------------------------------------------------------------
//
// Print information on fatal error to stderr.
//
// Arguments:
// exitCode - code of the fatal error
// pszMessage - error message (can be NULL)
// errorSource - details on the source of the error (can be NULL)
// argExceptionString - exception details (can be NULL)
//
// Return Value:
// None
//
void LogInfoForFatalError(UINT exitCode, LPCWSTR pszMessage, PEXCEPTION_POINTERS pExceptionInfo, LPCWSTR errorSource, LPCWSTR argExceptionString)
{
WRAPPER_NO_CONTRACT;
static size_t s_pCrashingThreadID;
size_t currentThreadID;
#ifndef TARGET_UNIX
currentThreadID = GetCurrentThreadId();
#else
currentThreadID = PAL_GetCurrentOSThreadId();
#endif
size_t previousThreadID = InterlockedCompareExchangeT<size_t>(&s_pCrashingThreadID, currentThreadID, 0);
// Let the first crashing thread take care of the reporting.
if (previousThreadID != 0)
{
if (previousThreadID == currentThreadID)
{
PrintToStdErrA("Fatal error while logging another fatal error.\n");
}
else
{
// Switch to preemptive mode to avoid blocking the crashing thread. It may try to suspend the runtime
// for GC during the stacktrace reporting.
GCX_PREEMP();
ClrSleepEx(INFINITE, /*bAlertable*/ FALSE);
}
return;
}
EX_TRY
{
if (exitCode == (UINT)COR_E_FAILFAST)
{
PrintToStdErrA("Process terminated.\n");
}
else
{
PrintToStdErrA("Fatal error.\n");
}
if (errorSource != NULL)
{
PrintToStdErrW(errorSource);
PrintToStdErrA("\n");
}
if (pszMessage != NULL)
{
PrintToStdErrW(pszMessage);
}
else
{
// If no message was passed in, generate it from the exitCode
InlineSString<256> exitCodeMessage;
GetHRMsg(exitCode, exitCodeMessage);
PrintToStdErrW(exitCodeMessage.GetUnicode());
}
PrintToStdErrA("\n");
Thread* pThread = GetThreadNULLOk();
if (pThread && errorSource == NULL)
{
LogCallstackForLogWorker(pThread, pExceptionInfo);
if (argExceptionString != NULL) {
PrintToStdErrW(argExceptionString);
}
}
}
EX_CATCH
{
}
EX_END_CATCH
}
//This starts FALSE and then converts to true if HandleFatalError has ever been called by a GC thread
BOOL g_fFatalErrorOccurredOnGCThread = FALSE;
//
// Log an error to the event log if possible, then throw up a dialog box.
//
void EEPolicy::LogFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage, PEXCEPTION_POINTERS pExceptionInfo, LPCWSTR errorSource, LPCWSTR argExceptionString)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_ANY;
_ASSERTE(pExceptionInfo != NULL);
// Log exception to StdErr
LogInfoForFatalError(exitCode, pszMessage, pExceptionInfo, errorSource, argExceptionString);
if(ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context, FailFast))
{
// Fire an ETW FailFast event
FireEtwFailFast(pszMessage,
(const PVOID)address,
pExceptionInfo->ExceptionRecord ? pExceptionInfo->ExceptionRecord->ExceptionCode : 0,
exitCode,
GetClrInstanceId());
}
#ifndef TARGET_UNIX
// Write an event log entry. We do allocate some resources here (spread between the stack and maybe the heap for longer
// messages), so it's possible for the event write to fail. If needs be we can use a more elaborate scheme here in the future
// (maybe trying multiple approaches and backing off on failure, falling back on a limited size static buffer as a last
// resort). In all likelihood the Win32 event reporting mechanism requires resources though, so it's not clear how much
// effort we should put into this without knowing the benefit we'd receive.
EX_TRY
{
if (ShouldLogInEventLog())
{
// If the exit code is COR_E_FAILFAST then the fatal error was raised by managed code and the address argument points to a
// unicode message buffer rather than a faulting EIP.
EventReporter::EventReporterType failureType = EventReporter::ERT_UnmanagedFailFast;
if (exitCode == (UINT)COR_E_FAILFAST)
failureType = EventReporter::ERT_ManagedFailFast;
else if (exitCode == (UINT)COR_E_CODECONTRACTFAILED)
failureType = EventReporter::ERT_CodeContractFailed;
else if (exitCode == EXCEPTION_ACCESS_VIOLATION)
failureType = EventReporter::ERT_UnhandledException;
EventReporter reporter(failureType);
StackSString s(argExceptionString);
if ((exitCode == (UINT)COR_E_FAILFAST) || (exitCode == (UINT)COR_E_CODECONTRACTFAILED) || (exitCode == (UINT)CLR_E_GC_OOM) || (exitCode == EXCEPTION_ACCESS_VIOLATION))
{
if (pszMessage)
{
reporter.AddDescription((WCHAR*)pszMessage);
}
if (argExceptionString)
{
reporter.AddFailFastStackTrace(s);
}
if (exitCode != (UINT)CLR_E_GC_OOM)
LogCallstackForEventReporter(reporter);
}
else
{
WCHAR addressString[MaxIntegerDecHexString + 1];
FormatInteger(addressString, ARRAY_SIZE(addressString), "%p", (SIZE_T)pExceptionInfo->ExceptionRecord->ExceptionAddress);
// We should always have the reference to the runtime's instance
_ASSERTE(GetClrModuleBase() != NULL);
// Setup the string to contain the runtime's base address. Thus, when customers report FEEE with just
// the event log entry containing this string, we can use the absolute and base addresses to determine
// where the fault happened inside the runtime.
WCHAR runtimeBaseAddressString[MaxIntegerDecHexString + 1];
FormatInteger(runtimeBaseAddressString, ARRAY_SIZE(runtimeBaseAddressString), "%p", (SIZE_T)GetClrModuleBase());
WCHAR exitCodeString[MaxIntegerDecHexString + 1];
FormatInteger(exitCodeString, ARRAY_SIZE(exitCodeString), "%x", exitCode);
// Format the string
InlineSString<80> ssMessage;
ssMessage.FormatMessage(FORMAT_MESSAGE_FROM_STRING, W("at IP 0x%1 (0x%2) with exit code 0x%3."), 0, 0,
SString{ SString::Literal, addressString },
SString{ SString::Literal, runtimeBaseAddressString },
SString{ SString::Literal, exitCodeString });
reporter.AddDescription(ssMessage);
}
reporter.Report();
}
}
EX_CATCH
{
}
EX_END_CATCH
#endif // !TARGET_UNIX
#ifdef _DEBUG
// If we're native-only (Win32) debugging this process, we'd love to break now.
// However, we should not do this because a managed debugger attached to a
// SxS runtime also appears to be a native debugger. Unfortunately, the managed
// debugger won't handle any native event from another runtime, which means this
// breakpoint would go unhandled and terminate the process. Instead, we will let
// the process continue so at least the fatal error is logged rather than abrupt
// termination.
//
// This behavior can still be overridden if the right config value is set.
if (minipal_is_native_debugger_present())
{
bool fBreak = (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgOOBinFEEE) != 0);
if (fBreak)
{
DebugBreak();
}
}
#endif // _DEBUG
{
#ifdef DEBUGGING_SUPPORTED
//Give a managed debugger a chance if this fatal error is on a managed thread.
Thread *pThread = GetThreadNULLOk();
if (pThread && !g_fFatalErrorOccurredOnGCThread)
{
GCX_COOP();
OBJECTHANDLE ohException = NULL;
if (exitCode == (UINT)COR_E_STACKOVERFLOW)
{
// If we're going down because of stack overflow, go ahead and use the preallocated SO exception.
ohException = CLRException::GetPreallocatedStackOverflowExceptionHandle();
}
else
{
// Though we would like to remove the usage of ExecutionEngineException in any manner,
// we cannot. Its okay to use it in the case below since the process is terminating
// and this will serve as an exception object for debugger.
ohException = g_pPreallocatedExecutionEngineException;
}
// Preallocated exception handles can be null if FailFast is invoked before LoadBaseSystemClasses
// (in SystemDomain::Init) finished. See Dev10 Bug 677432 for the detail.
if (ohException != NULL)
{
// for fail-fast, if there's a LTO available then use that as the inner exception object
// for the FEEE we'll be reporting. this can help the Watson back-end to generate better
// buckets for apps that call Environment.FailFast() and supply an exception object.
OBJECTREF lto = pThread->LastThrownObject();
if (exitCode == static_cast<UINT>(COR_E_FAILFAST) && lto != NULL)
{
EXCEPTIONREF curEx = (EXCEPTIONREF)ObjectFromHandle(ohException);
curEx->SetInnerException(lto);
}
pThread->SetLastThrownObject(ObjectFromHandle(ohException), TRUE);
}
// If a managed debugger is already attached, and if that debugger is thinking it might be inclined to
// try to intercept this excepiton, then tell it that's not possible.
if (pThread->IsExceptionInProgress())
{
pThread->GetExceptionState()->GetFlags()->SetDebuggerInterceptNotPossible();
}
}
if (EXCEPTION_CONTINUE_EXECUTION == WatsonLastChance(pThread, pExceptionInfo, TypeOfReportedError::FatalError))
{
LOG((LF_EH, LL_INFO100, "EEPolicy::LogFatalError: debugger ==> EXCEPTION_CONTINUE_EXECUTION\n"));
_ASSERTE(!"Debugger should not have returned ContinueExecution");
}
#endif // DEBUGGING_SUPPORTED
}
}
void DisplayStackOverflowException()
{
LIMITED_METHOD_CONTRACT;
PrintToStdErrA("Stack overflow.\n");
}
DWORD LogStackOverflowStackTraceThread(void* arg)
{
LogCallstackForLogWorker((Thread*)arg, NULL);
return 0;
}
void DECLSPEC_NORETURN EEPolicy::HandleFatalStackOverflow(EXCEPTION_POINTERS *pExceptionInfo, BOOL fSkipDebugger)
{
// This is fatal error. We do not care about SO mode any more.
// All of the code from here on out is robust to any failures in any API's that are called.
CONTRACT_VIOLATION(GCViolation | ModeViolation | FaultNotFatal | TakesLockViolation);
WRAPPER_NO_CONTRACT;
_ASSERTE(pExceptionInfo != NULL);
// Disable GC stress triggering GC at this point, we don't want the GC to start running
// on this thread when we have only a very limited space left on the stack
GCStressPolicy::InhibitHolder iholder;
STRESS_LOG0(LF_EH, LL_INFO100, "In EEPolicy::HandleFatalStackOverflow\n");
FaultingExceptionFrame fef;
if (pExceptionInfo->ContextRecord)
{
GCX_COOP();
CONTEXT *pExceptionContext = pExceptionInfo->ContextRecord;
#if defined(TARGET_X86) && defined(TARGET_WINDOWS)
// For Windows x86, we don't have a reliable method to unwind to the first managed call frame,
// so we handle at least the cases when the stack overflow happens in JIT helpers
AdjustContextForJITHelpers(pExceptionInfo->ExceptionRecord, pExceptionInfo->ContextRecord);
#else
// There are three possible kinds of locations where the stack overflow can happen:
// 1. In managed code
// 2. In native code with no explicit frame above the topmost managed frame
// 3. In native code with a explicit frame(s) above the topmost managed frame
// The FaultingExceptionFrame's context needs to point to the topmost managed code frame except for the case 3.
// In that case, it needs to point to the actual frame where the stack overflow happened, otherwise the stack
// walker would skip the explicit frame(s) and misbehave.
Thread *pThread = GetThreadNULLOk();
if (pThread)
{
// Use the context in the FaultingExceptionFrame as a temporary store for unwinding to the first managed frame
CopyOSContext((&fef)->GetExceptionContext(), pExceptionInfo->ContextRecord);
Thread::VirtualUnwindToFirstManagedCallFrame((&fef)->GetExceptionContext());
if (GetSP((&fef)->GetExceptionContext()) > (TADDR)pThread->GetFrame())
{
// If the unwind has crossed any explicit frame, use the original exception context.
pExceptionContext = pExceptionInfo->ContextRecord;
}
else
{
// Otherwise use the first managed frame context.
pExceptionContext = (&fef)->GetExceptionContext();
}
}
#endif
fef.InitAndLink(pExceptionContext);
}
static volatile LONG g_stackOverflowCallStackLogged = 0;
// Dump stack trace only for the first thread failing with stack overflow to prevent mixing
// multiple stack traces together.
if (InterlockedCompareExchange(&g_stackOverflowCallStackLogged, 1, 0) == 0)
{
#ifdef _DEBUG
g_LogStackOverflowExit = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_LogStackOverflowExit) != 0;
#endif
DisplayStackOverflowException();
HandleHolder stackDumpThreadHandle = Thread::CreateUtilityThread(Thread::StackSize_Small, LogStackOverflowStackTraceThread, GetThreadNULLOk(), W(".NET SO Tracer"));
if (stackDumpThreadHandle != INVALID_HANDLE_VALUE)
{
// Wait for the stack trace logging completion
DWORD res = WaitForSingleObject(stackDumpThreadHandle, INFINITE);
_ASSERTE(res == WAIT_OBJECT_0);
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Stack trace printing helper thread exited.\n");
#endif
}
g_stackOverflowCallStackLogged = 2;
}
else
{
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Waiting for thread that's logging stack overflow.\n");
#endif
// Wait for the thread that is logging the stack trace to complete
while (g_stackOverflowCallStackLogged != 2)
{
Sleep(50);
}
}
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Proceeding with exit.\n");
#endif
if(ETW_EVENT_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PRIVATE_PROVIDER_DOTNET_Context, FailFast))
{
// Fire an ETW FailFast event
FireEtwFailFast(W("StackOverflowException"),
(const PVOID)(pExceptionInfo->ContextRecord ? GetIP(pExceptionInfo->ContextRecord) : 0),
pExceptionInfo->ExceptionRecord ? pExceptionInfo->ExceptionRecord->ExceptionCode : 0,
COR_E_STACKOVERFLOW,
GetClrInstanceId());
}
if (!fSkipDebugger)
{
Thread *pThread = GetThreadNULLOk();
BOOL fTreatAsNativeUnhandledException = FALSE;
if (pThread)
{
GCX_COOP();
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Setting throwable.\n");
#endif
// If we had a SO before preallocated exception objects are initialized, we will AV here. This can happen
// during the initialization of SystemDomain during EEStartup. Thus, setup the SO throwable only if its not
// NULL.
//
// When WatsonLastChance (WLC) is invoked below, it treats this case as UnhandledException. If there is no
// managed exception object available, we should treat this case as NativeUnhandledException. This aligns
// well with the fact that there cannot be a managed debugger attached at this point that will require
// LastChanceManagedException notification to be delivered. Also, this is the same as how
// we treat an unhandled exception as NativeUnhandled when throwable is not available.
OBJECTHANDLE ohSO = CLRException::GetPreallocatedStackOverflowExceptionHandle();
if (ohSO != NULL)
{
pThread->SafeSetThrowables(ObjectFromHandle(ohSO)
DEBUG_ARG(ThreadExceptionState::STEC_CurrentTrackerEqualNullOkHackForFatalStackOverflow),
TRUE);
}
else
{
// We dont have a throwable - treat this as native unhandled exception
fTreatAsNativeUnhandledException = TRUE;
}
}
#ifndef TARGET_UNIX
if (IsWatsonEnabled() && (g_pDebugInterface != NULL))
{
ResetWatsonBucketsParams param;
param.m_pThread = pThread;
param.pExceptionRecord = pExceptionInfo->ExceptionRecord;
g_pDebugInterface->RequestFavor(ResetWatsonBucketsFavorWorker, reinterpret_cast<void *>(¶m));
}
#endif // !TARGET_UNIX
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Calling WatsonLastChance.\n");
#endif
WatsonLastChance(pThread, pExceptionInfo,
(fTreatAsNativeUnhandledException == FALSE)? TypeOfReportedError::UnhandledException: TypeOfReportedError::NativeThreadUnhandledException);
}
#ifdef _DEBUG
if (g_LogStackOverflowExit)
PrintToStdErrA("@Terminating the process.\n");
#endif
CrashDumpAndTerminateProcess(COR_E_STACKOVERFLOW);
UNREACHABLE();
}
#if defined(TARGET_X86) && defined(TARGET_WINDOWS)
// This noinline method is required to ensure that RtlCaptureContext captures
// the context of HandleFatalError. On x86 RtlCaptureContext will not capture
// the current method's context
// NOTE: explicitly turning off optimizations to force the compiler to spill to the
// stack and establish a stack frame. This is required to ensure that
// RtlCaptureContext captures the context of HandleFatalError
#pragma optimize("", off)
int NOINLINE WrapperClrCaptureContext(CONTEXT* context)
{
ClrCaptureContext(context);
return 0;
}
#pragma optimize("", on)
#endif // defined(TARGET_X86) && defined(TARGET_WINDOWS)
// This method must return a value to avoid getting non-actionable dumps on x86.
// If this method were a DECLSPEC_NORETURN then dumps would not provide the necessary
// context at the point of the failure
int NOINLINE EEPolicy::HandleFatalError(UINT exitCode, UINT_PTR address, LPCWSTR pszMessage /* = NULL */, PEXCEPTION_POINTERS pExceptionInfo /* = NULL */, LPCWSTR errorSource /* = NULL */, LPCWSTR argExceptionString /* = NULL */)
{
WRAPPER_NO_CONTRACT;
// All of the code from here on out is robust to any failures in any API's that are called.
FAULT_NOT_FATAL();
EXCEPTION_RECORD exceptionRecord;
EXCEPTION_POINTERS exceptionPointers;
CONTEXT context;
if (pExceptionInfo == NULL)
{
ZeroMemory(&exceptionPointers, sizeof(exceptionPointers));
ZeroMemory(&exceptionRecord, sizeof(exceptionRecord));
ZeroMemory(&context, sizeof(context));
context.ContextFlags = CONTEXT_CONTROL;
#if defined(TARGET_X86) && defined(TARGET_WINDOWS)
// Add a frame to ensure that the context captured is this method and not the caller
WrapperClrCaptureContext(&context);
#else // defined(TARGET_X86) && defined(TARGET_WINDOWS)
ClrCaptureContext(&context);
#endif
exceptionRecord.ExceptionCode = exitCode;
exceptionRecord.ExceptionAddress = reinterpret_cast< PVOID >(address);
exceptionPointers.ExceptionRecord = &exceptionRecord;
exceptionPointers.ContextRecord = &context;
pExceptionInfo = &exceptionPointers;
}
// All of the code from here on out is allowed to trigger a GC, even if we're in a no-trigger region. We're
// ripping the process down due to a fatal error... our invariants are already gone.
{
// This is fatal error. We do not care about SO mode any more.
// All of the code from here on out is robust to any failures in any API's that are called.
CONTRACT_VIOLATION(GCViolation | ModeViolation | FaultNotFatal | TakesLockViolation);
// Setting g_fFatalErrorOccurredOnGCThread allows code to avoid attempting to make GC mode transitions which could
// block indefinitely if the fatal error occurred during the GC.
if (IsGCSpecialThread() && GCHeapUtilities::IsGCInProgress())
{
g_fFatalErrorOccurredOnGCThread = TRUE;
}
// ThreadStore lock needs to be released before continuing with the FatalError handling should
// because debugger is going to take CrstDebuggerMutex, whose lock level is higher than that of
// CrstThreadStore. It should be safe to release the lock since execution will not be resumed
// after fatal errors.
if (ThreadStore::HoldingThreadStore(GetThreadNULLOk()))
{
ThreadSuspend::UnlockThreadStore();
}
g_fFastExitProcess = 2;
STRESS_LOG0(LF_CORDB,LL_INFO100, "D::HFE: About to call LogFatalError\n");
LogFatalError(exitCode, address, pszMessage, pExceptionInfo, errorSource, argExceptionString);
SafeExitProcess(exitCode, SCA_TerminateProcessWhenShutdownComplete);
}
UNREACHABLE();
return -1;
}
#ifdef HOST_ANDROID
// Logs the managed callstack when a signal is received.
void EEPolicy::LogManagedCallstackForSignal(LPCWSTR signalName)
{
WRAPPER_NO_CONTRACT;
InlineSString<256> message;
message.Append(W("Got a "));
message.Append(signalName);
message.Append(W(" while executing native code. This usually indicates\n")
W("a fatal error in the runtime or one of the native libraries\n")
W("used by your application."));
LogInfoForFatalError(0, message.GetUnicode(), nullptr, nullptr, nullptr);
}
#endif // HOST_ANDROID