This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
excep.cpp
13136 lines (11220 loc) · 474 KB
/
excep.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
/* EXCEP.CPP:
*
*/
#include "common.h"
#include "frames.h"
#include "threads.h"
#include "excep.h"
#include "object.h"
#include "field.h"
#include "dbginterface.h"
#include "cgensys.h"
#include "comutilnative.h"
#include "siginfo.hpp"
#include "gcheaputilities.h"
#include "eedbginterfaceimpl.h" //so we can clearexception in RealCOMPlusThrow
#include "dllimportcallback.h"
#include "stackwalk.h" //for CrawlFrame, in SetIPFromSrcToDst
#include "shimload.h"
#include "eeconfig.h"
#include "virtualcallstub.h"
#include "typestring.h"
#ifndef FEATURE_PAL
#include "dwreport.h"
#endif // !FEATURE_PAL
#include "eventreporter.h"
#ifdef FEATURE_COMINTEROP
#include<roerrorapi.h>
#endif
#ifdef FEATURE_EH_FUNCLETS
#include "exceptionhandling.h"
#endif
#include <errorrep.h>
#ifndef FEATURE_PAL
// Include definition of GenericModeBlock
#include <msodw.h>
#endif // FEATURE_PAL
// Support for extracting MethodDesc of a delegate.
#include "comdelegate.h"
#ifdef HAVE_GCCOVER
#include "gccover.h"
#endif // HAVE_GCCOVER
#ifndef FEATURE_PAL
// Windows uses 64kB as the null-reference area
#define NULL_AREA_SIZE (64 * 1024)
#else // !FEATURE_PAL
#define NULL_AREA_SIZE GetOsPageSize()
#endif // !FEATURE_PAL
#ifndef CROSSGEN_COMPILE
BOOL IsIPInEE(void *ip);
//----------------------------------------------------------------------------
//
// IsExceptionFromManagedCode - determine if pExceptionRecord points to a managed exception
//
// Arguments:
// pExceptionRecord - pointer to exception record
//
// Return Value:
// TRUE or FALSE
//
//----------------------------------------------------------------------------
BOOL IsExceptionFromManagedCode(const EXCEPTION_RECORD * pExceptionRecord)
{
CONTRACTL {
NOTHROW;
GC_NOTRIGGER;
SUPPORTS_DAC;
PRECONDITION(CheckPointer(pExceptionRecord));
} CONTRACTL_END;
if (pExceptionRecord == NULL)
{
return FALSE;
}
DACCOP_IGNORE(FieldAccess, "EXCEPTION_RECORD is a OS structure, and ExceptionAddress is actually a target address here.");
UINT_PTR address = reinterpret_cast<UINT_PTR>(pExceptionRecord->ExceptionAddress);
// An exception code of EXCEPTION_COMPLUS indicates a managed exception
// has occurred (most likely due to executing a "throw" instruction).
//
// Also, a hardware level exception may not have an exception code of
// EXCEPTION_COMPLUS. In this case, an exception address that resides in
// managed code indicates a managed exception has occurred.
return (IsComPlusException(pExceptionRecord) ||
(ExecutionManager::IsManagedCode((PCODE)address)));
}
#ifndef DACCESS_COMPILE
#define SZ_UNHANDLED_EXCEPTION W("Unhandled exception.")
#define SZ_UNHANDLED_EXCEPTION_CHARLEN ((sizeof(SZ_UNHANDLED_EXCEPTION) / sizeof(WCHAR)))
typedef struct {
OBJECTREF pThrowable;
STRINGREF s1;
OBJECTREF pTmpThrowable;
} ProtectArgsStruct;
PEXCEPTION_REGISTRATION_RECORD GetCurrentSEHRecord();
BOOL IsUnmanagedToManagedSEHHandler(EXCEPTION_REGISTRATION_RECORD*);
VOID DECLSPEC_NORETURN RealCOMPlusThrow(OBJECTREF throwable, BOOL rethrow
#ifdef FEATURE_CORRUPTING_EXCEPTIONS
, CorruptionSeverity severity = NotCorrupting
#endif // FEATURE_CORRUPTING_EXCEPTIONS
);
//-------------------------------------------------------------------------------
// Basically, this asks whether the exception is a managed exception thrown by
// this instance of the CLR.
//
// The way the result is used, however, is to decide whether this instance is the
// one to throw up the Watson box.
//-------------------------------------------------------------------------------
BOOL ShouldOurUEFDisplayUI(PEXCEPTION_POINTERS pExceptionInfo)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
// Test first for the canned SO EXCEPTION_POINTERS structure as it has a NULL context record and will break the code below.
extern EXCEPTION_POINTERS g_SOExceptionPointers;
if (pExceptionInfo == &g_SOExceptionPointers)
{
return TRUE;
}
return IsComPlusException(pExceptionInfo->ExceptionRecord) || ExecutionManager::IsManagedCode(GetIP(pExceptionInfo->ContextRecord));
}
BOOL NotifyAppDomainsOfUnhandledException(
PEXCEPTION_POINTERS pExceptionPointers,
OBJECTREF *pThrowableIn,
BOOL useLastThrownObject,
BOOL isTerminating);
VOID SetManagedUnhandledExceptionBit(
BOOL useLastThrownObject);
//-------------------------------------------------------------------------------
// This simply tests to see if the exception object is a subclass of
// the descriminating class specified in the exception clause.
//-------------------------------------------------------------------------------
BOOL ExceptionIsOfRightType(TypeHandle clauseType, TypeHandle thrownType)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
// if not resolved to, then it wasn't loaded and couldn't have been thrown
if (clauseType.IsNull())
return FALSE;
if (clauseType == thrownType)
return TRUE;
// now look for parent match
TypeHandle superType = thrownType;
while (!superType.IsNull()) {
if (superType == clauseType) {
break;
}
superType = superType.GetParent();
}
return !superType.IsNull();
}
//===========================================================================
// Gets the message text from an exception
//===========================================================================
ULONG GetExceptionMessage(OBJECTREF throwable,
__inout_ecount(bufferLength) LPWSTR buffer,
ULONG bufferLength)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory());
}
CONTRACTL_END;
// Prefast buffer sanity check. Don't call the API with a zero length buffer.
if (bufferLength == 0)
{
_ASSERTE(bufferLength > 0);
return 0;
}
StackSString result;
GetExceptionMessage(throwable, result);
ULONG length = result.GetCount();
LPCWSTR chars = result.GetUnicode();
if (length < bufferLength)
{
wcsncpy_s(buffer, bufferLength, chars, length);
}
else
{
wcsncpy_s(buffer, bufferLength, chars, bufferLength-1);
}
return length;
}
//-----------------------------------------------------------------------------
// Given an object, get the "message" from it. If the object is an Exception
// call Exception.ToString, otherwise, call Object.ToString
//-----------------------------------------------------------------------------
void GetExceptionMessage(OBJECTREF throwable, SString &result)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory());
}
CONTRACTL_END;
STRINGREF pString = GetExceptionMessage(throwable);
// If call returned NULL (not empty), oh well, no message.
if (pString != NULL)
pString->GetSString(result);
} // void GetExceptionMessage()
#if FEATURE_COMINTEROP
// This method returns IRestrictedErrorInfo associated with the ErrorObject.
// It checks whether the given managed exception object has __HasRestrictedLanguageErrorObject set
// in which case it returns the IRestrictedErrorInfo associated with the __RestrictedErrorObject.
IRestrictedErrorInfo* GetRestrictedErrorInfoFromErrorObject(OBJECTREF throwable)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory());
}
CONTRACTL_END;
IRestrictedErrorInfo* pRestrictedErrorInfo = NULL;
// If there is no object, there is no restricted error.
if (throwable == NULL)
return NULL;
_ASSERTE(IsException(throwable->GetMethodTable())); // what is the pathway here?
if (!IsException(throwable->GetMethodTable()))
{
return NULL;
}
struct _gc {
OBJECTREF Throwable;
OBJECTREF RestrictedErrorInfoObjRef;
} gc;
ZeroMemory(&gc, sizeof(gc));
GCPROTECT_BEGIN(gc);
gc.Throwable = throwable;
// Get the MethodDesc on which we'll call.
MethodDescCallSite getRestrictedLanguageErrorObject(METHOD__EXCEPTION__TRY_GET_RESTRICTED_LANGUAGE_ERROR_OBJECT, &gc.Throwable);
// Make the call.
ARG_SLOT Args[] =
{
ObjToArgSlot(gc.Throwable),
PtrToArgSlot(&gc.RestrictedErrorInfoObjRef)
};
BOOL bHasLanguageRestrictedErrorObject = (BOOL)getRestrictedLanguageErrorObject.Call_RetBool(Args);
if(bHasLanguageRestrictedErrorObject)
{
// The __RestrictedErrorObject represents IRestrictedErrorInfo RCW of a non-CLR platform. Lets get the corresponding IRestrictedErrorInfo for it.
pRestrictedErrorInfo = (IRestrictedErrorInfo *)GetComIPFromObjectRef(&gc.RestrictedErrorInfoObjRef, IID_IRestrictedErrorInfo);
}
GCPROTECT_END();
return pRestrictedErrorInfo;
}
#endif
STRINGREF GetExceptionMessage(OBJECTREF throwable)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory());
}
CONTRACTL_END;
// If there is no object, there is no message.
if (throwable == NULL)
return NULL;
// Return value.
STRINGREF pString = NULL;
GCPROTECT_BEGIN(throwable);
// Call Object.ToString(). Note that exceptions do not have to inherit from System.Exception
MethodDescCallSite toString(METHOD__OBJECT__TO_STRING, &throwable);
// Make the call.
ARG_SLOT arg[1] = {ObjToArgSlot(throwable)};
pString = toString.Call_RetSTRINGREF(arg);
GCPROTECT_END();
return pString;
}
HRESULT GetExceptionHResult(OBJECTREF throwable)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
HRESULT hr = E_FAIL;
if (throwable == NULL)
return hr;
// Since any object can be thrown in managed code, not only instances of System.Exception subclasses
// we need to check to see if we are dealing with an exception before attempting to retrieve
// the HRESULT field. If we are not dealing with an exception, then we will simply return E_FAIL.
_ASSERTE(IsException(throwable->GetMethodTable())); // what is the pathway here?
if (IsException(throwable->GetMethodTable()))
{
hr = ((EXCEPTIONREF)throwable)->GetHResult();
}
return hr;
} // HRESULT GetExceptionHResult()
DWORD GetExceptionXCode(OBJECTREF throwable)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_COOPERATIVE;
}
CONTRACTL_END;
HRESULT hr = E_FAIL;
if (throwable == NULL)
return hr;
// Since any object can be thrown in managed code, not only instances of System.Exception subclasses
// we need to check to see if we are dealing with an exception before attempting to retrieve
// the HRESULT field. If we are not dealing with an exception, then we will simply return E_FAIL.
_ASSERTE(IsException(throwable->GetMethodTable())); // what is the pathway here?
if (IsException(throwable->GetMethodTable()))
{
hr = ((EXCEPTIONREF)throwable)->GetXCode();
}
return hr;
} // DWORD GetExceptionXCode()
//------------------------------------------------------------------------------
// This function will extract some information from an Access Violation SEH
// exception, and store it in the System.AccessViolationException object.
// - the faulting instruction's IP.
// - the target address of the faulting instruction.
// - a code indicating attempted read vs write
//------------------------------------------------------------------------------
void SetExceptionAVParameters( // No return.
OBJECTREF throwable, // The object into which to set the values.
EXCEPTION_RECORD *pExceptionRecord) // The SEH exception information.
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(throwable != NULL);
}
CONTRACTL_END;
GCPROTECT_BEGIN(throwable)
{
// This should only be called for AccessViolationException
_ASSERTE(MscorlibBinder::GetException(kAccessViolationException) == throwable->GetMethodTable());
FieldDesc *pFD_ip = MscorlibBinder::GetField(FIELD__ACCESS_VIOLATION_EXCEPTION__IP);
FieldDesc *pFD_target = MscorlibBinder::GetField(FIELD__ACCESS_VIOLATION_EXCEPTION__TARGET);
FieldDesc *pFD_access = MscorlibBinder::GetField(FIELD__ACCESS_VIOLATION_EXCEPTION__ACCESSTYPE);
_ASSERTE(pFD_ip->GetFieldType() == ELEMENT_TYPE_I);
_ASSERTE(pFD_target->GetFieldType() == ELEMENT_TYPE_I);
_ASSERTE(pFD_access->GetFieldType() == ELEMENT_TYPE_I4);
void *ip = pExceptionRecord->ExceptionAddress;
void *target = (void*)(pExceptionRecord->ExceptionInformation[1]);
DWORD access = (DWORD)(pExceptionRecord->ExceptionInformation[0]);
pFD_ip->SetValuePtr(throwable, ip);
pFD_target->SetValuePtr(throwable, target);
pFD_access->SetValue32(throwable, access);
}
GCPROTECT_END();
} // void SetExceptionAVParameters()
//------------------------------------------------------------------------------
// This will call InternalPreserveStackTrace (if the throwable derives from
// System.Exception), to copy the stack trace to the _remoteStackTraceString.
// Doing so allows the stack trace of an exception caught by the runtime, and
// rethrown with COMPlusThrow(OBJECTREF thowable), to be preserved. Otherwise
// the exception handling code may clear the stack trace. (Generally, we see
// the stack trace preserved on win32 and cleared on win64.)
//------------------------------------------------------------------------------
void ExceptionPreserveStackTrace( // No return.
OBJECTREF throwable) // Object about to be thrown.
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
INJECT_FAULT(ThrowOutOfMemory());
}
CONTRACTL_END;
// If there is no object, there is no stack trace to save.
if (throwable == NULL)
return;
GCPROTECT_BEGIN(throwable);
// Make sure it is derived from System.Exception, that it is not one of the
// preallocated exception objects, and that it has a stack trace to save.
if (IsException(throwable->GetMethodTable()) &&
!CLRException::IsPreallocatedExceptionObject(throwable))
{
LOG((LF_EH, LL_INFO1000, "ExceptionPreserveStackTrace called\n"));
// Call Exception.InternalPreserveStackTrace() ...
MethodDescCallSite preserveStackTrace(METHOD__EXCEPTION__INTERNAL_PRESERVE_STACK_TRACE, &throwable);
// Make the call.
ARG_SLOT arg[1] = {ObjToArgSlot(throwable)};
preserveStackTrace.Call(arg);
}
GCPROTECT_END();
} // void ExceptionPreserveStackTrace()
// We have to cache the MethodTable and FieldDesc for wrapped non-compliant exceptions the first
// time we wrap, because we cannot tolerate a GC when it comes time to detect and unwrap one.
static MethodTable *pMT_RuntimeWrappedException;
static FieldDesc *pFD_WrappedException;
// Non-compliant exceptions are immediately wrapped in a RuntimeWrappedException instance. The entire
// exception system can now ignore the possibility of these cases except:
//
// 1) IL_Throw, which must wrap via this API
// 2) Calls to Filters & Catch handlers, which must unwrap based on whether the assembly is on the legacy
// plan.
//
void WrapNonCompliantException(OBJECTREF *ppThrowable)
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(IsProtectedByGCFrame(ppThrowable));
}
CONTRACTL_END;
_ASSERTE(!IsException((*ppThrowable)->GetMethodTable()));
EX_TRY
{
// idempotent operations, so the race condition is okay.
if (pMT_RuntimeWrappedException == NULL)
pMT_RuntimeWrappedException = MscorlibBinder::GetException(kRuntimeWrappedException);
if (pFD_WrappedException == NULL)
pFD_WrappedException = MscorlibBinder::GetField(FIELD__RUNTIME_WRAPPED_EXCEPTION__WRAPPED_EXCEPTION);
OBJECTREF orWrapper = AllocateObject(MscorlibBinder::GetException(kRuntimeWrappedException));
GCPROTECT_BEGIN(orWrapper);
MethodDescCallSite ctor(METHOD__RUNTIME_WRAPPED_EXCEPTION__OBJ_CTOR, &orWrapper);
ARG_SLOT args[] =
{
ObjToArgSlot(orWrapper),
ObjToArgSlot(*ppThrowable)
};
ctor.Call(args);
*ppThrowable = orWrapper;
GCPROTECT_END();
}
EX_CATCH
{
// If we took an exception while binding, or running the constructor of the RuntimeWrappedException
// instance, we know that this new exception is CLS compliant. In fact, it's likely to be
// OutOfMemoryException, StackOverflowException or ThreadAbortException.
OBJECTREF orReplacement = GET_THROWABLE();
_ASSERTE(IsException(orReplacement->GetMethodTable()));
*ppThrowable = orReplacement;
} EX_END_CATCH(SwallowAllExceptions);
}
// Before presenting an exception object to a handler (filter or catch, not finally or fault), it
// may be necessary to turn it back into a non-compliant exception. This is conditioned on an
// assembly level setting.
OBJECTREF PossiblyUnwrapThrowable(OBJECTREF throwable, Assembly *pAssembly)
{
// Check if we are required to compute the RuntimeWrapExceptions status.
BOOL fIsRuntimeWrappedException = ((throwable != NULL) && (throwable->GetMethodTable() == pMT_RuntimeWrappedException));
BOOL fRequiresComputingRuntimeWrapExceptionsStatus = (fIsRuntimeWrappedException &&
(!(pAssembly->GetManifestModule()->IsRuntimeWrapExceptionsStatusComputed())));
CONTRACTL
{
THROWS;
// If we are required to compute the status of RuntimeWrapExceptions, then the operation could trigger a GC.
// Thus, conditionally setup the contract.
if (fRequiresComputingRuntimeWrapExceptionsStatus) GC_TRIGGERS; else GC_NOTRIGGER;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pAssembly));
}
CONTRACTL_END;
if (fIsRuntimeWrappedException && (!pAssembly->GetManifestModule()->IsRuntimeWrapExceptions()))
{
// We already created the instance, fetched the field. We know it is
// not marshal by ref, or any of the other cases that might trigger GC.
ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE();
throwable = pFD_WrappedException->GetRefValue(throwable);
}
return throwable;
}
// This is used by a holder in CreateTypeInitializationExceptionObject to
// reset the state as appropriate.
void ResetTypeInitializationExceptionState(BOOL isAlreadyCreating)
{
LIMITED_METHOD_CONTRACT;
if (!isAlreadyCreating)
GetThread()->ResetIsCreatingTypeInitException();
}
void CreateTypeInitializationExceptionObject(LPCWSTR pTypeThatFailed,
OBJECTREF *pInnerException,
OBJECTREF *pInitException,
OBJECTREF *pThrowable)
{
CONTRACTL {
NOTHROW;
GC_TRIGGERS;
MODE_COOPERATIVE;
PRECONDITION(CheckPointer(pInnerException, NULL_OK));
PRECONDITION(CheckPointer(pInitException));
PRECONDITION(CheckPointer(pThrowable));
PRECONDITION(IsProtectedByGCFrame(pInnerException));
PRECONDITION(IsProtectedByGCFrame(pInitException));
PRECONDITION(IsProtectedByGCFrame(pThrowable));
PRECONDITION(CheckPointer(GetThread()));
} CONTRACTL_END;
Thread *pThread = GetThread();
*pThrowable = NULL;
// This will make sure to put the thread back to its original state if something
// throws out of this function (like an OOM exception or something)
Holder< BOOL, DoNothing< BOOL >, ResetTypeInitializationExceptionState, FALSE, NoNull< BOOL > >
isAlreadyCreating(pThread->IsCreatingTypeInitException());
EX_TRY {
// This will contain the type of exception we want to create. Read comment below
// on why we'd want to create an exception other than TypeInitException
MethodTable *pMT;
BinderMethodID methodID;
// If we are already in the midst of creating a TypeInitializationException object,
// and we get here, it means there was an exception thrown while initializing the
// TypeInitializationException type itself, or one of the types used by its class
// constructor. In this case, we're going to back down and use a SystemException
// object in its place. It is *KNOWN* that both these exception types have identical
// .ctor sigs "void instance (string, exception)" so both can be used interchangeably
// in the code that follows.
if (!isAlreadyCreating.GetValue()) {
pThread->SetIsCreatingTypeInitException();
pMT = MscorlibBinder::GetException(kTypeInitializationException);
methodID = METHOD__TYPE_INIT_EXCEPTION__STR_EX_CTOR;
}
else {
// If we ever hit one of these asserts, then it is bad
// because we do not know what exception to return then.
_ASSERTE(pInnerException != NULL);
_ASSERTE(*pInnerException != NULL);
*pThrowable = *pInnerException;
*pInitException = *pInnerException;
goto ErrExit;
}
// Allocate the exception object
*pThrowable = AllocateObject(pMT);
MethodDescCallSite ctor(methodID, pThrowable);
// Since the inner exception object in the .ctor is of type Exception, make sure
// that the object we're passed in derives from Exception. If not, pass NULL.
BOOL isException = FALSE;
if (pInnerException != NULL)
isException = IsException((*pInnerException)->GetMethodTable());
_ASSERTE(isException); // What pathway can give us non-compliant exceptions?
STRINGREF sType = StringObject::NewString(pTypeThatFailed);
// If the inner object derives from exception, set it as the third argument.
ARG_SLOT args[] = { ObjToArgSlot(*pThrowable),
ObjToArgSlot(sType),
ObjToArgSlot(isException ? *pInnerException : NULL) };
// Call the .ctor
ctor.Call(args);
// On success, set the init exception.
*pInitException = *pThrowable;
}
EX_CATCH {
// If calling the constructor fails, then we'll call ourselves again, and this time
// through we will try and create an EEException object. If that fails, then the
// else block of this will be executed.
if (!isAlreadyCreating.GetValue()) {
CreateTypeInitializationExceptionObject(pTypeThatFailed, pInnerException, pInitException, pThrowable);
}
// If we were already in the middle of creating a type init
// exception when we were called, we would have tried to create an EEException instead
// of a TypeInitException.
else {
// If we're recursing, then we should be calling ourselves from DoRunClassInitThrowing,
// in which case we're guaranteed that we're passing in all three arguments.
*pInitException = pInnerException ? *pInnerException : NULL;
*pThrowable = GET_THROWABLE();
}
} EX_END_CATCH(SwallowAllExceptions);
CONSISTENCY_CHECK(*pInitException != NULL || !pInnerException);
ErrExit:
;
}
// ==========================================================================
// ComputeEnclosingHandlerNestingLevel
//
// This is code factored out of COMPlusThrowCallback to figure out
// what the number of nested exception handlers is.
// ==========================================================================
DWORD ComputeEnclosingHandlerNestingLevel(IJitManager *pIJM,
const METHODTOKEN& mdTok,
SIZE_T offsNat)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
// Determine the nesting level of EHClause. Just walk the table
// again, and find out how many handlers enclose it
DWORD nestingLevel = 0;
EH_CLAUSE_ENUMERATOR pEnumState;
unsigned EHCount = pIJM->InitializeEHEnumeration(mdTok, &pEnumState);
for (unsigned j=0; j<EHCount; j++)
{
EE_ILEXCEPTION_CLAUSE EHClause;
pIJM->GetNextEHClause(&pEnumState,&EHClause);
_ASSERTE(EHClause.HandlerEndPC != (DWORD) -1); // <TODO> remove, only protects against a deprecated convention</TODO>
if ((offsNat > EHClause.HandlerStartPC) &&
(offsNat < EHClause.HandlerEndPC))
{
nestingLevel++;
}
}
return nestingLevel;
}
// ******************************* EHRangeTreeNode ************************** //
EHRangeTreeNode::EHRangeTreeNode(void)
{
WRAPPER_NO_CONTRACT;
CommonCtor(0, false);
}
EHRangeTreeNode::EHRangeTreeNode(DWORD offset, bool fIsRange /* = false */)
{
WRAPPER_NO_CONTRACT;
CommonCtor(offset, fIsRange);
}
void EHRangeTreeNode::CommonCtor(DWORD offset, bool fIsRange)
{
LIMITED_METHOD_CONTRACT;
m_pTree = NULL;
m_clause = NULL;
m_pContainedBy = NULL;
m_offset = offset;
m_fIsRange = fIsRange;
m_fIsRoot = false; // must set this flag explicitly
}
inline bool EHRangeTreeNode::IsRange()
{
// Please see the header file for an explanation of this assertion.
_ASSERTE(m_fIsRoot || m_clause != NULL || !m_fIsRange);
return m_fIsRange;
}
void EHRangeTreeNode::MarkAsRange()
{
m_offset = 0;
m_fIsRange = true;
m_fIsRoot = false;
}
inline bool EHRangeTreeNode::IsRoot()
{
// Please see the header file for an explanation of this assertion.
_ASSERTE(m_fIsRoot || m_clause != NULL || !m_fIsRange);
return m_fIsRoot;
}
void EHRangeTreeNode::MarkAsRoot(DWORD offset)
{
m_offset = offset;
m_fIsRange = true;
m_fIsRoot = true;
}
inline DWORD EHRangeTreeNode::GetOffset()
{
_ASSERTE(m_clause == NULL);
_ASSERTE(IsRoot() || !IsRange());
return m_offset;
}
inline DWORD EHRangeTreeNode::GetTryStart()
{
_ASSERTE(IsRange());
_ASSERTE(!IsRoot());
if (IsRoot())
{
return 0;
}
else
{
return m_clause->TryStartPC;
}
}
inline DWORD EHRangeTreeNode::GetTryEnd()
{
_ASSERTE(IsRange());
_ASSERTE(!IsRoot());
if (IsRoot())
{
return GetOffset();
}
else
{
return m_clause->TryEndPC;
}
}
inline DWORD EHRangeTreeNode::GetHandlerStart()
{
_ASSERTE(IsRange());
_ASSERTE(!IsRoot());
if (IsRoot())
{
return 0;
}
else
{
return m_clause->HandlerStartPC;
}
}
inline DWORD EHRangeTreeNode::GetHandlerEnd()
{
_ASSERTE(IsRange());
_ASSERTE(!IsRoot());
if (IsRoot())
{
return GetOffset();
}
else
{
return m_clause->HandlerEndPC;
}
}
inline DWORD EHRangeTreeNode::GetFilterStart()
{
_ASSERTE(IsRange());
_ASSERTE(!IsRoot());
if (IsRoot())
{
return 0;
}
else
{
return m_clause->FilterOffset;
}
}
// Get the end offset of the filter clause. This offset is exclusive.
inline DWORD EHRangeTreeNode::GetFilterEnd()
{
_ASSERTE(IsRange());
_ASSERTE(!IsRoot());
if (IsRoot())
{
// We should never get here if the "this" node is the root.
// By definition, the root contains everything. No checking is necessary.
return 0;
}
else
{
return m_FilterEndPC;
}
}
bool EHRangeTreeNode::Contains(DWORD offset)
{
WRAPPER_NO_CONTRACT;
EHRangeTreeNode node(offset);
return Contains(&node);
}
bool EHRangeTreeNode::TryContains(DWORD offset)
{
WRAPPER_NO_CONTRACT;
EHRangeTreeNode node(offset);
return TryContains(&node);
}
bool EHRangeTreeNode::HandlerContains(DWORD offset)
{
WRAPPER_NO_CONTRACT;
EHRangeTreeNode node(offset);
return HandlerContains(&node);
}
bool EHRangeTreeNode::FilterContains(DWORD offset)
{
WRAPPER_NO_CONTRACT;
EHRangeTreeNode node(offset);
return FilterContains(&node);
}
bool EHRangeTreeNode::Contains(EHRangeTreeNode* pNode)
{
LIMITED_METHOD_CONTRACT;
// If we are checking a range of address, then we should check the end address inclusively.
if (pNode->IsRoot())
{
// No node contains the root node.
return false;
}
else if (this->IsRoot())
{
return (pNode->IsRange() ?
(pNode->GetTryEnd() <= this->GetOffset()) && (pNode->GetHandlerEnd() <= this->GetOffset())
: (pNode->GetOffset() < this->GetOffset()) );
}
else
{
return (this->TryContains(pNode) || this->HandlerContains(pNode) || this->FilterContains(pNode));
}
}
bool EHRangeTreeNode::TryContains(EHRangeTreeNode* pNode)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(this->IsRange());
if (pNode->IsRoot())
{
// No node contains the root node.
return false;
}
else if (this->IsRoot())
{
// We will only get here from GetTcf() to determine if an address is in a try clause.
// In this case we want to return false.
return false;
}
else
{
DWORD tryStart = this->GetTryStart();
DWORD tryEnd = this->GetTryEnd();
// If we are checking a range of address, then we should check the end address inclusively.
if (pNode->IsRange())
{
DWORD start = pNode->GetTryStart();
DWORD end = pNode->GetTryEnd();
if (start == tryStart && end == tryEnd)
{
return false;
}
else if (start == end)
{
// This is effectively a single offset.
if ((tryStart <= start) && (end < tryEnd))
{
return true;
}
}
else if ((tryStart <= start) && (end <= tryEnd))
{
return true;
}
}
else