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
/
syncblk.h
1569 lines (1287 loc) · 48.5 KB
/
syncblk.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.
//
// SYNCBLK.H
//
//
// Definition of a SyncBlock and the SyncBlockCache which manages it
// See file:#SyncBlockOverview Sync block overview
#ifndef _SYNCBLK_H_
#define _SYNCBLK_H_
#include "util.hpp"
#include "slist.h"
#include "crst.h"
#include "vars.hpp"
// #SyncBlockOverview
//
// Every Object is preceded by an ObjHeader (at a negative offset). The code:ObjHeader has an index to a
// code:SyncBlock. This index is 0 for the bulk of all instances, which indicates that the object shares a
// dummy SyncBlock with most other objects.
//
// The SyncBlock is primarily responsible for object synchronization. However, it is also a "kitchen sink" of
// sparsely allocated instance data. For instance, the default implementation of Hash() is based on the
// existence of a code:SyncTableEntry. And objects exposed to or from COM, or through context boundaries, can
// store sparse data here.
//
// SyncTableEntries and SyncBlocks are allocated in non-GC memory. A weak pointer from the SyncTableEntry to
// the instance is used to ensure that the SyncBlock and SyncTableEntry are reclaimed (recycled) when the
// instance dies.
//
// The organization of the SyncBlocks isn't intuitive (at least to me). Here's the explanation:
//
// Before each Object is an code:ObjHeader. If the object has a code:SyncBlock, the code:ObjHeader contains a
// non-0 index to it.
//
// The index is looked up in the code:g_pSyncTable of SyncTableEntries. This means the table is consecutive
// for all outstanding indices. Whenever it needs to grow, it doubles in size and copies all the original
// entries. The old table is kept until GC time, when it can be safely discarded.
//
// Each code:SyncTableEntry has a backpointer to the object and a forward pointer to the actual SyncBlock.
// The SyncBlock is allocated out of a SyncBlockArray which is essentially just a block of SyncBlocks.
//
// The code:SyncBlockArray s are managed by a code:SyncBlockCache that handles the actual allocations and
// frees of the blocks.
//
// So...
//
// Each allocation and release has to handle free lists in the table of entries and the table of blocks.
//
// We burn an extra 4 bytes for the pointer from the SyncTableEntry to the SyncBlock.
//
// The reason for this is that many objects have a SyncTableEntry but no SyncBlock. That's because someone
// (e.g. HashTable) called Hash() on them.
//
// Incidentally, there's a better write-up of all this stuff in the archives.
#ifdef _TARGET_X86_
#include <pshpack4.h>
#endif // _TARGET_X86_
// forwards:
class SyncBlock;
class SyncBlockCache;
class SyncTableEntry;
class SyncBlockArray;
class AwareLock;
class Thread;
class AppDomain;
#ifdef EnC_SUPPORTED
class EnCSyncBlockInfo;
typedef DPTR(EnCSyncBlockInfo) PTR_EnCSyncBlockInfo;
#endif // EnC_SUPPORTED
#include "eventstore.hpp"
#include "eventstore.hpp"
#include "synch.h"
// At a negative offset from each Object is an ObjHeader. The 'size' of the
// object includes these bytes. However, we rely on the previous object allocation
// to zero out the ObjHeader for the current allocation. And the limits of the
// GC space are initialized to respect this "off by one" error.
// m_SyncBlockValue is carved up into an index and a set of bits. Steal bits by
// reducing the mask. We use the very high bit, in _DEBUG, to be sure we never forget
// to mask the Value to obtain the Index
#define BIT_SBLK_UNUSED 0x80000000
#define BIT_SBLK_FINALIZER_RUN 0x40000000
#define BIT_SBLK_GC_RESERVE 0x20000000
// This lock is only taken when we need to modify the index value in m_SyncBlockValue.
// It should not be taken if the object already has a real syncblock index.
#define BIT_SBLK_SPIN_LOCK 0x10000000
#define BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX 0x08000000
// if BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX is clear, the rest of the header dword is layed out as follows:
// - lower ten bits (bits 0 thru 9) is thread id used for the thin locks
// value is zero if no thread is holding the lock
// - following six bits (bits 10 thru 15) is recursion level used for the thin locks
// value is zero if lock is not taken or only taken once by the same thread
#define SBLK_MASK_LOCK_THREADID 0x000003FF // special value of 0 + 1023 thread ids
#define SBLK_MASK_LOCK_RECLEVEL 0x0000FC00 // 64 recursion levels
#define SBLK_LOCK_RECLEVEL_INC 0x00000400 // each level is this much higher than the previous one
#define SBLK_RECLEVEL_SHIFT 10 // shift right this much to get recursion level
// add more bits here... (adjusting the following mask to make room)
// if BIT_SBLK_IS_HASH_OR_SYNCBLKINDEX is set,
// then if BIT_SBLK_IS_HASHCODE is also set, the rest of the dword is the hash code (bits 0 thru 25),
// otherwise the rest of the dword is the sync block index (bits 0 thru 25)
#define BIT_SBLK_IS_HASHCODE 0x04000000
#define HASHCODE_BITS 26
#define MASK_HASHCODE ((1<<HASHCODE_BITS)-1)
#define SYNCBLOCKINDEX_BITS 26
#define MASK_SYNCBLOCKINDEX ((1<<SYNCBLOCKINDEX_BITS)-1)
// Spin for about 1000 cycles before waiting longer.
#define BIT_SBLK_SPIN_COUNT 1000
// The GC is highly dependent on SIZE_OF_OBJHEADER being exactly the sizeof(ObjHeader)
// We define this macro so that the preprocessor can calculate padding structures.
#ifdef BIT64
#define SIZEOF_OBJHEADER 8
#else // !BIT64
#define SIZEOF_OBJHEADER 4
#endif // !BIT64
inline void InitializeSpinConstants()
{
WRAPPER_NO_CONTRACT;
#if !defined(DACCESS_COMPILE)
g_SpinConstants.dwInitialDuration = g_pConfig->SpinInitialDuration();
g_SpinConstants.dwMaximumDuration = min(g_pConfig->SpinLimitProcCap(), g_SystemInfo.dwNumberOfProcessors) * g_pConfig->SpinLimitProcFactor() + g_pConfig->SpinLimitConstant();
g_SpinConstants.dwBackoffFactor = g_pConfig->SpinBackoffFactor();
g_SpinConstants.dwRepetitions = g_pConfig->SpinRetryCount();
g_SpinConstants.dwMonitorSpinCount = g_SpinConstants.dwMaximumDuration == 0 ? 0 : g_pConfig->MonitorSpinCount();
#endif
}
// this is a 'GC-aware' Lock. It is careful to enable preemptive GC before it
// attempts any operation that can block. Once the operation is finished, it
// restores the original state of GC.
// AwareLocks can only be created inside SyncBlocks, since they depend on the
// enclosing SyncBlock for coordination. This is enforced by the private ctor.
typedef DPTR(class AwareLock) PTR_AwareLock;
class AwareLock
{
friend class CheckAsmOffsets;
friend class SyncBlockCache;
friend class SyncBlock;
public:
enum EnterHelperResult {
EnterHelperResult_Entered,
EnterHelperResult_Contention,
EnterHelperResult_UseSlowPath
};
enum LeaveHelperAction {
LeaveHelperAction_None,
LeaveHelperAction_Signal,
LeaveHelperAction_Yield,
LeaveHelperAction_Contention,
LeaveHelperAction_Error,
};
private:
class LockState
{
private:
// Layout constants for m_state
static const UINT32 IsLockedMask = (UINT32)1 << 0; // bit 0
static const UINT32 ShouldNotPreemptWaitersMask = (UINT32)1 << 1; // bit 1
static const UINT32 SpinnerCountIncrement = (UINT32)1 << 2;
static const UINT32 SpinnerCountMask = (UINT32)0x7 << 2; // bits 2-4
static const UINT32 IsWaiterSignaledToWakeMask = (UINT32)1 << 5; // bit 5
static const UINT8 WaiterCountShift = 6;
static const UINT32 WaiterCountIncrement = (UINT32)1 << WaiterCountShift;
static const UINT32 WaiterCountMask = (UINT32)-1 >> WaiterCountShift << WaiterCountShift; // bits 6-31
private:
UINT32 m_state;
public:
LockState(UINT32 state = 0) : m_state(state)
{
LIMITED_METHOD_CONTRACT;
}
public:
UINT32 GetState() const
{
LIMITED_METHOD_CONTRACT;
return m_state;
}
UINT32 GetMonitorHeldState() const
{
LIMITED_METHOD_CONTRACT;
static_assert_no_msg(IsLockedMask == 1);
static_assert_no_msg(WaiterCountShift >= 1);
// Return only the locked state and waiter count in the previous (m_MonitorHeld) layout for the debugger:
// bit 0: 1 if locked, 0 otherwise
// bits 1-31: waiter count
UINT32 state = m_state;
return (state & IsLockedMask) + (state >> WaiterCountShift << 1);
}
public:
bool IsUnlockedWithNoWaiters() const
{
LIMITED_METHOD_CONTRACT;
return !(m_state & (IsLockedMask + WaiterCountMask));
}
void InitializeToLockedWithNoWaiters()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!m_state);
m_state = IsLockedMask;
}
public:
bool IsLocked() const
{
LIMITED_METHOD_CONTRACT;
return !!(m_state & IsLockedMask);
}
private:
void InvertIsLocked()
{
LIMITED_METHOD_CONTRACT;
m_state ^= IsLockedMask;
}
public:
bool ShouldNotPreemptWaiters() const
{
LIMITED_METHOD_CONTRACT;
return !!(m_state & ShouldNotPreemptWaitersMask);
}
private:
void InvertShouldNotPreemptWaiters()
{
WRAPPER_NO_CONTRACT;
m_state ^= ShouldNotPreemptWaitersMask;
_ASSERTE(!ShouldNotPreemptWaiters() || HasAnyWaiters());
}
bool ShouldNonWaiterAttemptToAcquireLock() const
{
WRAPPER_NO_CONTRACT;
_ASSERTE(!ShouldNotPreemptWaiters() || HasAnyWaiters());
return !(m_state & (IsLockedMask + ShouldNotPreemptWaitersMask));
}
public:
bool HasAnySpinners() const
{
LIMITED_METHOD_CONTRACT;
return !!(m_state & SpinnerCountMask);
}
private:
bool TryIncrementSpinnerCount()
{
WRAPPER_NO_CONTRACT;
LockState newState = m_state + SpinnerCountIncrement;
if (newState.HasAnySpinners()) // overflow check
{
m_state = newState;
return true;
}
return false;
}
void DecrementSpinnerCount()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(HasAnySpinners());
m_state -= SpinnerCountIncrement;
}
public:
bool IsWaiterSignaledToWake() const
{
LIMITED_METHOD_CONTRACT;
return !!(m_state & IsWaiterSignaledToWakeMask);
}
private:
void InvertIsWaiterSignaledToWake()
{
LIMITED_METHOD_CONTRACT;
m_state ^= IsWaiterSignaledToWakeMask;
}
public:
bool HasAnyWaiters() const
{
LIMITED_METHOD_CONTRACT;
return m_state >= WaiterCountIncrement;
}
private:
void IncrementWaiterCount()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_state + WaiterCountIncrement >= WaiterCountIncrement);
m_state += WaiterCountIncrement;
}
void DecrementWaiterCount()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(HasAnyWaiters());
m_state -= WaiterCountIncrement;
}
private:
bool NeedToSignalWaiter() const
{
WRAPPER_NO_CONTRACT;
return HasAnyWaiters() && !(m_state & (SpinnerCountMask + IsWaiterSignaledToWakeMask));
}
private:
operator UINT32() const
{
LIMITED_METHOD_CONTRACT;
return m_state;
}
LockState &operator =(UINT32 state)
{
LIMITED_METHOD_CONTRACT;
m_state = state;
return *this;
}
public:
LockState VolatileLoadWithoutBarrier() const
{
WRAPPER_NO_CONTRACT;
return ::VolatileLoadWithoutBarrier(&m_state);
}
LockState VolatileLoad() const
{
WRAPPER_NO_CONTRACT;
return ::VolatileLoad(&m_state);
}
private:
LockState CompareExchange(LockState toState, LockState fromState)
{
LIMITED_METHOD_CONTRACT;
return (UINT32)InterlockedCompareExchange((LONG *)&m_state, (LONG)toState, (LONG)fromState);
}
LockState CompareExchangeAcquire(LockState toState, LockState fromState)
{
LIMITED_METHOD_CONTRACT;
return (UINT32)InterlockedCompareExchangeAcquire((LONG *)&m_state, (LONG)toState, (LONG)fromState);
}
public:
bool InterlockedTryLock();
bool InterlockedTryLock(LockState state);
bool InterlockedUnlock();
bool InterlockedTrySetShouldNotPreemptWaitersIfNecessary(AwareLock *awareLock);
bool InterlockedTrySetShouldNotPreemptWaitersIfNecessary(AwareLock *awareLock, LockState state);
EnterHelperResult InterlockedTry_LockOrRegisterSpinner(LockState state);
EnterHelperResult InterlockedTry_LockAndUnregisterSpinner();
bool InterlockedUnregisterSpinner_TryLock();
bool InterlockedTryLock_Or_RegisterWaiter(AwareLock *awareLock, LockState state);
void InterlockedUnregisterWaiter();
bool InterlockedTry_LockAndUnregisterWaiterAndObserveWakeSignal(AwareLock *awareLock);
bool InterlockedObserveWakeSignal_Try_LockAndUnregisterWaiter(AwareLock *awareLock);
};
friend class LockState;
private:
// Take care to use 'm_lockState.VolatileLoadWithoutBarrier()` when loading this value into a local variable that will be
// reused. That prevents an optimization in the compiler that avoids stack-spilling a value loaded from memory and instead
// reloads the value from the original memory location under the assumption that it would not be changed by another thread,
// which can result in the local variable's value changing between reads if the memory location is modifed by another
// thread. This is important for patterns such as:
//
// T x = m_x; // no barrier
// if (meetsCondition(x))
// {
// assert(meetsCondition(x)); // This may fail!
// }
//
// The code should be written like this instead:
//
// T x = VolatileLoadWithoutBarrier(&m_x); // compile-time barrier, no run-time barrier
// if (meetsCondition(x))
// {
// assert(meetsCondition(x)); // This will not fail
// }
LockState m_lockState;
ULONG m_Recursion;
PTR_Thread m_HoldingThread;
LONG m_TransientPrecious;
// This is a backpointer from the syncblock to the synctable entry. This allows
// us to recover the object that holds the syncblock.
DWORD m_dwSyncIndex;
CLREvent m_SemEvent;
DWORD m_waiterStarvationStartTimeMs;
static const DWORD WaiterStarvationDurationMsBeforeStoppingPreemptingWaiters = 100;
// Only SyncBlocks can create AwareLocks. Hence this private constructor.
AwareLock(DWORD indx)
: m_Recursion(0),
#ifndef DACCESS_COMPILE
// PreFAST has trouble with intializing a NULL PTR_Thread.
m_HoldingThread(NULL),
#endif // DACCESS_COMPILE
m_TransientPrecious(0),
m_dwSyncIndex(indx),
m_waiterStarvationStartTimeMs(0)
{
LIMITED_METHOD_CONTRACT;
}
~AwareLock()
{
LIMITED_METHOD_CONTRACT;
// We deliberately allow this to remain incremented if an exception blows
// through a lock attempt. This simply prevents the GC from aggressively
// reclaiming a particular syncblock until the associated object is garbage.
// From a perf perspective, it's not worth using SEH to prevent this from
// happening.
//
// _ASSERTE(m_TransientPrecious == 0);
}
#if defined(ENABLE_CONTRACTS_IMPL)
// The LOCK_TAKEN/RELEASED macros need a "pointer" to the lock object to do
// comparisons between takes & releases (and to provide debugging info to the
// developer). Since AwareLocks are always allocated embedded inside SyncBlocks,
// and since SyncBlocks don't move (unlike the GC objects that use
// the syncblocks), it's safe for us to just use the AwareLock pointer directly
void * GetPtrForLockContract()
{
return (void *) this;
}
#endif // defined(ENABLE_CONTRACTS_IMPL)
public:
UINT32 GetLockState() const
{
WRAPPER_NO_CONTRACT;
return m_lockState.VolatileLoadWithoutBarrier().GetState();
}
bool IsUnlockedWithNoWaiters() const
{
WRAPPER_NO_CONTRACT;
return m_lockState.VolatileLoadWithoutBarrier().IsUnlockedWithNoWaiters();
}
UINT32 GetMonitorHeldStateVolatile() const
{
WRAPPER_NO_CONTRACT;
return m_lockState.VolatileLoad().GetMonitorHeldState();
}
ULONG GetRecursionLevel() const
{
LIMITED_METHOD_CONTRACT;
return m_Recursion;
}
PTR_Thread GetHoldingThread() const
{
LIMITED_METHOD_CONTRACT;
return m_HoldingThread;
}
private:
void ResetWaiterStarvationStartTime();
void RecordWaiterStarvationStartTime();
bool ShouldStopPreemptingWaiters() const;
private: // friend access is required for this unsafe function
void InitializeToLockedWithNoWaiters(ULONG recursionLevel, PTR_Thread holdingThread)
{
WRAPPER_NO_CONTRACT;
m_lockState.InitializeToLockedWithNoWaiters();
m_Recursion = recursionLevel;
m_HoldingThread = holdingThread;
}
public:
static void SpinWait(const YieldProcessorNormalizationInfo &normalizationInfo, DWORD spinIteration);
// Helper encapsulating the fast path entering monitor. Returns what kind of result was achieved.
bool TryEnterHelper(Thread* pCurThread);
EnterHelperResult TryEnterBeforeSpinLoopHelper(Thread *pCurThread);
EnterHelperResult TryEnterInsideSpinLoopHelper(Thread *pCurThread);
bool TryEnterAfterSpinLoopHelper(Thread *pCurThread);
// Helper encapsulating the core logic for leaving monitor. Returns what kind of
// follow up action is necessary
AwareLock::LeaveHelperAction LeaveHelper(Thread* pCurThread);
void Enter();
BOOL TryEnter(INT32 timeOut = 0);
BOOL EnterEpilog(Thread *pCurThread, INT32 timeOut = INFINITE);
BOOL EnterEpilogHelper(Thread *pCurThread, INT32 timeOut);
BOOL Leave();
void Signal()
{
WRAPPER_NO_CONTRACT;
// CLREvent::SetMonitorEvent works even if the event has not been intialized yet
m_SemEvent.SetMonitorEvent();
m_lockState.InterlockedTrySetShouldNotPreemptWaitersIfNecessary(this);
}
void AllocLockSemEvent();
LONG LeaveCompletely();
BOOL OwnedByCurrentThread();
void IncrementTransientPrecious()
{
LIMITED_METHOD_CONTRACT;
FastInterlockIncrement(&m_TransientPrecious);
_ASSERTE(m_TransientPrecious > 0);
}
void DecrementTransientPrecious()
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(m_TransientPrecious > 0);
FastInterlockDecrement(&m_TransientPrecious);
}
DWORD GetSyncBlockIndex();
void SetPrecious();
// Provide access to the object associated with this awarelock, so client can
// protect it.
inline OBJECTREF GetOwningObject();
// Provide access to the Thread object that owns this awarelock. This is used
// to provide a host to find out owner of a lock.
inline PTR_Thread GetOwningThread()
{
LIMITED_METHOD_CONTRACT;
return m_HoldingThread;
}
};
#ifdef FEATURE_COMINTEROP
class ComCallWrapper;
class ComClassFactory;
struct RCW;
class RCWHolder;
typedef DPTR(class ComCallWrapper) PTR_ComCallWrapper;
#endif // FEATURE_COMINTEROP
class InteropSyncBlockInfo
{
friend class RCWHolder;
public:
#ifndef FEATURE_PAL
// List of InteropSyncBlockInfo instances that have been freed since the last syncblock cleanup.
static SLIST_HEADER s_InteropInfoStandbyList;
#endif // !FEATURE_PAL
InteropSyncBlockInfo()
{
LIMITED_METHOD_CONTRACT;
ZeroMemory(this, sizeof(InteropSyncBlockInfo));
}
#ifndef DACCESS_COMPILE
~InteropSyncBlockInfo();
#endif
#ifndef FEATURE_PAL
// Deletes all items in code:s_InteropInfoStandbyList.
static void FlushStandbyList();
#endif // !FEATURE_PAL
#ifdef FEATURE_COMINTEROP
//
// We'll be using the sentinel value of 0x1 to indicate that a particular
// field was set at one time, but is now NULL.
#ifndef DACCESS_COMPILE
RCW* GetRawRCW()
{
LIMITED_METHOD_CONTRACT;
return (RCW *)((size_t)m_pRCW & ~1);
}
// Returns either NULL or an RCW on which AcquireLock has been called.
RCW* GetRCWAndIncrementUseCount();
// Sets the m_pRCW field in a thread-safe manner, pRCW can be NULL.
void SetRawRCW(RCW* pRCW);
bool RCWWasUsed()
{
LIMITED_METHOD_CONTRACT;
return (m_pRCW != NULL);
}
#else // !DACCESS_COMPILE
TADDR DacGetRawRCW()
{
return (TADDR)((size_t)m_pRCW & ~1);
}
#endif // DACCESS_COMPILE
#ifndef DACCESS_COMPILE
void SetCCW(ComCallWrapper* pCCW)
{
LIMITED_METHOD_CONTRACT;
if (pCCW == NULL)
pCCW = (ComCallWrapper*) 0x1;
m_pCCW = pCCW;
}
#endif // !DACCESS_COMPILE
PTR_ComCallWrapper GetCCW()
{
LIMITED_METHOD_DAC_CONTRACT;
if (m_pCCW == (PTR_ComCallWrapper)0x1)
return NULL;
return m_pCCW;
}
bool CCWWasUsed()
{
LIMITED_METHOD_CONTRACT;
if (m_pCCW == NULL)
return false;
return true;
}
#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
void SetComClassFactory(ComClassFactory* pCCF)
{
LIMITED_METHOD_CONTRACT;
if (pCCF == NULL)
pCCF = (ComClassFactory*)0x1;
m_pCCF = pCCF;
}
ComClassFactory* GetComClassFactory()
{
LIMITED_METHOD_CONTRACT;
if (m_pCCF == (ComClassFactory*)0x1)
return NULL;
return m_pCCF;
}
bool CCFWasUsed()
{
LIMITED_METHOD_CONTRACT;
if (m_pCCF == NULL)
return false;
return true;
}
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
#endif // FEATURE_COMINTEROP
#if !defined(DACCESS_COMPILE)
// set m_pUMEntryThunkOrInterceptStub if not already set - return true if not already set
bool SetUMEntryThunk(void* pUMEntryThunk)
{
WRAPPER_NO_CONTRACT;
return (FastInterlockCompareExchangePointer(&m_pUMEntryThunkOrInterceptStub,
pUMEntryThunk,
NULL) == NULL);
}
// set m_pUMEntryThunkOrInterceptStub if not already set - return true if not already set
bool SetInterceptStub(Stub* pInterceptStub)
{
WRAPPER_NO_CONTRACT;
void *pPtr = (void *)((UINT_PTR)pInterceptStub | 1);
return (FastInterlockCompareExchangePointer(&m_pUMEntryThunkOrInterceptStub,
pPtr,
NULL) == NULL);
}
void FreeUMEntryThunkOrInterceptStub();
#endif // DACCESS_COMPILE
void* GetUMEntryThunk()
{
LIMITED_METHOD_CONTRACT;
return (((UINT_PTR)m_pUMEntryThunkOrInterceptStub & 1) ? NULL : m_pUMEntryThunkOrInterceptStub);
}
Stub* GetInterceptStub()
{
LIMITED_METHOD_CONTRACT;
return (((UINT_PTR)m_pUMEntryThunkOrInterceptStub & 1) ? (Stub *)((UINT_PTR)m_pUMEntryThunkOrInterceptStub & ~1) : NULL);
}
private:
// If this is a delegate marshalled out to unmanaged code, this points
// to the thunk generated for unmanaged code to call back on.
// If this is a delegate representing an unmanaged function pointer,
// this may point to a stub that intercepts calls to the unmng target.
// An example of an intercept call is pInvokeStackImbalance MDA.
// We differentiate between a thunk or intercept stub by setting the lowest
// bit if it is an intercept stub.
void* m_pUMEntryThunkOrInterceptStub;
#ifdef FEATURE_COMINTEROP
// If this object is being exposed to COM, it will have an associated CCW object
PTR_ComCallWrapper m_pCCW;
#ifdef FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
// If this object represents a type object, it will have an associated class factory
ComClassFactory* m_pCCF;
#endif // FEATURE_COMINTEROP_UNMANAGED_ACTIVATION
public:
#ifndef DACCESS_COMPILE
// If this is a __ComObject, it will have an associated RCW object
RCW* m_pRCW;
#else
// We can't define this as PTR_RCW, as this would create a typedef cycle. Use TADDR
// instead.
TADDR m_pRCW;
#endif
#endif // FEATURE_COMINTEROP
};
typedef DPTR(InteropSyncBlockInfo) PTR_InteropSyncBlockInfo;
// this is a lazily created additional block for an object which contains
// synchronzation information and other "kitchen sink" data
typedef DPTR(SyncBlock) PTR_SyncBlock;
// See code:#SyncBlockOverview for more
class SyncBlock
{
// ObjHeader creates our Mutex and Event
friend class ObjHeader;
friend class SyncBlockCache;
friend struct ThreadQueue;
#ifdef DACCESS_COMPILE
friend class ClrDataAccess;
#endif
friend class CheckAsmOffsets;
protected:
AwareLock m_Monitor; // the actual monitor
public:
// If this object is exposed to unmanaged code, we keep some extra info here.
PTR_InteropSyncBlockInfo m_pInteropInfo;
protected:
#ifdef EnC_SUPPORTED
// And if the object has new fields added via EnC, this is a list of them
PTR_EnCSyncBlockInfo m_pEnCInfo;
#endif // EnC_SUPPORTED
// We thread two different lists through this link. When the SyncBlock is
// active, we create a list of waiting threads here. When the SyncBlock is
// released (we recycle them), the SyncBlockCache maintains a free list of
// SyncBlocks here.
//
// We can't afford to use an SList<> here because we only want to burn
// space for the minimum, which is the pointer within an SLink.
SLink m_Link;
// This is the hash code for the object. It can either have been transfered
// from the header dword, in which case it will be limited to 26 bits, or
// have been generated right into this member variable here, when it will
// be a full 32 bits.
// A 0 in this variable means no hash code has been set yet - this saves having
// another flag to express this state, and it enables us to use a 32-bit interlocked
// operation to set the hash code, on the other hand it means that hash codes
// can never be 0. ObjectNative::GetHashCode in COMObject.cpp makes sure to enforce this.
DWORD m_dwHashCode;
// In some early version of VB when there were no arrays developers used to use BSTR as arrays
// The way this was done was by adding a trail byte at the end of the BSTR
// To support this scenario, we need to use the sync block for this special case and
// save the trail character in here.
// This stores the trail character when a BSTR is used as an array
WCHAR m_BSTRTrailByte;
public:
SyncBlock(DWORD indx)
: m_Monitor(indx)
#ifdef EnC_SUPPORTED
, m_pEnCInfo(PTR_NULL)
#endif // EnC_SUPPORTED
, m_dwHashCode(0)
, m_BSTRTrailByte(0)
{
LIMITED_METHOD_CONTRACT;
m_pInteropInfo = NULL;
// The monitor must be 32-bit aligned for atomicity to be guaranteed.
_ASSERTE((((size_t) &m_Monitor) & 3) == 0);
}
DWORD GetSyncBlockIndex()
{
LIMITED_METHOD_CONTRACT;
return m_Monitor.GetSyncBlockIndex();
}
// As soon as a syncblock acquires some state that cannot be recreated, we latch
// a bit.
void SetPrecious()
{
WRAPPER_NO_CONTRACT;
m_Monitor.SetPrecious();
}
BOOL IsPrecious()
{
LIMITED_METHOD_CONTRACT;
return (m_Monitor.m_dwSyncIndex & SyncBlockPrecious) != 0;
}
// True is the syncblock and its index are disposable.
// If new members are added to the syncblock, this
// method needs to be modified accordingly
BOOL IsIDisposable()
{
WRAPPER_NO_CONTRACT;
return (!IsPrecious() &&
m_Monitor.IsUnlockedWithNoWaiters() &&
m_Monitor.m_TransientPrecious == 0);
}
// Gets the InteropInfo block, creates a new one if none is present.
InteropSyncBlockInfo* GetInteropInfo()
{
CONTRACT (InteropSyncBlockInfo*)
{
THROWS;
GC_TRIGGERS;
MODE_ANY;
POSTCONDITION(CheckPointer(RETVAL));
}
CONTRACT_END;
if (!m_pInteropInfo)
{
NewHolder<InteropSyncBlockInfo> pInteropInfo;
#ifndef FEATURE_PAL
pInteropInfo = (InteropSyncBlockInfo *)InterlockedPopEntrySList(&InteropSyncBlockInfo::s_InteropInfoStandbyList);
if (pInteropInfo != NULL)
{
// cache hit - reinitialize the data structure
new (pInteropInfo) InteropSyncBlockInfo();
}
else
#endif // !FEATURE_PAL
{
pInteropInfo = new InteropSyncBlockInfo();
}
if (SetInteropInfo(pInteropInfo))
pInteropInfo.SuppressRelease();
}
RETURN m_pInteropInfo;
}
PTR_InteropSyncBlockInfo GetInteropInfoNoCreate()
{
CONTRACT (PTR_InteropSyncBlockInfo)
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SUPPORTS_DAC;
POSTCONDITION(CheckPointer(RETVAL, NULL_OK));
}
CONTRACT_END;
RETURN m_pInteropInfo;
}
// Returns false if the InteropInfo block was already set - does not overwrite the previous value.
// True if the InteropInfo block was successfully set with the passed in value.
bool SetInteropInfo(InteropSyncBlockInfo* pInteropInfo);
#ifdef EnC_SUPPORTED
// Get information about fields added to this object by the Debugger's Edit and Continue support
PTR_EnCSyncBlockInfo GetEnCInfo()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pEnCInfo;
}
// Store information about fields added to this object by the Debugger's Edit and Continue support
void SetEnCInfo(EnCSyncBlockInfo *pEnCInfo);
#endif // EnC_SUPPORTED
DWORD GetHashCode()
{
LIMITED_METHOD_CONTRACT;
return m_dwHashCode;
}
DWORD SetHashCode(DWORD hashCode)
{
WRAPPER_NO_CONTRACT;
DWORD result = FastInterlockCompareExchange((LONG*)&m_dwHashCode, hashCode, 0);
if (result == 0)
{
// the sync block now holds a hash code, which we can't afford to lose.
SetPrecious();
return hashCode;
}
else
return result;
}
void *operator new (size_t sz, void* p)
{
LIMITED_METHOD_CONTRACT;
return p ;
}
void operator delete(void *p)
{
LIMITED_METHOD_CONTRACT;
// We've already destructed. But retain the memory.
}
void EnterMonitor()
{