This repository was 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.6k
/
Copy pathcontract.h
2355 lines (1961 loc) · 97.8 KB
/
contract.h
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.
// ---------------------------------------------------------------------------
// Contract.h
//
// ! I am the owner for issues in the contract *infrastructure*, not for every
// ! CONTRACT_VIOLATION dialog that comes up. If you interrupt my work for a routine
// ! CONTRACT_VIOLATION, you will become the new owner of this file.
//--------------------------------------------------------------------------------
// CONTRACTS - User Reference
//
// A CONTRACT is a container for a set of checked declarations about a
// function. Besides giving developers a "laundry list" of checks to
// make checking more complete, contracts compile these checks
// as hidden annotations into the checked executable that our static scanner
// uses to detect violations automatically.
//
// Contracts can be dynamic or static. Dynamic contracts perform runtime checks
// as well as being visible to the static scanner. Static contracts generate no
// runtime code but are still visible to the scanner. Dynamic contracts are
// preferred unless perf or other considerations preclude them.
//
// The following annotations can appear in contracts:
//
//
// THROWS an exception might be thrown out of the function
// -or- NOTHROW an exception will NOT be thrown out of the function
//
//
//
// INJECT_FAULT(statement) function might require its caller to handle an OOM
// -or- FAULT_FORBID function will NOT require its caller to handle an OOM
//
//
//
// GC_TRIGGERS the function can trigger a GC
// -or- GC_NOTRIGGER the function will never trigger a GC provided its
// called in coop mode.
//
//
// MODE_COOPERATIVE the function requires Cooperative GC mode on entry
// -or- MODE_PREEMPTIVE the function requires Preemptive GC mode on entry
// -or- MODE_ANY the function can be entered in either mode
//
// LOADS_TYPE(level) the function promises not to load any types beyond "level"
//
// CAN_TAKE_LOCK the function has a code path that takes a lock
// _or_ (CAN_TAKE_LOCK and CANNOT_RETAKE_LOCK)
// the function has a code path that takes a lock, but never tries to reenter
// locks held at the time this function was called.
// -or- CANNOT_TAKE_LOCK the function will never allow a lock to be taken
// -or- the default is WRAPPER(CAN_TAKE_LOCK). i.e., if any callees take locks,
// then it's ok for this function to as well. If LIMITED_METHOD_CONTRACT is specified,
// however, then CANNOT_TAKE_LOCK is assumed.
//
// EE_THREAD_NOT_REQUIRED the function does not assume an EE Thread object is available in TLS.
// Either GetThread() is never called, or any code path that requires a Thread
// has another code path that deals with the absence of a Thread. Any call to
// to GetThread() must be bracketed with BEGIN_GETTHREAD_ALLOWED /
// END_GETTHREAD_ALLOWED to avoid bogus asserts (the short-form
// GetThreadNULLOk() may be used as well). However, this is only allowed if visual
// inspection of the call site makes it patently obvious that the function deals
// appropriately with the GetThread() == NULL case.
// -or- EE_THREAD_REQUIRED the function requires an EE Thread object in TLS (i.e., GetThread() != NULL)
// If this contract is used, we will ASSERT on entry to the function that
// GetThread() != NULL.
// -or- the default is DISABLED(EE_THREAD_REQUIRED). i.e., we do not assert
// GetThread() != NULL on entry to the function and do not assert on any
// unprotected uses of GetThread().
// See code:GetThreadGenericFullCheck for info on how these
// contracts are enforced.
//
// SUPPORTS_DAC The function has been written to be callable from out-of-process using DAC.
// In builds where DACCESS_COMPILE is defined, such functions can only call
// other such functions (and a few primitives like new). Functions that support
// DAC must be carefully written to conform to the rules in daccess.h.
//
// SUPPORTS_DAC_HOST_ONLY The function and its call graph has been written to be callable from out of process
// using DAC, but it differs from SUPPORTS_DAC in that these functions won't perform
// any marshalling. Because it does no marshalling, SUPPORTS_DAC_HOST_ONLY functions
// and their call graph won't be checked by DacCop. This should only be used by utility
// functions which will never marshal anything.
//
// PRECONDITION(X) - generic CHECK or BOOL expression which should be true
// on function entry
//
// POSTCONDITION(X) - generic CHECK or BOOL expression which should be true
// on function entry. Note that variable RETVAL will be
// available for use in the expression.
//
//
// INSTANCE_CHECK - equivalent of:
// PRECONDITION(CheckPointer(this));
// POSTCONDITION(CheckInvariant(this));
// INSTANCE_CHECK_NULL - equivalent of:
// PRECONDITION(CheckPointer(this, NULL_OK));
// POSTCONDITION(CheckInvariant(this, NULL_OK));
// CONSTRUCTOR_CHECK - equivalent of:
// POSTCONDITION(CheckPointer(this));
// DESTRUCTOR_CHECK - equivalent of:
// PRECONDITION(CheckPointer(this));
//
//
//
//
// Contracts come in the following flavors:
//
// Dynamic:
// CONTRACTL the standard version used for all dynamic contracts
// except those including postconditions.
//
// CONTRACT(rettype) an uglier version of CONTRACTL that's unfortunately
// needed to support postconditions. You must specify
// the correct return type and it cannot be "void."
// (Use CONTRACT_VOID instead) You must use the
// RETURN macro rather than the "return" keyword.
//
// CONTRACT_VOID you can't supply "void" to a CONTRACT - use this
// instead.
//
// Static:
// LIMITED_METHOD_CONTRACT
// A static contract equivalent to NOTHROW/GC_NOTRIGGER/FORBID_FAULT/MODE_ANY.
// Use only for trivial functions that call only functions with LIMITED_METHOD_CONTRACTs
// (as long as there is no cycle that may introduce infinite recursion).
//
// STATIC_CONTRACT_THROWS
// STATIC_CONTRACT_NOTHROW
// STATIC_CONTRACT_GC_TRIGGERS
// STATIC_CONTRACT_GCNOTRIGGER
// STATIC_CONTRACT_FAULT
// STATIC_CONTRACT_FORBID_FAULT
// use to implement statically checkable contracts
// when runtime contracts cannot be used.
//
//
// WRAPPER(annotation)
//
// When a function does not explicitly caused a condition, use the WRAPPER macro around
// the declaration. This implies that the function is dependent on the functions it calls
// for its behaviour, and guarantees nothing.
//
//
// CONTRACT_VIOLATION(violationmask):
//
// A bandaid used to suppress contract assertions. A contract violation
// is always a bug and you're expected to remove it before shipping.
// If a violation cannot be fixed immediately, however, it's better
// to use this on the offending callsite than to disable a contract entirely.
//
// The violationmask can be one or more of the following OR'd together.
//
// ThrowsViolation
// GCViolation
// ModeViolation
// FaultViolation
// FaultNotFatal
// HostViolation
// LoadsTypeViolation
// TakesLockViolation
//
// The associated assertion will be suppressed until you leave the scope
// containing the CONTRACT_VIOLATION. Note, however, that any called
// function that redeclares the associated annotation reinstates
// the assert for the scope of *its* call. This prevents a CONTRACT_VIOLATION
// placed at the root of a calltree from decimating our entire protection.
//
//
// PERMANENT_CONTRACT_VIOLATION(violationmask, permanentContractViolationReason):
//
// Like a CONTRACT_VIOLATION but also indicates that the violation was a deliberate decision
// and we don't plan on removing the violation in the next release. The reason
// for the violation should be given as the second parameter to the macro. Reasons
// are currently for documentation purposes only and do not have an effect on the binary.
// Valid values are listed below in the definition of PermanentContractViolationReason.
//
//
// CONDITIONAL_CONTRACT_VIOLATION(violationmask, condition):
//
// Similar to CONTRACT_VIOLATION, but only suppresses the contract if the
// condition evaluates to non-zero. The need for this macro should be very
// rare, but it can be useful if a contract should be suppressed based on a
// condition known only at run-time. For example, if a particular test causes
// call sequences never expected by real scenarios, you may want to suppress
// resulting violations, but only when that test is run.
//
// WRAPPER_NO_CONTRACT
//
// A do-nothing contract used by functions that trivially wrap another.
//
//
// "LEGACY" stuff - these features have been mostly superceded by better solutions
// so their use should be discouraged.
//
//
// DISABLED(annotation)
//
// Indicates that a condition is supposed to be checked but is being suppressed
// due to some temporary bug. The more surgical CONTRACT_VIOLATION is
// preferred over DISABLED.
//
// UNCHECKED(annotation)
//
// Indicates that a condition is supposed to be checked but is being suppressed
// due for perf reasons. Use STATIC_CONTRACT over this.
//
//
// Default values:
// If you don't specify certain annotaions, you get defaults.
// - THROWS/NOTHROW defaults to THROWS
// - GCTRIGGERS/GCNOTRIGGER defaults to GCTRIGGERS within the VM directory
// and to no check otherwise
// - INJECT/FORBID_FAULT defaults to no check
// - MODE defaults to MODE_ANY
//
// The problem is that defaults don't work well with static contracts.
// The scanner will always treat a missing annotation as DISABLED.
// New code should not rely on defaults. Explicitly state your invariants.
//
//
//--------------------------------------------------------------------------------
#ifndef CONTRACT_H_
#define CONTRACT_H_
#ifdef _MSC_VER
#pragma warning(disable:4189) //local variable is initialized but not referenced
#endif
// We only enable contracts in _DEBUG builds
#if defined(_DEBUG) && !defined(DISABLE_CONTRACTS)
#define ENABLE_CONTRACTS_DATA
#endif
// Also, we won't enable contracts if this is a DAC build.
#if defined(ENABLE_CONTRACTS_DATA) && !defined(DACCESS_COMPILE) && !defined(CROSS_COMPILE)
#define ENABLE_CONTRACTS
#endif
// Finally, only define the implementaiton parts of contracts if this isn't a DAC build.
#if defined(_DEBUG_IMPL) && defined(ENABLE_CONTRACTS)
#define ENABLE_CONTRACTS_IMPL
#endif
#include "specstrings.h"
#include "clrtypes.h"
#include "malloc.h"
#include "check.h"
#include "debugreturn.h"
#include "staticcontract.h"
#ifdef ENABLE_CONTRACTS_DATA
#include "eh.h"
// We chain these onto a stack to give us a stack trace of contract assertions (useful
// when the bug report doesn't contain valid symbols)
struct ContractStackRecord
{
ContractStackRecord *m_pNext;
const char *m_szFunction;
const char *m_szFile;
int m_lineNum;
UINT m_testmask; // Bitmask of Contract::TestEnum bitsf
const char *m_construct; // The syntactic construct that pushed this thing
};
class CrstBase;
// The next few enums / structs are used to keep track of all kinds of locks
// currently taken by the current thread (crsts, spinlocks, CLR critical sections).
// Across the VM, there are still multiple counts of locks. The lock counts in these
// contract structs are used to verify consistency of lock take/release in EE code, and
// for contracts. Both user and EE locks are tracked here, but it's EE code consistency
// we're verifying. The Thread object keeps its own counts as well, primarily of user
// locks for implementing thread abort & escalation policy. We tried to have the Thread
// counts also be used for consistency checking, but that doesn't work. Thread counters
// have the following behavior that hurts our internal consistency checks:
// - They only count user locks.
// - Counters are reset & restored as we leave and return to AppDomains
// An array of these is stored in DbgStateLockData::m_rgTakenLockInfos
// to remember which locks we've taken. If you hit an assert that
// indicates we're exiting locks in the wrong order, or that locks were
// taken when we expected none to be taken, then you can use
// DbgStateLockData::m_rgTakenLockInfos to see the locks we know about.
struct TakenLockInfo
{
// Generally, this will be a pointer to the lock, but really it's just
// a value that identifies which lock is taken. Ya see, sometimes we don't
// have a lock pointer handy (e.g., if the lock is based on a GC object,
// which has no persistent object pointer we can use). Look at the source
// indicated by m_szFile / m_lineNum to see what was specified as m_pvLock.
//
// A common case is that the lock is just a Crst, so to aid debugging, we
// also include a statically typed version of this pointer (m_pCrstBase) just
// for Crsts. Again, you'll want look at m_szFile / m_lineNum to see how to
// interpret this union.
union
{
void * m_pvLock;
CrstBase * m_pCrstBase;
};
// File & line of the *LOCK_TAKEN* macro that added this lock to our list
const char * m_szFile;
int m_lineNum;
};
enum DbgStateLockType
{
// EE locks (used to sync EE structures). These do not include
// CRST_HOST_BREAKABLE Crsts, and are thus not held while managed
// code runs
kDbgStateLockType_EE,
// CRST_HOST_BREAKABLE Crsts. These can be held while arbitrary
// managed code runs.
kDbgStateLockType_HostBreakableCrst,
// User locks (e.g., Monitor.Enter, ReaderWriterLock class)
kDbgStateLockType_User,
// add more lock types here
kDbgStateLockType_Count
};
// This keeps track of how many locks, and which locks, are currently owned
// by the current thread. There is one instance of this structure per
// thread (no EE Thread object required). This is in contrast to the
// ClrDebugState structure, which is instantiated once per function
// on the stack. Reason is that ClrDebugState resets its state on exit
// of function (Contract destructor reinstates previous ClrDebugState), whereas
// we want DbgStateLockData to persist across function enters & exits.
struct DbgStateLockData
{
// When a lock is taken, we keep track of its pointer and file/line# when it
// was added in a static-size array DbgStateLockData::m_rgTakenLockInfos. This is
// the size of that array, and therefore indicates the maximum number of locks we
// expect one thread to hold at the same time. If we should exceed this limit,
// we'll lose this data for the latter locks that exceed this limit
// (though still maintaining an accurate *count* of locks).
static const int kMaxAllowedSimultaneousLocks = 20;
// Count of locks taken, separately by type
UINT m_rgcLocksTaken[kDbgStateLockType_Count];
// List of the specific locks that have been taken (all DbgStateLockTypes
// intermingled), in the order they were taken. If we exceed the elements
// in the array, we just won't track the latter locks in here (though they are
// included in the counts above)
TakenLockInfo m_rgTakenLockInfos[kMaxAllowedSimultaneousLocks];
void SetStartingValues();
void LockTaken(DbgStateLockType dbgStateLockType,
UINT cEntrances,
void * pvLock,
__in_z const char * szFunction,
__in_z const char * szFile,
int lineNum);
void LockReleased(DbgStateLockType dbgStateLockType, UINT cExits, void * pvLock);
UINT GetLockCount(DbgStateLockType dbgStateLockType);
UINT GetCombinedLockCount();
};
// This struct contains all lock contract information. It is created and destroyed along with
// ClrDebugState. m_pLockData points to a DbgStateLockData object that is allocated per thread
// and persists across function enters and exists.
struct DbgStateLockState
{
private:
// Count of locks taken at the time the function with CANNOT_RETAKE_LOCK contract
// was called
UINT m_cLocksEnteringCannotRetakeLock;
DbgStateLockData * m_pLockData; // How many and which locks are currently taken on this thread
public:
void SetStartingValues();
void OnEnterCannotRetakeLockFunction();
BOOL IsLockRetaken(void * pvLock);
BOOL IsSafeToRelease(UINT cReleases);
void SetDbgStateLockData(DbgStateLockData * pDbgStateLockData);
DbgStateLockData * GetDbgStateLockData();
};
#define CONTRACT_BITMASK_OK_TO_THROW 0x1 << 0
#define CONTRACT_BITMASK_FAULT_FORBID 0x1 << 1
#define CONTRACT_BITMASK_HOSTCALLS 0x1 << 2
#define CONTRACT_BITMASK_SOTOLERANT 0x1 << 3
#define CONTRACT_BITMASK_DEBUGONLY 0x1 << 4
#define CONTRACT_BITMASK_SONOTMAINLINE 0x1 << 5
#define CONTRACT_BITMASK_ALLOWGETTHREAD 0x1 << 6
#define CONTRACT_BITMASK_OK_TO_LOCK 0x1 << 7
#define CONTRACT_BITMASK_OK_TO_RETAKE_LOCK 0x1 << 8
#define CONTRACT_BITMASK_IS_SET(whichbit) ((m_flags & (whichbit)) != 0)
#define CONTRACT_BITMASK_SET(whichbit) (m_flags |= (whichbit))
#define CONTRACT_BITMASK_RESET(whichbit) (m_flags &= ~(whichbit))
#define CONTRACT_BITMASK_UPDATE(whichbit, value) ((value)?CONTRACT_BITMASK_SET(whichbit):CONTRACT_BITMASK_RESET(whichbit))
// Stored in the FLS under TlsIdx_ClrDebugState.
struct ClrDebugState
{
private:
UINT_PTR m_flags;
UINT_PTR m_violationmask; // Current CONTRACT_VIOLATIONS in effect
ContractStackRecord *m_pContractStackTrace;
UINT m_GCNoTriggerCount;
UINT m_GCForbidCount;
UINT m_maxLoadTypeLevel; // taken from enum ClassLoadLevel
BOOL m_allowGetThread; // TRUE if GetThread() is ok in this scope
DbgStateLockState m_LockState;
public:
// Use an explicit Init rather than ctor as we don't want automatic
// construction of the ClrDebugState embedded inside the contract.
void SetStartingValues()
{
m_violationmask = 0; // No violations allowed
// Default is we're in a THROWS scope. This is not ideal, but there are
// just too many places that I'd have to go clean up right now
// (hundreds) in order to make this FALSE by default.
// Faults not forbidden (an unfortunate default but
// we'd never get this debug infrastructure bootstrapped otherwise.)
// We start out in SO-tolerant mode and must probe before entering SO-intolerant
// any global state updates.
// Initial mode is non-debug until we say otherwise
// Everthing defaults to mainline
// By default, GetThread() is perfectly fine to call
// By default, it's ok to take a lock (or call someone who does)
m_flags = CONTRACT_BITMASK_OK_TO_THROW|
CONTRACT_BITMASK_HOSTCALLS|
CONTRACT_BITMASK_SOTOLERANT|
CONTRACT_BITMASK_ALLOWGETTHREAD|
CONTRACT_BITMASK_OK_TO_LOCK|
CONTRACT_BITMASK_OK_TO_RETAKE_LOCK;
m_pContractStackTrace = NULL; // At top of stack, no contracts in force
m_GCNoTriggerCount = 0;
m_GCForbidCount = 0;
m_maxLoadTypeLevel = ((UINT)(-1)); // ideally CLASS_LOAD_LEVEL_FINAL but we don't have access to that #define, so
// the max integer value will do as a substitute.
m_allowGetThread = TRUE; // By default, GetThread() is perfectly fine to call
m_LockState.SetStartingValues();
}
void CheckOkayToThrow(__in_z const char *szFunction, __in_z const char *szFile, int lineNum); // Asserts if its not okay to throw.
BOOL CheckOkayToThrowNoAssert(); // Returns if OK to throw
//--//
UINT_PTR* ViolationMaskPtr()
{
return &m_violationmask;
}
UINT_PTR ViolationMask()
{
return m_violationmask;
}
void ViolationMaskSet( UINT_PTR value )
{
m_violationmask |= value;
}
void ViolationMaskReset( UINT_PTR value )
{
m_violationmask &= ~value;
}
//--//
BOOL IsOkToThrow()
{
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_OK_TO_THROW);
}
void SetOkToThrow()
{
CONTRACT_BITMASK_SET(CONTRACT_BITMASK_OK_TO_THROW);
}
BOOL SetOkToThrow( BOOL value )
{
BOOL prevState = CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_OK_TO_THROW);
CONTRACT_BITMASK_UPDATE(CONTRACT_BITMASK_OK_TO_THROW, value);
return prevState;
}
void ResetOkToThrow()
{
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_OK_TO_THROW);
}
//--//
BOOL IsFaultForbid()
{
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_FAULT_FORBID);
}
void SetFaultForbid()
{
CONTRACT_BITMASK_SET(CONTRACT_BITMASK_FAULT_FORBID);
}
BOOL SetFaultForbid(BOOL value)
{
BOOL prevState = CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_FAULT_FORBID);
CONTRACT_BITMASK_UPDATE(CONTRACT_BITMASK_FAULT_FORBID, value);
return prevState;
}
void ResetFaultForbid()
{
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_FAULT_FORBID);
}
//--//
BOOL IsHostCaller()
{
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_HOSTCALLS);
}
void SetHostCaller()
{
CONTRACT_BITMASK_SET(CONTRACT_BITMASK_HOSTCALLS);
}
BOOL SetHostCaller(BOOL value)
{
BOOL prevState = CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_HOSTCALLS);
CONTRACT_BITMASK_UPDATE(CONTRACT_BITMASK_HOSTCALLS,value);
return prevState;
}
void ResetHostCaller()
{
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_HOSTCALLS);
}
//--//
BOOL IsDebugOnly()
{
STATIC_CONTRACT_WRAPPER;
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_DEBUGONLY);
}
void SetDebugOnly()
{
STATIC_CONTRACT_WRAPPER;
CONTRACT_BITMASK_SET(CONTRACT_BITMASK_DEBUGONLY);
}
BOOL SetDebugOnly(BOOL value)
{
STATIC_CONTRACT_WRAPPER;
BOOL prevState = CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_DEBUGONLY);
CONTRACT_BITMASK_UPDATE(CONTRACT_BITMASK_DEBUGONLY,value);
return prevState;
}
void ResetDebugOnly()
{
STATIC_CONTRACT_LIMITED_METHOD;
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_DEBUGONLY);
}
//--//
BOOL IsGetThreadAllowed()
{
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_ALLOWGETTHREAD);
}
void SetGetThreadAllowed()
{
CONTRACT_BITMASK_SET(CONTRACT_BITMASK_ALLOWGETTHREAD);
}
BOOL SetGetThreadAllowed(BOOL value)
{
BOOL prevState = CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_ALLOWGETTHREAD);
CONTRACT_BITMASK_UPDATE(CONTRACT_BITMASK_ALLOWGETTHREAD,value);
return prevState;
}
void ResetGetThreadAllowed()
{
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_ALLOWGETTHREAD);
}
//--//
BOOL IsOkToLock()
{
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_OK_TO_LOCK);
}
void SetOkToLock()
{
CONTRACT_BITMASK_SET(CONTRACT_BITMASK_OK_TO_LOCK);
}
BOOL SetOkToLock( BOOL value )
{
BOOL prevState = CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_OK_TO_LOCK);
CONTRACT_BITMASK_UPDATE(CONTRACT_BITMASK_OK_TO_LOCK, value);
return prevState;
}
void ResetOkToLock()
{
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_OK_TO_LOCK);
}
//--//
BOOL IsOkToRetakeLock()
{
return CONTRACT_BITMASK_IS_SET(CONTRACT_BITMASK_OK_TO_RETAKE_LOCK);
}
void ResetOkToRetakeLock()
{
CONTRACT_BITMASK_RESET(CONTRACT_BITMASK_OK_TO_RETAKE_LOCK);
}
//--//
void LinkContractStackTrace( ContractStackRecord* pContractStackTrace )
{
pContractStackTrace->m_pNext = m_pContractStackTrace;
m_pContractStackTrace = pContractStackTrace;
}
ContractStackRecord* GetContractStackTrace()
{
return m_pContractStackTrace;
}
void SetContractStackTrace(ContractStackRecord* pContractStackTrace )
{
m_pContractStackTrace = pContractStackTrace;
}
//--//
UINT GetGCNoTriggerCount()
{
return m_GCNoTriggerCount;
}
void DecrementGCNoTriggerCount()
{
m_GCNoTriggerCount--;
}
void IncrementGCNoTriggerCount()
{
m_GCNoTriggerCount++;
}
UINT GetGCForbidCount()
{
return m_GCForbidCount;
}
void DecrementGCForbidCount()
{
m_GCForbidCount--;
}
void IncrementGCForbidCount()
{
m_GCForbidCount++;
}
UINT GetMaxLoadTypeLevel()
{
return m_maxLoadTypeLevel;
}
void SetMaxLoadTypeLevel(UINT newLevel)
{
m_maxLoadTypeLevel = newLevel;
}
//--//
void SetDbgStateLockData(DbgStateLockData * pDbgStateLockData)
{
m_LockState.SetDbgStateLockData(pDbgStateLockData);
}
DbgStateLockData * GetDbgStateLockData()
{
return m_LockState.GetDbgStateLockData();
}
void OnEnterCannotRetakeLockFunction()
{
m_LockState.OnEnterCannotRetakeLockFunction();
}
void CheckOkayToLock(__in_z const char *szFunction, __in_z const char *szFile, int lineNum); // Asserts if its not okay to lock
BOOL CheckOkayToLockNoAssert(); // Returns if OK to lock
void LockTaken(DbgStateLockType dbgStateLockType,
UINT cEntrances,
void * pvLock,
__in_z const char * szFunction,
__in_z const char * szFile,
int lineNum);
void LockReleased(DbgStateLockType dbgStateLockType, UINT cExits, void * pvLock);
UINT GetLockCount(DbgStateLockType dbgStateLockType);
UINT GetCombinedLockCount();
};
#endif // ENABLE_CONTRACTS
#ifdef ENABLE_CONTRACTS_IMPL
// Create ClrDebugState.
// This routine is not allowed to return NULL. If it can't allocate the memory needed,
// it should return a pointer to a global static ClrDebugState that indicates
// that debug assertions should be skipped.
ClrDebugState *CLRInitDebugState();
ClrDebugState *GetClrDebugState(BOOL fAlloc = TRUE);
// This function returns a ClrDebugState if one has been created, but will not create one itself.
inline ClrDebugState *CheckClrDebugState()
{
STATIC_CONTRACT_LIMITED_METHOD;
ClrDebugState *ret = (ClrDebugState*)ClrFlsGetValue(TlsIdx_ClrDebugState);
return ret;
}
void CONTRACT_ASSERT(const char *szElaboration,
UINT whichTest,
UINT whichTestMask,
const char *szFunction,
const char *szFile,
int lineNum
);
#endif
// This needs to be defined up here b/c it is used by ASSERT_CHECK which is used by the contract impl
#ifdef _DEBUG
#ifdef ENTER_DEBUG_ONLY_CODE
#undef ENTER_DEBUG_ONLY_CODE
#endif
#ifdef LEAVE_DEBUG_ONLY_CODE
#undef LEAVE_DEBUG_ONLY_CODE
#endif
#ifdef ENABLE_CONTRACTS_IMPL
// This can only appear in a debug function so don't define it non-debug
class DebugOnlyCodeHolder
{
public:
// We use GetClrDebugState on entry, but CheckClrDebugState on Leave
// That way we make sure to create one if we need to set state, but
// we don't recreated one on exit if its been deleted.
DEBUG_NOINLINE void Enter()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_DEBUG_ONLY;
m_pClrDebugState = GetClrDebugState();
if (m_pClrDebugState)
{
m_oldDebugOnlyValue = m_pClrDebugState->IsDebugOnly();
m_pClrDebugState->SetDebugOnly();
}
}
DEBUG_NOINLINE void Leave()
{
SCAN_SCOPE_END;
STATIC_CONTRACT_DEBUG_ONLY;
m_pClrDebugState = CheckClrDebugState();
if (m_pClrDebugState)
{
m_pClrDebugState->SetDebugOnly( m_oldDebugOnlyValue );
}
}
private:
BOOL m_oldDebugOnlyValue;
ClrDebugState *m_pClrDebugState;
};
#define ENTER_DEBUG_ONLY_CODE \
DebugOnlyCodeHolder __debugOnlyCodeHolder; \
__debugOnlyCodeHolder.Enter();
#define LEAVE_DEBUG_ONLY_CODE \
__debugOnlyCodeHolder.Leave();
class AutoCleanupDebugOnlyCodeHolder : public DebugOnlyCodeHolder
{
public:
DEBUG_NOINLINE AutoCleanupDebugOnlyCodeHolder()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_DEBUG_ONLY;
Enter();
};
DEBUG_NOINLINE ~AutoCleanupDebugOnlyCodeHolder()
{
SCAN_SCOPE_END;
Leave();
};
};
#define DEBUG_ONLY_FUNCTION \
STATIC_CONTRACT_DEBUG_ONLY; \
AutoCleanupDebugOnlyCodeHolder __debugOnlyCodeHolder;
#define DEBUG_ONLY_REGION() \
AutoCleanupDebugOnlyCodeHolder __debugOnlyCodeHolder;
#define BEGIN_DEBUG_ONLY_CODE \
{ \
AutoCleanupDebugOnlyCodeHolder __debugOnlyCodeHolder;
#define END_DEBUG_ONLY_CODE \
}
#else // ENABLE_CONTRACTS_IMPL
#define DEBUG_ONLY_FUNCTION STATIC_CONTRACT_DEBUG_ONLY
#define DEBUG_ONLY_REGION()
#define BEGIN_DEBUG_ONLY_CODE
#define END_DEBUG_ONLY_CODE
#define ENTER_DEBUG_ONLY_CODE
#define LEAVE_DEBUG_ONLY_CODE
#endif
#else // _DEBUG
#define DEBUG_ONLY_REGION()
#endif
#ifdef ENABLE_CONTRACTS_IMPL
// These helpers encapsulate our access to our FLS debug state. To improve
// contract perf, we'll soon move these to a private alloced block
// so we can reuse the pointer instead of constantly refetching it.
// Thus, these helpers are just to bridge this transition.
inline LPVOID GetViolationMask()
{
ClrDebugState *pState = CheckClrDebugState();
if (pState)
{
return (LPVOID)pState->ViolationMask();
}
else
{
return 0;
}
}
// This is the default binding of the MAYBETEMPLATE identifier,
// used in the RETURN macro
template <int DUMMY>
class ___maybetemplate
{
public:
FORCEINLINE void *operator new (size_t size)
{
return NULL;
}
};
// This is an abstract base class for contracts. The main reason we have this is so that the dtor for many derived class can
// be performant. If this class was not abstract and had a dtor, then the dtor for the derived class adds EH overhead (even if the derived
// class did not anything special in its dtor)
class BaseContract
{
// Really private, but used by macros
public:
// We use a single integer to specify all the settings for intrinsic tests
// such as THROWS and GC_TRIGGERS. The compiler should be able to fold all
// these clauses into a single constant.
//
// The value "0" is significant as this is what the entire mask will be initialized to
// in the absence of any clauses. Hence, whichever value is assigned "0" will be the
// default setting for the test.
//
// Also, there must be a "disabled" setting for each category in order to support
// the DISABLED macro.
enum TestEnum
{
THROWS_Mask = 0x00000003,
THROWS_Yes = 0x00000000, // the default
THROWS_No = 0x00000001,
THROWS_Disabled = 0x00000002,
GC_Mask = 0x0000000C,
GC_Triggers = 0x00000000, // the default
GC_NoTrigger = 0x00000004,
GC_Disabled = 0x00000008,
FAULT_Mask = 0x00000030,
FAULT_Disabled = 0x00000000, // the default
FAULT_Inject = 0x00000010,
FAULT_Forbid = 0x00000020,
MODE_Mask = 0x000000C0,
MODE_Disabled = 0x00000000, // the default
MODE_Preempt = 0x00000040,
MODE_Coop = 0x00000080,
DEBUG_ONLY_Yes = 0x00000400, // code runs under debug only
SO_MAINLINE_No = 0x00000800, // code is not part of our mainline SO scenario
// Any place where we can't safely call into the host should have a HOST_NoCalls contract
HOST_Mask = 0x00003000,
HOST_Calls = 0x00002000,
HOST_NoCalls = 0x00001000,
HOST_Disabled = 0x00000000, // the default
// This enforces the EE_THREAD_NOT_REQUIRED contract by clearing
// ClrDebugState::m_allowGetThread in its scope. That causes raw calls
// to GetThread() to assert, unless inside a temporary "don't worry it's ok" scope
// via BEGIN/END_GETTHREAD_ALLOWED. Useful for enforcing our docs that
// state certain unmanaged API entrypoints (e.g., some from profiling API)
// are callable without an EE Thread in TLS.
EE_THREAD_Mask = 0x0000C000,
EE_THREAD_Disabled = 0x00000000, // the default
EE_THREAD_Required = 0x00004000,
EE_THREAD_Not_Required = 0x00008000,
// These enforce the CAN_TAKE_LOCK / CANNOT_TAKE_LOCK contracts
CAN_TAKE_LOCK_Mask = 0x00060000,
CAN_TAKE_LOCK_Yes = 0x00020000,
CAN_TAKE_LOCK_No = 0x00040000,
CAN_TAKE_LOCK_Disabled = 0x00000000, // the default
// These enforce the CANNOT_RETAKE_LOCK contract
CAN_RETAKE_LOCK_No = 0x00080000,
CAN_RETAKE_LOCK_No_Disabled = 0x00000000, // the default
PRECONDITION_Used = 0x00010000, // a PRECONDITION appeared inside the contract
// IMPORTANT!!! LOADS_TYPE_Mask and LOADS_TYPE_Shift must be kept in sync.
LOADS_TYPE_Mask = 0x00f00000, // the max loadstype level + 1 ("+1" because 0 is reserved for the default which is "disabled")
LOADS_TYPE_Shift = 20, // # of bits to right-shift to get loadstype bits to rightmost position.
LOADS_TYPE_Disabled = 0x00000000, // the default
ALL_Disabled = THROWS_Disabled|GC_Disabled|FAULT_Disabled|MODE_Disabled|LOADS_TYPE_Disabled|
HOST_Disabled|EE_THREAD_Disabled|CAN_TAKE_LOCK_Disabled|CAN_RETAKE_LOCK_No_Disabled
};
enum Operation
{
Setup = 0x01,
Preconditions = 0x02,
Postconditions = 0x04,
};
NOTHROW_DECL BaseContract() : m_pClrDebugState(NULL), m_testmask(0)
{
}
NOTHROW_DECL void Restore()
{
// m_pClrDebugState is setup in BaseContract::DoChecks. If an SO happens after the
// BaseContract object is constructed but before DoChecks is invoked, m_pClrDebugState
// will remain NULL (which is what it is set to in the BaseContract ctor).
//
// Thus, we should check for it being NULL before dereferencing it.