forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebugger.cpp
16708 lines (13911 loc) · 550 KB
/
debugger.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.
//*****************************************************************************
// File: debugger.cpp
//
//
// Debugger runtime controller routines.
//
//*****************************************************************************
#include "stdafx.h"
#include "debugdebugger.h"
#include "../inc/common.h"
#include "eeconfig.h" // This is here even for retail & free builds...
#include "../../dlls/mscorrc/resource.h"
#include "vars.hpp"
#include <limits.h>
#include "ilformatter.h"
#include "typeparse.h"
#include "debuginfostore.h"
#include "generics.h"
#include "../../vm/methoditer.h"
#include "../../vm/encee.h"
#include "../../vm/dwreport.h"
#include "../../vm/eepolicy.h"
#include "../../vm/excep.h"
#if defined(FEATURE_DBGIPC_TRANSPORT_VM)
#include "dbgtransportsession.h"
#endif // FEATURE_DBGIPC_TRANSPORT_VM
#ifdef TEST_DATA_CONSISTENCY
#include "datatest.h"
#endif // TEST_DATA_CONSISTENCY
#include "dbgenginemetrics.h"
#include "../../vm/rejit.h"
#include "threadsuspend.h"
#ifdef DEBUGGING_SUPPORTED
#ifdef _DEBUG
// Reg key. We can set this and then any debugger-lazy-init code will assert.
// This helps track down places where we're caching in debugger stuff in a
// non-debugger scenario.
bool g_DbgShouldntUseDebugger = false;
#endif
/* ------------------------------------------------------------------------ *
* Global variables
* ------------------------------------------------------------------------ */
GPTR_IMPL(Debugger, g_pDebugger);
GPTR_IMPL(EEDebugInterface, g_pEEInterface);
SVAL_IMPL_INIT(BOOL, Debugger, s_fCanChangeNgenFlags, TRUE);
// This is a public export so debuggers can read and determine if the coreclr
// process is waiting for JIT debugging attach.
GVAL_IMPL_INIT(ULONG, CLRJitAttachState, 0);
// The following instances are used for invoking overloaded new/delete
InteropSafe interopsafe;
#ifndef DACCESS_COMPILE
DebuggerRCThread *g_pRCThread = NULL;
#ifndef _PREFAST_
// Do some compile time checking on the events in DbgIpcEventTypes.h
// No one ever calls this. But the compiler should still compile it,
// and that should be sufficient.
void DoCompileTimeCheckOnDbgIpcEventTypes()
{
_ASSERTE(!"Don't call this function. It just does compile time checking\n");
// We use the C_ASSERT macro here to get a compile-time assert.
// Make sure we don't have any duplicate numbers.
// The switch statements in the main loops won't always catch this
// since we may not switch on all events.
// store Type-0 in const local vars, so we can use them for bounds checking
// Create local vars with the val from Type1 & Type2. If there are any
// collisions, then the variables' names will collide at compile time.
#define IPC_EVENT_TYPE0(type, val) const int e_##type = val;
#define IPC_EVENT_TYPE1(type, val) int T_##val; T_##val = 0;
#define IPC_EVENT_TYPE2(type, val) int T_##val; T_##val = 0;
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
// Ensure that all identifiers are unique and are matched with
// integer values.
#define IPC_EVENT_TYPE0(type, val) int T2_##type; T2_##type = val;
#define IPC_EVENT_TYPE1(type, val) int T2_##type; T2_##type = val;
#define IPC_EVENT_TYPE2(type, val) int T2_##type; T2_##type = val;
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
// Make sure all values are subset of the bits specified by DB_IPCE_TYPE_MASK
#define IPC_EVENT_TYPE0(type, val)
#define IPC_EVENT_TYPE1(type, val) C_ASSERT((val & e_DB_IPCE_TYPE_MASK) == val);
#define IPC_EVENT_TYPE2(type, val) C_ASSERT((val & e_DB_IPCE_TYPE_MASK) == val);
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
// Make sure that no value is DB_IPCE_INVALID_EVENT
#define IPC_EVENT_TYPE0(type, val)
#define IPC_EVENT_TYPE1(type, val) C_ASSERT(val != e_DB_IPCE_INVALID_EVENT);
#define IPC_EVENT_TYPE2(type, val) C_ASSERT(val != e_DB_IPCE_INVALID_EVENT);
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
// Make sure first-last values are well structured.
static_assert_no_msg(e_DB_IPCE_RUNTIME_FIRST < e_DB_IPCE_RUNTIME_LAST);
static_assert_no_msg(e_DB_IPCE_DEBUGGER_FIRST < e_DB_IPCE_DEBUGGER_LAST);
// Make sure that event ranges don't overlap.
// This check is simplified because L->R events come before R<-L
static_assert_no_msg(e_DB_IPCE_RUNTIME_LAST < e_DB_IPCE_DEBUGGER_FIRST);
// Make sure values are in the proper ranges
// Type1 should be in the Runtime range, Type2 in the Debugger range.
#define IPC_EVENT_TYPE0(type, val)
#define IPC_EVENT_TYPE1(type, val) C_ASSERT((e_DB_IPCE_RUNTIME_FIRST <= val) && (val < e_DB_IPCE_RUNTIME_LAST));
#define IPC_EVENT_TYPE2(type, val) C_ASSERT((e_DB_IPCE_DEBUGGER_FIRST <= val) && (val < e_DB_IPCE_DEBUGGER_LAST));
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
// Make sure that events are in increasing order
// It's ok if the events skip numbers.
// This is a more specific check than the range check above.
/* Expands to look like this:
const bool f = (
first <=
10) && (10 <
11) && (11 <
12) && (12 <
last)
static_assert_no_msg(f);
*/
const bool f1 = (
(e_DB_IPCE_RUNTIME_FIRST <=
#define IPC_EVENT_TYPE0(type, val)
#define IPC_EVENT_TYPE1(type, val) val) && (val <
#define IPC_EVENT_TYPE2(type, val)
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
e_DB_IPCE_RUNTIME_LAST)
);
static_assert_no_msg(f1);
const bool f2 = (
(e_DB_IPCE_DEBUGGER_FIRST <=
#define IPC_EVENT_TYPE0(type, val)
#define IPC_EVENT_TYPE1(type, val)
#define IPC_EVENT_TYPE2(type, val) val) && (val <
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
e_DB_IPCE_DEBUGGER_LAST)
);
static_assert_no_msg(f2);
} // end checks
#endif // _PREFAST_
//-----------------------------------------------------------------------------
// Ctor for AtSafePlaceHolder
AtSafePlaceHolder::AtSafePlaceHolder(Thread * pThread)
{
_ASSERTE(pThread != NULL);
if (!g_pDebugger->IsThreadAtSafePlace(pThread))
{
m_pThreadAtUnsafePlace = pThread;
g_pDebugger->IncThreadsAtUnsafePlaces();
}
else
{
m_pThreadAtUnsafePlace = NULL;
}
}
//-----------------------------------------------------------------------------
// Dtor for AtSafePlaceHolder
AtSafePlaceHolder::~AtSafePlaceHolder()
{
Clear();
}
//-----------------------------------------------------------------------------
// Returns true if this adjusted the unsafe counter
bool AtSafePlaceHolder::IsAtUnsafePlace()
{
return m_pThreadAtUnsafePlace != NULL;
}
//-----------------------------------------------------------------------------
// Clear the holder.
// Notes:
// This can be called multiple times.
// Calling this makes the dtor a nop.
void AtSafePlaceHolder::Clear()
{
if (m_pThreadAtUnsafePlace != NULL)
{
// The thread is still at an unsafe place.
// We're clearing the flag to avoid the Dtor() calling DecThreads again.
m_pThreadAtUnsafePlace = NULL;
g_pDebugger->DecThreadsAtUnsafePlaces();
}
}
//-----------------------------------------------------------------------------
// Is the guard page missing on this thread?
// Should only be called for managed threads handling a managed exception.
// If we're handling a stack overflow (ie, missing guard page), then another
// stack overflow will instantly terminate the process. In that case, do stack
// intensive stuff on the helper thread (which has lots of stack space). Only
// problem is that if the faulting thread has a lock, the helper thread may
// get stuck.
// Serves as a hint whether we want to do a favor on the
// faulting thread (preferred) or the helper thread (if low stack).
// See whidbey issue 127436.
//-----------------------------------------------------------------------------
bool IsGuardPageGone()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
Thread * pThread = g_pEEInterface->GetThread();
// We're not going to be called for a unmanaged exception.
// Should always have a managed thread, but just in case something really
// strange happens, it's not worth an AV. (since this is just being used as a hint)
if (pThread == NULL)
{
return false;
}
// Don't use pThread->IsGuardPageGone(), it's not accurate here.
bool fGuardPageGone = (pThread->DetermineIfGuardPagePresent() == FALSE);
LOG((LF_CORDB, LL_INFO1000000, "D::IsGuardPageGone=%d\n", fGuardPageGone));
return fGuardPageGone;
}
//-----------------------------------------------------------------------------
// LSPTR_XYZ is a type-safe wrapper around an opaque reference type XYZ in the left-side.
// But TypeHandles are value-types that can't be directly converted into a pointer.
// Thus converting between LSPTR_XYZ and TypeHandles requires some extra glue.
// The following conversions are valid:
// LSPTR_XYZ <--> XYZ* (via Set/UnWrap methods)
// TypeHandle <--> void* (via AsPtr() and FromPtr()).
// so we can't directly convert between LSPTR_TYPEHANDLE and TypeHandle.
// We must do: TypeHandle <--> void* <--> XYZ <--> LSPTR_XYZ
// So LSPTR_TYPEHANDLE is actually for TypeHandleDummyPtr, and then we unsafe cast
// that to a void* to use w/ AsPtr() and FromPtr() to convert to TypeHandles.
// @todo- it would be nice to have these happen automatically w/ Set & UnWrap.
//-----------------------------------------------------------------------------
// helper class to do conversion above.
class TypeHandleDummyPtr
{
private:
TypeHandleDummyPtr() { }; // should never actually create this.
void * data;
};
// Convert: VMPTR_TYPEHANDLE --> TypeHandle
TypeHandle GetTypeHandle(VMPTR_TypeHandle ptr)
{
return TypeHandle::FromPtr(ptr.GetRawPtr());
}
// Convert: TypeHandle --> LSPTR_TYPEHANDLE
VMPTR_TypeHandle WrapTypeHandle(TypeHandle th)
{
return VMPTR_TypeHandle::MakePtr(reinterpret_cast<TypeHandle *> (th.AsPtr()));
}
extern void WaitForEndOfShutdown();
// Get the Canary structure which can sniff if the helper thread is safe to run.
HelperCanary * Debugger::GetCanary()
{
return g_pRCThread->GetCanary();
}
// IMPORTANT!!!!!
// Do not call Lock and Unlock directly. Because you might not unlock
// if exception takes place. Use DebuggerLockHolder instead!!!
// Only AcquireDebuggerLock can call directly.
//
void Debugger::DoNotCallDirectlyPrivateLock(void)
{
WRAPPER_NO_CONTRACT;
LOG((LF_CORDB,LL_INFO10000, "D::Lock acquire attempt by 0x%x\n",
GetCurrentThreadId()));
// Debugger lock is larger than both Controller & debugger-data locks.
// So we should never try to take the D lock if we hold either of the others.
// Lock becomes no-op in late shutdown.
if (g_fProcessDetach)
{
return;
}
//
// If the debugger has been disabled by the runtime, this means that it should block
// all threads that are trying to travel thru the debugger. We do this by blocking
// threads as they try and take the debugger lock.
//
if (m_fDisabled)
{
__SwitchToThread(INFINITE, CALLER_LIMITS_SPINNING);
_ASSERTE (!"Can not reach here");
}
m_mutex.Enter();
//
// If we were blocked on the lock and the debugging facilities got disabled
// while we were waiting, release the lock and park this thread.
//
if (m_fDisabled)
{
m_mutex.Leave();
__SwitchToThread(INFINITE, CALLER_LIMITS_SPINNING);
_ASSERTE (!"Can not reach here");
}
//
// Now check if we are in a shutdown case...
//
Thread * pThread;
bool fIsCooperative;
pThread = g_pEEInterface->GetThread();
fIsCooperative = (pThread != NULL) && (pThread->PreemptiveGCDisabled());
if (m_fShutdownMode && !fIsCooperative)
{
// The big fear is that some other random thread will take the debugger-lock and then block on something else,
// and thus prevent the helper/finalizer threads from taking the debugger-lock in shutdown scenarios.
//
// If we're in shutdown mode, then some locks (like the Thread-Store-Lock) get special semantics.
// Only helper / finalizer / shutdown threads can actually take these locks.
// Other threads that try to take them will just get parked and block forever.
// This is ok b/c the only threads that need to run at this point are the Finalizer and Helper threads.
//
// We need to be in preemptive to block for shutdown, so we don't do this block in Coop mode.
// Fortunately, it's safe to take this lock in coop mode because we know the thread can't block
// on anything interesting because we're in a GC-forbid region (see crst flags).
m_mutex.ReleaseAndBlockForShutdownIfNotSpecialThread();
}
#ifdef _DEBUG
_ASSERTE(m_mutexCount >= 0);
if (m_mutexCount>0)
{
if (pThread)
{
// mamaged thread
_ASSERTE(m_mutexOwner == GetThreadIdHelper(pThread));
}
else
{
// unmanaged thread
_ASSERTE(m_mutexOwner == GetCurrentThreadId());
}
}
m_mutexCount++;
if (pThread)
{
m_mutexOwner = GetThreadIdHelper(pThread);
}
else
{
// unmanaged thread
m_mutexOwner = GetCurrentThreadId();
}
if (m_mutexCount == 1)
{
LOG((LF_CORDB,LL_INFO10000, "D::Lock acquired by 0x%x\n", m_mutexOwner));
}
#endif
}
// See comment above.
// Only ReleaseDebuggerLock can call directly.
void Debugger::DoNotCallDirectlyPrivateUnlock(void)
{
WRAPPER_NO_CONTRACT;
// Controller lock is "smaller" than debugger lock.
if (!g_fProcessDetach)
{
#ifdef _DEBUG
if (m_mutexCount == 1)
LOG((LF_CORDB,LL_INFO10000, "D::Unlock released by 0x%x\n",
m_mutexOwner));
if(0 == --m_mutexCount)
m_mutexOwner = 0;
_ASSERTE( m_mutexCount >= 0);
#endif
m_mutex.Leave();
//
// If the debugger has been disabled by the runtime, this means that it should block
// all threads that are trying to travel thru the debugger. We do this by blocking
// threads also as they leave the debugger lock.
//
if (m_fDisabled)
{
__SwitchToThread(INFINITE, CALLER_LIMITS_SPINNING);
_ASSERTE (!"Can not reach here");
}
}
}
#ifdef TEST_DATA_CONSISTENCY
// ---------------------------------------------------------------------------------
// Implementations for DataTest member functions
// ---------------------------------------------------------------------------------
// Send an event to the RS to signal that it should test to determine if a crst is held.
// This is for testing purposes only.
// Arguments:
// input: pCrst - the lock to test
// fOkToTake - true iff the LS does NOT currently hold the lock
// output: none
// Notes: The RS will throw if the lock is held. The code that tests the lock will catch the
// exception and assert if throwing was not the correct thing to do (determined via the
// boolean). See the case for DB_IPCE_TEST_CRST in code:CordbProcess::RawDispatchEvent.
//
void DataTest::SendDbgCrstEvent(Crst * pCrst, bool fOkToTake)
{
DebuggerIPCEvent * pLockEvent = g_pDebugger->m_pRCThread->GetIPCEventSendBuffer();
g_pDebugger->InitIPCEvent(pLockEvent, DB_IPCE_TEST_CRST);
pLockEvent->TestCrstData.vmCrst.SetRawPtr(pCrst);
pLockEvent->TestCrstData.fOkToTake = fOkToTake;
g_pDebugger->SendRawEvent(pLockEvent);
} // DataTest::SendDbgCrstEvent
// Send an event to the RS to signal that it should test to determine if a SimpleRWLock is held.
// This is for testing purposes only.
// Arguments:
// input: pRWLock - the lock to test
// fOkToTake - true iff the LS does NOT currently hold the lock
// output: none
// Note: The RS will throw if the lock is held. The code that tests the lock will catch the
// exception and assert if throwing was not the correct thing to do (determined via the
// boolean). See the case for DB_IPCE_TEST_RWLOCK in code:CordbProcess::RawDispatchEvent.
//
void DataTest::SendDbgRWLockEvent(SimpleRWLock * pRWLock, bool okToTake)
{
DebuggerIPCEvent * pLockEvent = g_pDebugger->m_pRCThread->GetIPCEventSendBuffer();
g_pDebugger->InitIPCEvent(pLockEvent, DB_IPCE_TEST_RWLOCK);
pLockEvent->TestRWLockData.vmRWLock.SetRawPtr(pRWLock);
pLockEvent->TestRWLockData.fOkToTake = okToTake;
g_pDebugger->SendRawEvent(pLockEvent);
} // DataTest::SendDbgRWLockEvent
// Takes a series of locks in various ways and signals the RS to test the locks at interesting
// points to ensure we reliably detect when the LS holds a lock. If in the course of inspection, the
// DAC needs to execute a code path where the LS holds a lock, we assume that the locked data is in
// an inconsistent state. In this situation, we don't want to report information about this data, so
// we throw an exception.
// This is for testing purposes only.
//
// Arguments: none
// Return Value: none
// Notes: See code:CordbProcess::RawDispatchEvent for the RS part of this test and code:Debugger::Startup
// for the LS invocation of the test.
// The environment variable TestDataConsistency must be set to 1 to make this test run.
void DataTest::TestDataSafety()
{
const bool okToTake = true;
SendDbgCrstEvent(&m_crst1, okToTake);
{
CrstHolder ch1(&m_crst1);
SendDbgCrstEvent(&m_crst1, !okToTake);
{
CrstHolder ch2(&m_crst2);
SendDbgCrstEvent(&m_crst2, !okToTake);
SendDbgCrstEvent(&m_crst1, !okToTake);
}
SendDbgCrstEvent(&m_crst2, okToTake);
SendDbgCrstEvent(&m_crst1, !okToTake);
}
SendDbgCrstEvent(&m_crst1, okToTake);
{
SendDbgRWLockEvent(&m_rwLock, okToTake);
SimpleReadLockHolder readLock(&m_rwLock);
SendDbgRWLockEvent(&m_rwLock, okToTake);
}
SendDbgRWLockEvent(&m_rwLock, okToTake);
{
SimpleWriteLockHolder readLock(&m_rwLock);
SendDbgRWLockEvent(&m_rwLock, !okToTake);
}
} // DataTest::TestDataSafety
#endif // TEST_DATA_CONSISTENCY
#if _DEBUG
static DebugEventCounter g_debugEventCounter;
static int g_iDbgRuntimeCounter[DBG_RUNTIME_MAX];
static int g_iDbgDebuggerCounter[DBG_DEBUGGER_MAX];
void DoAssertOnType(DebuggerIPCEventType event, int count)
{
WRAPPER_NO_CONTRACT;
// check to see if we need fire the assertion or not.
if ((event & 0x0300) == 0x0100)
{
// use the Runtime array
if (g_iDbgRuntimeCounter[event & 0x00ff] == count)
{
char tmpStr[256];
_snprintf_s(tmpStr, ARRAY_SIZE(tmpStr), _TRUNCATE, "%s == %d, break now!",
IPCENames::GetName(event), count);
// fire the assertion
DbgAssertDialog(__FILE__, __LINE__, tmpStr);
}
}
// check to see if we need fire the assertion or not.
else if ((event & 0x0300) == 0x0200)
{
// use the Runtime array
if (g_iDbgDebuggerCounter[event & 0x00ff] == count)
{
char tmpStr[256];
_snprintf_s(tmpStr, ARRAY_SIZE(tmpStr), _TRUNCATE, "%s == %d, break now!",
IPCENames::GetName(event), count);
// fire the assertion
DbgAssertDialog(__FILE__, __LINE__, tmpStr);
}
}
}
void DbgLogHelper(DebuggerIPCEventType event)
{
WRAPPER_NO_CONTRACT;
switch (event)
{
// we don't need to handle event type 0
#define IPC_EVENT_TYPE0(type, val)
#define IPC_EVENT_TYPE1(type, val) case type: {\
g_debugEventCounter.m_iDebugCount_##type++; \
DoAssertOnType(type, g_debugEventCounter.m_iDebugCount_##type); \
break; \
}
#define IPC_EVENT_TYPE2(type, val) case type: { \
g_debugEventCounter.m_iDebugCount_##type++; \
DoAssertOnType(type, g_debugEventCounter.m_iDebugCount_##type); \
break; \
}
#include "dbgipceventtypes.h"
#undef IPC_EVENT_TYPE2
#undef IPC_EVENT_TYPE1
#undef IPC_EVENT_TYPE0
default:
break;
}
}
#endif // _DEBUG
/* ------------------------------------------------------------------------ *
* DLL export routine
* ------------------------------------------------------------------------ */
Debugger *CreateDebugger(void)
{
Debugger *pDebugger = NULL;
EX_TRY
{
pDebugger = new (nothrow) Debugger();
}
EX_CATCH
{
if (pDebugger != NULL)
{
delete pDebugger;
pDebugger = NULL;
}
}
EX_END_CATCH(RethrowTerminalExceptions);
return pDebugger;
}
//
// CorDBGetInterface is exported to the Runtime so that it can call
// the Runtime Controller.
//
extern "C"{
HRESULT __cdecl CorDBGetInterface(DebugInterface** rcInterface)
{
CONTRACT(HRESULT)
{
NOTHROW; // use HRESULTS instead
GC_NOTRIGGER;
POSTCONDITION(FAILED(RETVAL) || (rcInterface == NULL) || (*rcInterface != NULL));
}
CONTRACT_END;
HRESULT hr = S_OK;
if (rcInterface != NULL)
{
if (g_pDebugger == NULL)
{
LOG((LF_CORDB, LL_INFO10,
"CorDBGetInterface: initializing debugger.\n"));
g_pDebugger = CreateDebugger();
TRACE_ALLOC(g_pDebugger);
if (g_pDebugger == NULL)
hr = E_OUTOFMEMORY;
}
*rcInterface = g_pDebugger;
}
RETURN hr;
}
}
//-----------------------------------------------------------------------------
// Send a pre-init IPC event and block.
// We assume the IPC event has already been initialized. There's nothing special
// here; it just used the standard formula for sending an IPC event to the RS.
// This should match up w/ the description in SENDIPCEVENT_BEGIN.
//-----------------------------------------------------------------------------
void Debugger::SendSimpleIPCEventAndBlock()
{
CONTRACTL
{
MAY_DO_HELPER_THREAD_DUTY_THROWS_CONTRACT;
MAY_DO_HELPER_THREAD_DUTY_GC_TRIGGERS_CONTRACT;
}
CONTRACTL_END;
// BEGIN will acquire the lock (END will release it). While blocking, the
// debugger may have detached though, so we need to check for that.
_ASSERTE(ThreadHoldsLock());
if (CORDebuggerAttached())
{
m_pRCThread->SendIPCEvent();
// Stop all Runtime threads
this->TrapAllRuntimeThreads();
}
}
//-----------------------------------------------------------------------------
// Get context from a thread in managed code.
// See header for exact semantics.
//-----------------------------------------------------------------------------
CONTEXT * GetManagedStoppedCtx(Thread * pThread)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(pThread != NULL);
// We may be stopped or live.
// If we're stopped at an interop-hijack, we'll have a filter context,
// but we'd better not be redirected for a managed-suspension hijack.
if (pThread->GetInteropDebuggingHijacked())
{
_ASSERTE(!ISREDIRECTEDTHREAD(pThread));
return NULL;
}
// Check if we have a filter ctx. This should only be for managed-code.
// We're stopped at some exception (likely an int3 or single-step).
// Can't have both filter ctx + redirected ctx.
CONTEXT *pCtx = g_pEEInterface->GetThreadFilterContext(pThread);
if (pCtx != NULL)
{
_ASSERTE(!ISREDIRECTEDTHREAD(pThread));
return pCtx;
}
if (ISREDIRECTEDTHREAD(pThread))
{
pCtx = GETREDIRECTEDCONTEXT(pThread);
_ASSERTE(pCtx != NULL);
return pCtx;
}
// Not stopped somewhere in managed code.
return NULL;
}
//-----------------------------------------------------------------------------
// See header for exact semantics.
// Never NULL. (Caller guarantees this is active.)
//-----------------------------------------------------------------------------
CONTEXT * GetManagedLiveCtx(Thread * pThread)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(pThread != NULL);
// We should never be on the helper thread, we should only be inspecting our own thread.
// We're in some Controller's Filter after hitting an exception.
// We're not stopped.
//_ASSERTE(!g_pDebugger->IsStopped()); <-- @todo - this fires, need to find out why.
_ASSERTE(GetThreadNULLOk() == pThread);
CONTEXT *pCtx = g_pEEInterface->GetThreadFilterContext(pThread);
// Note that we may be in a M2U hijack. So we can't assert !pThread->GetInteropDebuggingHijacked()
_ASSERTE(!ISREDIRECTEDTHREAD(pThread));
_ASSERTE(pCtx);
return pCtx;
}
// Attempt to validate a GC handle.
HRESULT ValidateGCHandle(OBJECTHANDLE oh)
{
// The only real way to do this is to Enumerate all GC handles in the handle table.
// That's too expensive. So we'll use a similar workaround that we use in ValidateObject.
// This will err on the side off returning True for invalid handles.
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
HRESULT hr = S_OK;
EX_TRY
{
// Use AVInRuntimeImplOkHolder.
AVInRuntimeImplOkayHolder AVOkay;
// This may throw if the Object Handle is invalid.
Object * objPtr = *((Object**) oh);
// NULL is certinally valid...
if (objPtr != NULL)
{
if (!objPtr->ValidateObjectWithPossibleAV())
{
LOG((LF_CORDB, LL_INFO10000, "GAV: object methodtable-class invariant doesn't hold.\n"));
hr = E_INVALIDARG;
goto LExit;
}
}
LExit: ;
}
EX_CATCH
{
LOG((LF_CORDB, LL_INFO10000, "GAV: exception indicated ref is bad.\n"));
hr = E_INVALIDARG;
}
EX_END_CATCH(SwallowAllExceptions);
return hr;
}
// Validate an object. Returns E_INVALIDARG or S_OK.
HRESULT ValidateObject(Object *objPtr)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
HRESULT hr = S_OK;
EX_TRY
{
// Use AVInRuntimeImplOkHolder.
AVInRuntimeImplOkayHolder AVOkay;
// NULL is certinally valid...
if (objPtr != NULL)
{
if (!objPtr->ValidateObjectWithPossibleAV())
{
LOG((LF_CORDB, LL_INFO10000, "GAV: object methodtable-class invariant doesn't hold.\n"));
hr = E_INVALIDARG;
goto LExit;
}
}
LExit: ;
}
EX_CATCH
{
LOG((LF_CORDB, LL_INFO10000, "GAV: exception indicated ref is bad.\n"));
hr = E_INVALIDARG;
}
EX_END_CATCH(SwallowAllExceptions);
return hr;
} // ValidateObject
#ifdef FEATURE_DBGIPC_TRANSPORT_VM
void
ShutdownTransport()
{
if (g_pDbgTransport != NULL)
{
g_pDbgTransport->Shutdown();
g_pDbgTransport = NULL;
}
}
#endif // FEATURE_DBGIPC_TRANSPORT_VM
/* ------------------------------------------------------------------------ *
* Debugger routines
* ------------------------------------------------------------------------ */
//
// a Debugger object represents the global state of the debugger program.
//
//
// Constructor & Destructor
//
/******************************************************************************
*
******************************************************************************/
Debugger::Debugger()
:
m_fLeftSideInitialized(FALSE),
#ifdef _DEBUG
m_mutexCount(0),
#endif //_DEBUG
m_pRCThread(NULL),
m_trappingRuntimeThreads(FALSE),
m_stopped(FALSE),
m_unrecoverableError(FALSE),
m_ignoreThreadDetach(FALSE),
m_pMethodInfos(NULL),
m_mutex(CrstDebuggerMutex, (CrstFlags)(CRST_UNSAFE_ANYMODE | CRST_REENTRANCY | CRST_DEBUGGER_THREAD)),
#ifdef _DEBUG
m_mutexOwner(0),
m_tidLockedForEventSending(0),
#endif //_DEBUG
m_threadsAtUnsafePlaces(0),
m_jitAttachInProgress(FALSE),
m_launchingDebugger(FALSE),
m_LoggingEnabled(TRUE),
m_pAppDomainCB(NULL),
m_dClassLoadCallbackCount(0),
m_pModules(NULL),
m_RSRequestedSync(FALSE),
m_sendExceptionsOutsideOfJMC(TRUE),
m_forceNonInterceptable(FALSE),
m_pLazyData(NULL),
m_defines(_defines),
m_isSuspendedForGarbageCollection(FALSE),
m_isBlockedOnGarbageCollectionEvent(FALSE),
m_willBlockOnGarbageCollectionEvent(FALSE),
m_isGarbageCollectionEventsEnabled(FALSE),
m_isGarbageCollectionEventsEnabledLatch(FALSE)
{
CONTRACTL
{
WRAPPER(THROWS);
WRAPPER(GC_TRIGGERS);
CONSTRUCTOR_CHECK;
}
CONTRACTL_END;
m_fShutdownMode = false;
m_fDisabled = false;
m_rgHijackFunction = NULL;
#ifdef _DEBUG
InitDebugEventCounting();
#endif
m_processId = GetCurrentProcessId();
// Initialize these in ctor because we free them in dtor.
// And we can't set them to some safe uninited value (like NULL).
//------------------------------------------------------------------------------
// Metadata data structure version numbers
//
// 1 - initial state of the layouts ( .NET Framework 4.5.2 )
//
// as data structure layouts change, add a new version number
// and comment the changes
m_mdDataStructureVersion = 1;
m_fOutOfProcessSetContextEnabled =
#if defined(OUT_OF_PROCESS_SETTHREADCONTEXT) && !defined(DACCESS_COMPILE)
Thread::AreCetShadowStacksEnabled() || CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_OutOfProcessSetContext) != 0;
#else
FALSE;
#endif
}
/******************************************************************************
*
******************************************************************************/
Debugger::~Debugger()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
// We explicitly leak the debugger object on shutdown. See Debugger::StopDebugger for details.
_ASSERTE(!"Debugger dtor should not be called.");
}
#if defined(FEATURE_HIJACK) && !defined(TARGET_UNIX)
// Given the start address and the end address of a function, return a MemoryRange for the function.
inline MemoryRange GetMemoryRangeForFunction(void *pfnStart, void *pfnEnd)