This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
debugger.h
3969 lines (3166 loc) · 134 KB
/
debugger.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.
//*****************************************************************************
// File: debugger.h
//
//
// Header file for Runtime Controller classes of the COM+ Debugging Services.
//
//*****************************************************************************
#ifndef DEBUGGER_H_
#define DEBUGGER_H_
#include <windows.h>
#include <utilcode.h>
#include <metahost.h>
#if defined(_DEBUG) && !defined(DACCESS_COMPILE)
#define LOGGING
#endif
#include <log.h>
#include "cor.h"
#include "corpriv.h"
#include "daccess.h"
#include "common.h"
#include "winwrap.h"
#include "threads.h"
#include "threadsuspend.h"
#include "frames.h"
#include "appdomain.hpp"
#include "eedbginterface.h"
#include "dbginterface.h"
#include "corhost.h"
#include "corjit.h"
#include <dbgmeta.h> // <TODO>need to rip this out of here...</TODO>
#include "frameinfo.h"
#include "dllimportcallback.h"
#include "canary.h"
#undef ASSERT
#define CRASH(x) _ASSERTE(!(x))
#define ASSERT(x) _ASSERTE(x)
#ifndef TRACE_MEMORY
#define TRACE_MEMORY 0
#endif
#if TRACE_MEMORY
#define TRACE_ALLOC(p) LOG((LF_CORDB, LL_INFO10000, \
"--- Allocated %x at %s:%d\n", p, __FILE__, __LINE__));
#define TRACE_FREE(p) LOG((LF_CORDB, LL_INFO10000, \
"--- Freed %x at %s:%d\n", p, __FILE__, __LINE__));
#else
#define TRACE_ALLOC(p)
#define TRACE_FREE(p)
#endif
typedef CUnorderedArray<void*,11> UnorderedPtrArray;
/* ------------------------------------------------------------------------ *
* Forward class declarations
* ------------------------------------------------------------------------ */
class DebuggerFrame;
class DebuggerModule;
class DebuggerModuleTable;
class Debugger;
class DebuggerBreakpoint;
class DebuggerPendingFuncEvalTable;
class DebuggerRCThread;
class DebuggerStepper;
class DebuggerMethodInfo;
class DebuggerJitInfo;
class DebuggerMethodInfoTable;
struct DebuggerControllerPatch;
class DebuggerEval;
class DebuggerControllerQueue;
class DebuggerController;
class Crst;
typedef CUnorderedArray<DebuggerControllerPatch *, 17> PATCH_UNORDERED_ARRAY;
template<class T> void DeleteInteropSafe(T *p);
template<class T> void DeleteInteropSafeExecutable(T *p);
typedef VPTR(class Debugger) PTR_Debugger;
typedef DPTR(struct DebuggerILToNativeMap) PTR_DebuggerILToNativeMap;
typedef DPTR(class DebuggerMethodInfo) PTR_DebuggerMethodInfo;
typedef VPTR(class DebuggerMethodInfoTable) PTR_DebuggerMethodInfoTable;
typedef DPTR(class DebuggerJitInfo) PTR_DebuggerJitInfo;
typedef DPTR(class DebuggerEval) PTR_DebuggerEval;
typedef DPTR(struct DebuggerIPCControlBlock) PTR_DebuggerIPCControlBlock;
/* ------------------------------------------------------------------------ *
* Global variables
* ------------------------------------------------------------------------ */
GPTR_DECL(Debugger, g_pDebugger);
GPTR_DECL(EEDebugInterface, g_pEEInterface);
GVAL_DECL(ULONG, CLRJitAttachState);
#ifndef FEATURE_PAL
GVAL_DECL(HANDLE, g_hContinueStartupEvent);
#endif
extern DebuggerRCThread *g_pRCThread;
//---------------------------------------------------------------------------------------
// Holder to ensure our calls to IncThreadsAtUnsafePlaces and DecThreadsAtUnsafePlaces
class AtSafePlaceHolder
{
public:
AtSafePlaceHolder(Thread * pThread);
// Clear the holder.
~AtSafePlaceHolder();
// True if the holder is acquired.
bool IsAtUnsafePlace();
// Clear the holder (call DecThreadsAtUnsafePlaces if needed)
void Clear();
private:
// If this is non-null, then the holder incremented the unsafe counter and it needs
// to decrement it.
Thread * m_pThreadAtUnsafePlace;
};
template<BOOL COOPERATIVE, BOOL TOGGLE, BOOL IFTHREAD>
class GCHolderEEInterface
{
public:
DEBUG_NOINLINE GCHolderEEInterface();
DEBUG_NOINLINE ~GCHolderEEInterface();
};
#ifndef DACCESS_COMPILE
template<BOOL TOGGLE, BOOL IFTHREAD>
class GCHolderEEInterface<TRUE, TOGGLE, IFTHREAD>
{
private:
bool startInCoop;
public:
DEBUG_NOINLINE GCHolderEEInterface()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_COOPERATIVE;
if (IFTHREAD && g_pEEInterface->GetThread() == NULL)
{
return;
}
startInCoop = false;
if (g_pEEInterface->IsPreemptiveGCDisabled())
{
// we're starting in COOP, no need to switch
startInCoop = true;
}
else
{
// we're starting in PREEMP, need to switch to COOP
startInCoop = false;
g_pEEInterface->DisablePreemptiveGC();
}
};
DEBUG_NOINLINE ~GCHolderEEInterface()
{
SCAN_SCOPE_END;
if (IFTHREAD && g_pEEInterface->GetThread() == NULL)
{
return;
}
_ASSERT(g_pEEInterface->IsPreemptiveGCDisabled());
if (TOGGLE)
{
// We're in COOP, toggle to PREEMPTIVE and back to COOP
// for synch purposes.
g_pEEInterface->EnablePreemptiveGC();
g_pEEInterface->DisablePreemptiveGC();
// If we started in PREEMPTIVE switch back
if (!startInCoop)
{
g_pEEInterface->EnablePreemptiveGC();
}
}
else
{
// If we started in PREEMPTIVE switch back
if (!startInCoop)
{
g_pEEInterface->EnablePreemptiveGC();
}
}
};
};
template<BOOL TOGGLE, BOOL IFTHREAD>
class GCHolderEEInterface<FALSE, TOGGLE, IFTHREAD>
{
private:
bool startInCoop;
bool conditional;
void EnterInternal(bool bStartInCoop, bool bConditional)
{
startInCoop = bStartInCoop;
conditional = bConditional;
if (!conditional || (IFTHREAD && g_pEEInterface->GetThread() == NULL))
{
return;
}
if (g_pEEInterface->IsPreemptiveGCDisabled())
{
// we're starting in COOP, we need to switch to PREEMP
startInCoop = true;
g_pEEInterface->EnablePreemptiveGC();
}
else
{
// We're starting in PREEMP, no need to switch
startInCoop = false;
}
}
void LeaveInternal()
{
if (!conditional || (IFTHREAD && g_pEEInterface->GetThread() == NULL))
{
return;
}
_ASSERTE(!g_pEEInterface->IsPreemptiveGCDisabled());
if (TOGGLE)
{
// Explicitly toggle to COOP for eventin
g_pEEInterface->DisablePreemptiveGC();
// If we started in PREEMPTIVE switch back to PREEMPTIVE
if (!startInCoop)
{
g_pEEInterface->EnablePreemptiveGC();
}
}
else
{
// If we started in COOP, flip back to COOP at the end of the
// scope, if we started in preemptive we should be fine.
if (startInCoop)
{
g_pEEInterface->DisablePreemptiveGC();
}
}
}
public:
DEBUG_NOINLINE GCHolderEEInterface()
{
SCAN_SCOPE_BEGIN;
STATIC_CONTRACT_MODE_PREEMPTIVE;
this->EnterInternal(false, true);
}
DEBUG_NOINLINE GCHolderEEInterface(bool bConditional)
{
SCAN_SCOPE_BEGIN;
if (bConditional)
{
STATIC_CONTRACT_MODE_PREEMPTIVE;
}
this->EnterInternal(false, bConditional);
}
DEBUG_NOINLINE ~GCHolderEEInterface()
{
SCAN_SCOPE_END;
this->LeaveInternal();
};
};
#endif //DACCESS_COMPILE
#define GCX_COOP_EEINTERFACE() \
GCHolderEEInterface<TRUE, FALSE, FALSE> __gcCoop_onlyOneAllowedPerScope
#define GCX_PREEMP_EEINTERFACE() \
GCHolderEEInterface<FALSE, FALSE, FALSE> __gcCoop_onlyOneAllowedPerScope
#define GCX_COOP_EEINTERFACE_TOGGLE() \
GCHolderEEInterface<TRUE, TRUE, FALSE> __gcCoop_onlyOneAllowedPerScope
#define GCX_PREEMP_EEINTERFACE_TOGGLE() \
GCHolderEEInterface<FALSE, TRUE, FALSE> __gcCoop_onlyOneAllowedPerScope
#define GCX_PREEMP_EEINTERFACE_TOGGLE_IFTHREAD() \
GCHolderEEInterface<FALSE, TRUE, TRUE> __gcCoop_onlyOneAllowedPerScope
#define GCX_PREEMP_EEINTERFACE_TOGGLE_COND(cond) \
GCHolderEEInterface<FALSE, TRUE, FALSE> __gcCoop_onlyOneAllowedPerScope((cond))
#define GCX_PREEMP_EEINTERFACE_TOGGLE_IFTHREAD_COND(cond) \
GCHolderEEInterface<FALSE, TRUE, TRUE> __gcCoop_onlyOneAllowedPerScope((cond))
// There are still some APIs that call new that we call from the helper thread.
// These are unsafe operations, so we wrap them here. Each of these is a potential hang.
inline DWORD UnsafeGetConfigDWORD_DontUse_(LPCWSTR name, DWORD defValue)
{
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
return REGUTIL::GetConfigDWORD_DontUse_(name, defValue);
}
inline DWORD UnsafeGetConfigDWORD(const CLRConfig::ConfigDWORDInfo & info)
{
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
return CLRConfig::GetConfigValue(info);
}
#define FILE_DEBUG INDEBUG(__FILE__) NOT_DEBUG(NULL)
#define LINE_DEBUG INDEBUG(__LINE__) NOT_DEBUG(0)
#define CORDBDebuggerSetUnrecoverableWin32Error(__d, __code, __w) \
((__d)->UnrecoverableError(HRESULT_FROM_WIN32(GetLastError()), \
(__code), FILE_DEBUG, LINE_DEBUG, (__w)), \
HRESULT_FROM_GetLastError())
#define CORDBDebuggerSetUnrecoverableError(__d, __hr, __w) \
(__d)->UnrecoverableError((__hr), \
(__hr), FILE_DEBUG, LINE_DEBUG, (__w))
#define CORDBUnrecoverableError(__d) ((__d)->m_unrecoverableError == TRUE)
/* ------------------------------------------------------------------------ *
* Helpers used for contract preconditions.
* ------------------------------------------------------------------------ */
bool ThisIsHelperThreadWorker(void);
bool ThisIsTempHelperThread();
bool ThisIsTempHelperThread(DWORD tid);
#ifdef _DEBUG
// Functions can be split up into 3 categories:
// 1.) Functions that must run on the helper thread.
// Returns true if this is the helper thread (or the thread
// doing helper-threadduty).
// 2.) Functions that can't run on the helper thread.
// This is just !ThisIsHelperThread();
// 3.) Functions that may or may not run on the helper thread.
// Note this is trivially true, but it's presences means that
// we're not case #1 or #2, so it's still valuable.
inline bool ThisMaybeHelperThread() { return true; }
#endif
// These are methods for transferring information between a REGDISPLAY and
// a DebuggerREGDISPLAY.
extern void CopyREGDISPLAY(REGDISPLAY* pDst, REGDISPLAY* pSrc);
extern void SetDebuggerREGDISPLAYFromREGDISPLAY(DebuggerREGDISPLAY* pDRD, REGDISPLAY* pRD);
//
// PUSHED_REG_ADDR gives us NULL if the register still lives in the thread's context, or it gives us the address
// of where the register was pushed for this frame.
//
// This macro is used in CopyREGDISPLAY() and SetDebuggerREGDISPLAYFromREGDISPLAY(). We really should make
// DebuggerREGDISPLAY to be a class with these two methods, but unfortunately, the RS has no notion of REGDISPLAY.
inline LPVOID PushedRegAddr(REGDISPLAY* pRD, LPVOID pAddr)
{
LIMITED_METHOD_CONTRACT;
#ifdef FEATURE_EH_FUNCLETS
if ( ((UINT_PTR)(pAddr) >= (UINT_PTR)pRD->pCurrentContextPointers) &&
((UINT_PTR)(pAddr) <= ((UINT_PTR)pRD->pCurrentContextPointers + sizeof(T_KNONVOLATILE_CONTEXT_POINTERS))) )
#else
if ( ((UINT_PTR)(pAddr) >= (UINT_PTR)pRD->pContext) &&
((UINT_PTR)(pAddr) <= ((UINT_PTR)pRD->pContext + sizeof(T_CONTEXT))) )
#endif
return NULL;
// (Microsoft 2/9/07 - putting this in an else clause confuses gcc for some reason, so I've moved
// it to here)
return pAddr;
}
bool HandleIPCEventWrapper(Debugger* pDebugger, DebuggerIPCEvent *e);
HRESULT ValidateObject(Object *objPtr);
//-----------------------------------------------------------------------------
// Execution control needs several ways to get at the context of a thread
// stopped in mangaged code (stepping, setip, func-eval).
// We want to abstract away a few things:
// - active: this thread is stopped at a patch
// - inactive: this threads was managed suspended somewhere in jitted code
// because of some other active thread.
//
// In general, execution control operations administered from the helper thread
// can occur on any managed thread (active or inactive).
// Intermediate triggers (eg, TriggerPatch) only occur on an active thread.
//
// Viewing the context in terms of Active vs. Inactive lets us abstract away
// filter context, redirected context, and interop hijacks.
//-----------------------------------------------------------------------------
// Get the context for a thread stopped (perhaps temporarily) in managed code.
// The process may be live or stopped.
// This thread could be 'active' (stopped at patch) or inactive.
// This context should always be in managed code and this context can be manipulated
// for execution control (setip, single-step, func-eval, etc)
// Returns NULL if not available.
CONTEXT * GetManagedStoppedCtx(Thread * pThread);
// Get the context for a thread live in or around managed code.
// Caller guarantees this is active.
// This ctx is just for a 'live' thread. This means that the ctx may include
// from a M2U hijack or from a Native patch (like .
// Never NULL.
CONTEXT * GetManagedLiveCtx(Thread * pThread);
#undef UtilMessageBoxCatastrophic
#undef UtilMessageBoxCatastrophicNonLocalized
#undef UtilMessageBoxCatastrophicVA
#undef UtilMessageBoxCatastrophicNonLocalizedVA
#undef UtilMessageBox
#undef UtilMessageBoxNonLocalized
#undef UtilMessageBoxVA
#undef UtilMessageBoxNonLocalizedVA
#undef WszMessageBox
#define UtilMessageBoxCatastrophic __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBoxCatastrophicNonLocalized __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBoxCatastrophicVA __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBoxCatastrophicNonLocalizedVA __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBox __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBoxNonLocalized __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBoxVA __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define UtilMessageBoxNonLocalizedVA __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
#define WszMessageBox __error("Use g_pDebugger->MessageBox from inside the left side of the debugger")
/* ------------------------------------------------------------------------ *
* Module classes
* ------------------------------------------------------------------------ */
// Once a module / appdomain is unloaded, all Right-side objects (such as breakpoints)
// in that appdomain will get neutered and will thus be prevented from accessing
// the unloaded appdomain.
//
// @dbgtodo jmc - This is now purely relegated to the LS. Eventually completely get rid of this
// by moving fields off to Module or getting rid of the fields completely.
typedef DPTR(class DebuggerModule) PTR_DebuggerModule;
class DebuggerModule
{
public:
DebuggerModule(Module * pRuntimeModule, DomainFile * pDomainFile, AppDomain * pAppDomain);
// Do we have any optimized code in the module?
// JMC-probes aren't emitted in optimized code,
bool HasAnyOptimizedCode();
// If the debugger updates things to allow/disallow optimized code, then we have to track that.
void MarkAllowedOptimizedCode();
void UnmarkAllowedOptimizedCode();
BOOL ClassLoadCallbacksEnabled(void);
void EnableClassLoadCallbacks(BOOL f);
AppDomain* GetAppDomain();
Module * GetRuntimeModule();
// <TODO> (8/12/2002)
// Currently we create a new DebuggerModules for each appdomain a shared
// module lives in. We then pretend there aren't any shared modules.
// This is bad. We need to move away from this.
// Once we stop lying, then every module will be it's own PrimaryModule. :)
//
// Currently, Module* is 1:n w/ DebuggerModule.
// We add a notion of PrimaryModule so that:
// Module* is 1:1 w/ DebuggerModule::GetPrimaryModule();
// This should help transition towards exposing shared modules.
// If the Runtime module is shared, then this gives a common DM.
// If the runtime module is not shared, then this is an identity function.
//
// The runtime has the notion of "DomainFile", which is 1:1 with DebuggerModule
// and thus 1:1 with CordbModule. The CordbModule hash table on the RS now uses
// the DomainFile as the key instead of DebuggerModule. This is a temporary
// workaround to facilitate the removal of DebuggerModule.
// </TODO>
DebuggerModule * GetPrimaryModule();
DomainFile * GetDomainFile()
{
LIMITED_METHOD_DAC_CONTRACT;
return m_pRuntimeDomainFile;
}
// Called by DebuggerModuleTable to set our primary module
void SetPrimaryModule(DebuggerModule * pPrimary);
void SetCanChangeJitFlags(bool fCanChangeJitFlags);
private:
BOOL m_enableClassLoadCallbacks;
// First step in moving away from hiding shared modules.
DebuggerModule* m_pPrimaryModule;
PTR_Module m_pRuntimeModule;
PTR_DomainFile m_pRuntimeDomainFile;
AppDomain* m_pAppDomain;
bool m_fHasOptimizedCode;
void PickPrimaryModule();
// Can we change jit flags on the module?
// This is true during the Module creation
bool m_fCanChangeJitFlags;
};
/* ------------------------------------------------------------------------ *
* Hash to hold pending func evals by thread id
* ------------------------------------------------------------------------ */
struct DebuggerPendingFuncEval
{
FREEHASHENTRY entry;
PTR_Thread pThread;
PTR_DebuggerEval pDE;
};
typedef DPTR(struct DebuggerPendingFuncEval) PTR_DebuggerPendingFuncEval;
/* ------------------------------------------------------------------------ *
* DebuggerRCThread class -- the Runtime Controller thread.
* ------------------------------------------------------------------------ */
#define DRCT_CONTROL_EVENT 0
#define DRCT_RSEA 1
#define DRCT_FAVORAVAIL 2
#define DRCT_COUNT_INITIAL 3
#define DRCT_DEBUGGER_EVENT 3
#define DRCT_COUNT_FINAL 4
// Canary is used as way to have a runtime failure for the SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE
// contract violation.
// Have a macro which checks the canary and then uses the Suppress macro.
// We need this check to be a macro in order to chain to the Suppress_allocation macro.
#define CHECK_IF_CAN_TAKE_HELPER_LOCKS_IN_THIS_SCOPE(pHR, pCanary) \
{ \
HelperCanary * __pCanary = (pCanary); \
if (!__pCanary->AreLocksAvailable()) { \
(*pHR) = CORDBG_E_HELPER_MAY_DEADLOCK; \
} else { \
(*pHR) = S_OK; \
} \
} \
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE \
; \
// Mechanics for cross-thread call to helper thread (called "Favor").
class HelperThreadFavor
{
// Only let RCThread access these fields.
friend class DebuggerRCThread;
HelperThreadFavor();
// No dtor because we intentionally leak all shutdown.
void Init();
protected:
// Stuff for having the helper thread do function calls for a thread
// that blew its stack
FAVORCALLBACK m_fpFavor;
void *m_pFavorData;
HANDLE m_FavorReadEvent;
Crst m_FavorLock;
HANDLE m_FavorAvailableEvent;
};
// The *LazyInit classes represents storage that the debugger doesn't need until after it has started up.
// This is effectively an extension to the debugger class; but for perf reasons, we only
// want to instantiate it if we're actually debugging.
// Fields that are a logical extension of RCThread
class RCThreadLazyInit
{
// Only let RCThread access these fields.
friend class DebuggerRCThread;
public:
RCThreadLazyInit() { }
~RCThreadLazyInit() { }
void Init() { }
protected:
HelperCanary m_Canary;
};
// Fields that are a logical extension of Debugger
class DebuggerLazyInit
{
friend class Debugger;
public:
DebuggerLazyInit();
~DebuggerLazyInit();
protected:
void Init();
DebuggerPendingFuncEvalTable *m_pPendingEvals;
// The "debugger data lock" is a very small leaf lock used to protect debugger internal data structures (such
// as DJIs, DMIs, module table). It is a GC-unsafe-anymode lock and so it can't trigger a GC while being held.
// It also can't issue any callbacks into the EE or anycode that it does not directly control.
// This is a separate lock from the the larger Debugger-lock / Controller lock, which allows regions under those
// locks to access debugger datastructures w/o blocking each other.
Crst m_DebuggerDataLock;
HANDLE m_CtrlCMutex;
HANDLE m_exAttachEvent;
HANDLE m_exUnmanagedAttachEvent;
HANDLE m_garbageCollectionBlockerEvent;
BOOL m_DebuggerHandlingCtrlC;
// Used by MapAndBindFunctionBreakpoints. Note that this is thread-safe
// only b/c we access it from within the DebuggerController::Lock
SIZE_T_UNORDERED_ARRAY m_BPMappingDuplicates;
UnorderedPtrArray m_pMemBlobs;
// Hang RCThread fields off DebuggerLazyInit to avoid an extra pointer.
RCThreadLazyInit m_RCThread;
};
typedef DPTR(DebuggerLazyInit) PTR_DebuggerLazyInit;
class DebuggerRCThread
{
public:
DebuggerRCThread(Debugger * pDebugger);
virtual ~DebuggerRCThread();
void CloseIPCHandles();
//
// You create a new instance of this class, call Init() to set it up,
// then call Start() start processing events. Stop() terminates the
// thread and deleting the instance cleans all the handles and such
// up.
//
HRESULT Init(void);
HRESULT Start(void);
HRESULT AsyncStop(void);
//
// These are used by this thread to send IPC events to the Debugger
// Interface side.
//
DebuggerIPCEvent* GetIPCEventSendBuffer()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
#ifdef LOGGING
if(IsRCThreadReady()) {
LOG((LF_CORDB, LL_EVERYTHING, "RCThread is ready\n"));
}
#endif
_ASSERTE(m_pDCB != NULL);
// In case this turns into a continuation event
GetRCThreadSendBuffer()->next = NULL;
LOG((LF_CORDB,LL_EVERYTHING, "GIPCESBuffer: got event 0x%x\n", GetRCThreadSendBuffer()));
return GetRCThreadSendBuffer();
}
DebuggerIPCEvent *GetIPCEventSendBufferContinuation(
DebuggerIPCEvent *eventCur)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(eventCur != NULL);
PRECONDITION(eventCur->next == NULL);
}
CONTRACTL_END;
DebuggerIPCEvent *dipce = (DebuggerIPCEvent *) new (nothrow) BYTE [CorDBIPC_BUFFER_SIZE];
dipce->next = NULL;
LOG((LF_CORDB,LL_INFO1000000, "About to GIPCESBC 0x%x\n",dipce));
if (dipce != NULL)
{
eventCur->next = dipce;
}
#ifdef _DEBUG
else
{
_ASSERTE( !"GetIPCEventSendBufferContinuation failed to allocate mem!" );
}
#endif //_DEBUG
return dipce;
}
// Send an IPCEvent once we're ready for sending. This should be done inbetween
// SENDIPCEVENT_BEGIN & SENDIPCEVENT_END. See definition of SENDIPCEVENT_BEGIN
// for usage pattern
HRESULT SendIPCEvent();
HRESULT EnsureRuntimeOffsetsInit(IpcTarget i); // helper function for SendIPCEvent
void NeedRuntimeOffsetsReInit(IpcTarget i);
DebuggerIPCEvent* GetIPCEventReceiveBuffer()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(m_pDCB != NULL);
return GetRCThreadReceiveBuffer();
}
HRESULT SendIPCReply();
//
// Handle Favors - get the Helper thread to do a function call for us
// because our thread can't (eg, we don't have the stack space)
// DoFavor will call (*fp)(pData) and block until fp returns.
// pData can store parameters, return value, and a this ptr (if we
// need to call a member function)
//
void DoFavor(FAVORCALLBACK fp, void * pData);
//
// Convience routines
//
PTR_DebuggerIPCControlBlock GetDCB()
{
LIMITED_METHOD_DAC_CONTRACT;
// This may be called before we init or after we shutdown.
return m_pDCB;
}
void WatchForStragglers(void);
HRESULT SetupRuntimeOffsets(DebuggerIPCControlBlock *pDCB);
bool HandleRSEA();
void MainLoop();
void TemporaryHelperThreadMainLoop();
HANDLE GetHelperThreadCanGoEvent(void) {LIMITED_METHOD_CONTRACT; return m_helperThreadCanGoEvent; }
void EarlyHelperThreadDeath(void);
void RightSideDetach(void);
//
//
//
void ThreadProc(void);
static DWORD WINAPI ThreadProcStatic(LPVOID parameter);
static DWORD WINAPI ThreadProcRemote(LPVOID parameter);
DWORD GetRCThreadId()
{
LIMITED_METHOD_CONTRACT;
return m_pDCB->m_helperThreadId;
}
// Return true if the Helper Thread up & initialized.
bool IsRCThreadReady();
HRESULT ReDaclEvents(PSECURITY_DESCRIPTOR securityDescriptor);
private:
// The transport based communication protocol keeps the send and receive buffers outside of the DCB
// to keep the DCB size down (since we send it over the wire).
DebuggerIPCEvent * GetRCThreadReceiveBuffer()
{
#if defined(FEATURE_DBGIPC_TRANSPORT_VM)
return reinterpret_cast<DebuggerIPCEvent *>(&m_receiveBuffer[0]);
#else
return reinterpret_cast<DebuggerIPCEvent *>(&m_pDCB->m_receiveBuffer[0]);
#endif
}
// The transport based communication protocol keeps the send and receive buffers outside of the DCB
// to keep the DCB size down (since we send it over the wire).
DebuggerIPCEvent * GetRCThreadSendBuffer()
{
#if defined(FEATURE_DBGIPC_TRANSPORT_VM)
return reinterpret_cast<DebuggerIPCEvent *>(&m_sendBuffer[0]);
#else // FEATURE_DBGIPC_TRANSPORT_VM
return reinterpret_cast<DebuggerIPCEvent *>(&m_pDCB->m_sendBuffer[0]);
#endif // FEATURE_DBGIPC_TRANSPORT_VM
}
FAVORCALLBACK GetFavorFnPtr() { return m_favorData.m_fpFavor; }
void * GetFavorData() { return m_favorData.m_pFavorData; }
void SetFavorFnPtr(FAVORCALLBACK fp, void * pData)
{
m_favorData.m_fpFavor = fp;
m_favorData.m_pFavorData = pData;
}
Crst * GetFavorLock() { return &m_favorData.m_FavorLock; }
HANDLE GetFavorReadEvent() { return m_favorData.m_FavorReadEvent; }
HANDLE GetFavorAvailableEvent() { return m_favorData.m_FavorAvailableEvent; }
HelperThreadFavor m_favorData;
HelperCanary * GetCanary() { return &GetLazyData()->m_Canary; }
friend class Debugger;
Debugger* m_debugger;
// IPC_TARGET_* define default targets - if we ever want to do
// multiple right sides, we'll have to switch to a OUTOFPROC + iTargetProcess scheme
PTR_DebuggerIPCControlBlock m_pDCB;
#ifdef FEATURE_DBGIPC_TRANSPORT_VM
// These buffers move here out of the DebuggerIPCControlBlock since the block is not shared memory when
// using the transport, but we do send its contents over the wire (and these buffers would greatly impact
// the number of bytes sent without being useful in any way).
BYTE m_receiveBuffer[CorDBIPC_BUFFER_SIZE];
BYTE m_sendBuffer[CorDBIPC_BUFFER_SIZE];
#endif // FEATURE_DBGIPC_TRANSPORT_VM
HANDLE m_thread;
bool m_run;
HANDLE m_threadControlEvent;
HANDLE m_helperThreadCanGoEvent;
bool m_rgfInitRuntimeOffsets[IPC_TARGET_COUNT];
bool m_fDetachRightSide;
RCThreadLazyInit * GetLazyData();
#ifdef _DEBUG
// Tracking to ensure that the helper thread only calls New() on the interop-safe heap.
// We need a very light-weight way to track the helper b/c we need to check everytime somebody
// calls operator new, which may occur during shutdown paths.
static EEThreadId s_DbgHelperThreadId;
public:
// The OS ThreadId of the helper as determined from the CreateThread call.
DWORD m_DbgHelperThreadOSTid;
private:
#endif
};
typedef DPTR(DebuggerRCThread) PTR_DebuggerRCThread;
/* ------------------------------------------------------------------------ *
* Debugger Method Info struct and hash table
* ------------------------------------------------------------------------ */
// class DebuggerMethodInfo: Struct to hold all the information
// necessary for a given function.
//
// m_module, m_token: Method that this DMI applies to
//
const bool bOriginalToInstrumented = true;
const bool bInstrumentedToOriginal = false;
class DebuggerMethodInfo
{
// This is the most recent version of the function based on the latest update and is
// set in UpdateFunction. When a function is jitted, the version is copied from here
// and stored in the corresponding DebuggerJitInfo structure so can always know the
// version of a particular jitted function.
SIZE_T m_currentEnCVersion;
public:
PTR_Module m_module;
mdMethodDef m_token;
PTR_DebuggerMethodInfo m_prevMethodInfo;
PTR_DebuggerMethodInfo m_nextMethodInfo;
// Enumerate DJIs
// Expected usage:
// DMI.InitDJIIterator(&it);
// while(!it.IsAtEnd()) {
// f(it.Current()); it.Next();
// }
class DJIIterator
{
friend class DebuggerMethodInfo;
DebuggerJitInfo* m_pCurrent;
Module* m_pLoaderModuleFilter;
MethodDesc* m_pMethodDescFilter;
public:
DJIIterator();
bool IsAtEnd();
DebuggerJitInfo * Current();
void Next(BOOL fFirst = FALSE);
};
// Ensure the DJI cache is completely up to date. (This can be an expensive call, but
// much less so if pMethodDescFilter is used).
void CreateDJIsForNativeBlobs(AppDomain * pAppDomain, Module * pModuleFilter, MethodDesc * pMethodDescFilter);
// Ensure the DJI cache is up to date for a particular closed method desc
void CreateDJIsForMethodDesc(MethodDesc * pMethodDesc);
// Get an iterator for all native blobs (accounts for Generics, Enc, + Prejiiting).
// Must be stopped when we do this. This could be heavy weight.
// This will call CreateDJIsForNativeBlobs() to ensure we have all DJIs available.
// You may optionally pass pLoaderModuleFilter to restrict the DJIs iterated to
// exist only on MethodDescs whose loader module matches the filter (pass NULL not
// to filter by loader module).
// You may optionally pass pMethodDescFilter to restrict the DJIs iterated to only
// a single generic instantiation.
void IterateAllDJIs(AppDomain * pAppDomain, Module * pLoaderModuleFilter, MethodDesc * pMethodDescFilter, DJIIterator * pEnum);
private:
// The linked list of JIT's of this version of the method. This will ALWAYS
// contain one element except for code in generic classes or generic methods,
// which may get JITted more than once under different type instantiations.
//
// We find the appropriate JitInfo by searching the list (nearly always this
// will return the first element of course).
//
// The JitInfos contain back pointers to this MethodInfo. They should never be associated
// with any other MethodInfo.
//
// USE ACCESSOR FUNCTION GetLatestJitInfo(), as it does lazy init of this field.
//
PTR_DebuggerJitInfo m_latestJitInfo;