forked from maraf/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.cpp
More file actions
9330 lines (7840 loc) · 339 KB
/
controller.cpp
File metadata and controls
9330 lines (7840 loc) · 339 KB
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: controller.cpp
//
//
// controller.cpp: Debugger execution control routines
//
// ****************************************************************************
// Putting code & #includes, #defines, etc, before the stdafx.h will
// cause the code,etc, to be silently ignored
//
#include "stdafx.h"
#include "openum.h"
#include "../inc/common.h"
#include "eeconfig.h"
#include "../../vm/methoditer.h"
#include "../../vm/tailcallhelp.h"
const char *GetTType( TraceType tt);
#define IsSingleStep(exception) ((exception) == EXCEPTION_SINGLE_STEP)
typedef enum __TailCallFunctionType {
TailCallThatReturns = 1,
StoreTailCallArgs = 2
} TailCallFunctionType;
// -------------------------------------------------------------------------
// DebuggerController routines
// -------------------------------------------------------------------------
SPTR_IMPL_INIT(DebuggerPatchTable, DebuggerController, g_patches, NULL);
SVAL_IMPL_INIT(BOOL, DebuggerController, g_patchTableValid, FALSE);
#if !defined(DACCESS_COMPILE)
DebuggerController *DebuggerController::g_controllers = NULL;
DebuggerControllerPage *DebuggerController::g_protections = NULL;
CrstStatic DebuggerController::g_criticalSection;
int DebuggerController::g_cTotalMethodEnter = 0;
// Is this patch at a position at which it's safe to take a stack?
bool DebuggerControllerPatch::IsSafeForStackTrace()
{
LIMITED_METHOD_CONTRACT;
TraceType tt = this->trace.GetTraceType();
Module *module = this->key.module;
BOOL managed = this->IsManagedPatch();
// Patches placed by MgrPush can come at lots of illegal spots. Can't take a stack trace here.
if ((module == NULL) && managed && (tt == TRACE_MGR_PUSH))
{
return false;
}
// Consider everything else legal.
// This is a little shady for TRACE_FRAME_PUSH. But TraceFrame() needs a stackInfo
// to get a RegDisplay (though almost nobody uses it, so perhaps it could be removed).
return true;
}
#ifndef FEATURE_EMULATE_SINGLESTEP
// returns a pointer to the shared buffer. each call will AddRef() the object
// before returning it so callers only need to Release() when they're finished with it.
SharedPatchBypassBuffer* DebuggerControllerPatch::GetOrCreateSharedPatchBypassBuffer()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
if (m_pSharedPatchBypassBuffer == NULL)
{
void *pSharedPatchBypassBufferRX = g_pDebugger->GetInteropSafeExecutableHeap()->Alloc(sizeof(SharedPatchBypassBuffer));
#if defined(HOST_OSX) && defined(HOST_ARM64)
ExecutableWriterHolder<SharedPatchBypassBuffer> sharedPatchBypassBufferWriterHolder((SharedPatchBypassBuffer*)pSharedPatchBypassBufferRX, sizeof(SharedPatchBypassBuffer));
void *pSharedPatchBypassBufferRW = sharedPatchBypassBufferWriterHolder.GetRW();
#else // HOST_OSX && HOST_ARM64
void *pSharedPatchBypassBufferRW = pSharedPatchBypassBufferRX;
#endif // HOST_OSX && HOST_ARM64
new (pSharedPatchBypassBufferRW) SharedPatchBypassBuffer();
m_pSharedPatchBypassBuffer = (SharedPatchBypassBuffer*)pSharedPatchBypassBufferRX;
_ASSERTE(m_pSharedPatchBypassBuffer);
TRACE_ALLOC(m_pSharedPatchBypassBuffer);
}
m_pSharedPatchBypassBuffer->AddRef();
return m_pSharedPatchBypassBuffer;
}
#endif // !FEATURE_EMULATE_SINGLESTEP
// @todo - remove all this splicing trash
// This Sort/Splice stuff just reorders the patches within a particular chain such
// that when we iterate through by calling GetPatch() and GetNextPatch(DebuggerControllerPatch),
// we'll get patches in increasing order of DebuggerControllerTypes.
// Practically, this means that calling GetPatch() will return EnC patches before stepping patches.
//
#if 1
void DebuggerPatchTable::SortPatchIntoPatchList(DebuggerControllerPatch **ppPatch)
{
LOG((LF_CORDB, LL_EVERYTHING, "DPT::SPIPL ppPatch: %p, pPatch: %p \n", ppPatch, (*ppPatch)));
#ifdef _DEBUG
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) Find(Hash((*ppPatch)), Key((*ppPatch)));
_ASSERTE(patchFirst == (*ppPatch));
_ASSERTE((*ppPatch)->controller->GetDCType() != DEBUGGER_CONTROLLER_STATIC);
#endif //_DEBUG
DebuggerControllerPatch *patchNext = GetNextPatch((*ppPatch));
//List contains one, (sorted) element
if (patchNext == NULL)
{
LOG((LF_CORDB, LL_INFO10000, "DPT::SPIPL: %p single element\n", (*ppPatch)));
return;
}
// If we decide to reorder the list, we'll need to keep the element
// indexed by the hash function as the (sorted)first item. Everything else
// chains off this element, can thus stay put.
// Thus, either the element we just added is already sorted, or else we'll
// have to move it elsewhere in the list, meaning that we'll have to swap
// the second item & the new item, so that the index points to the proper
// first item in the list.
//use Cur ptr for case where patch gets appended to list
DebuggerControllerPatch *patchCur = patchNext;
while (patchNext != NULL &&
((*ppPatch)->controller->GetDCType() >
patchNext->controller->GetDCType()) )
{
patchCur = patchNext;
patchNext = GetNextPatch(patchNext);
}
if (patchNext == GetNextPatch((*ppPatch)))
{
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch %p is already sorted\n", (*ppPatch)));
return; //already sorted
}
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch %p will be moved \n", (*ppPatch)));
//remove it from the list
SpliceOutOfList((*ppPatch));
// the kinda neat thing is: since we put it originally at the front of the list,
// and it's not in order, then it must be behind another element of this list,
// so we don't have to write any 'SpliceInFrontOf' code.
_ASSERTE(patchCur != NULL);
SpliceInBackOf((*ppPatch), patchCur);
LOG((LF_CORDB, LL_INFO10000,
"DPT::SPIPL: Patch %p is now sorted\n", (*ppPatch)));
}
// This can leave the list empty, so don't do this unless you put
// the patch back somewhere else.
void DebuggerPatchTable::SpliceOutOfList(DebuggerControllerPatch *patch)
{
// We need to get iHash, the index of the ptr within
// m_piBuckets, ie it's entry in the hashtable.
ULONG iHash = Hash(patch) % m_iBuckets;
ULONG iElement = m_piBuckets[iHash];
DebuggerControllerPatch *patchFirst
= (DebuggerControllerPatch *) EntryPtr(iElement);
// Fix up pointers to chain
if (patchFirst == patch)
{
// The first patch shouldn't have anything behind it.
_ASSERTE(patch->entry.iPrev == DPT_INVALID_SLOT);
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
m_piBuckets[iHash] = patch->entry.iNext;
}
else
{
m_piBuckets[iHash] = DPT_INVALID_SLOT;
}
}
if (patch->entry.iNext != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iPrev = patch->entry.iPrev;
}
if (patch->entry.iPrev != DPT_INVALID_SLOT)
{
EntryPtr(patch->entry.iNext)->iNext = patch->entry.iNext;
}
patch->entry.iNext = DPT_INVALID_SLOT;
patch->entry.iPrev = DPT_INVALID_SLOT;
}
void DebuggerPatchTable::SpliceInBackOf(DebuggerControllerPatch *patchAppend,
DebuggerControllerPatch *patchEnd)
{
ULONG iAppend = ItemIndex((HASHENTRY*)patchAppend);
ULONG iEnd = ItemIndex((HASHENTRY*)patchEnd);
patchAppend->entry.iPrev = iEnd;
patchAppend->entry.iNext = patchEnd->entry.iNext;
if (patchAppend->entry.iNext != DPT_INVALID_SLOT)
EntryPtr(patchAppend->entry.iNext)->iPrev = iAppend;
patchEnd->entry.iNext = iAppend;
}
#endif
//-----------------------------------------------------------------------------
// Stack safety rules.
// In general, we're safe to crawl whenever we're in preemptive mode.
// We're also must be safe at any spot the thread could get synchronized,
// because that means that the thread will be stopped to let the debugger shell
// inspect it and that can definitely take stack traces.
// Basically the only unsafe spot is in the middle of goofy stub with some
// partially constructed frame while in coop mode.
//-----------------------------------------------------------------------------
// Safe if we're at certain types of patches.
// See Patch::IsSafeForStackTrace for details.
StackTraceTicket::StackTraceTicket(DebuggerControllerPatch * patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->IsSafeForStackTrace());
}
// Safe if there was already another stack trace at this spot. (Grandfather clause)
// This is commonly used for StepOut, which takes runs stacktraces to crawl up
// the stack to find a place to patch.
StackTraceTicket::StackTraceTicket(ControllerStackInfo * info)
{
_ASSERTE(info != NULL);
// Ensure that the other stack info object actually executed (and thus was
// actually valid).
_ASSERTE(info->m_dbgExecuted);
}
// Safe b/c the context shows we're in native managed code.
// This must be safe because we could always set a managed breakpoint by native
// offset and thus synchronize the shell at this spot. So this is
// a specific example of the Synchronized case. The fact that we don't actually
// synchronize doesn't make us any less safe.
StackTraceTicket::StackTraceTicket(const BYTE * ip)
{
_ASSERTE(g_pEEInterface->IsManagedNativeCode(ip));
}
// Safe it we're at a Synchronized point point.
StackTraceTicket::StackTraceTicket(Thread * pThread)
{
_ASSERTE(pThread != NULL);
// If we're synchronized, the debugger should be stopped.
// That means all threads are synced and must be safe to take a stacktrace.
// Thus we don't even need to do a thread-specific check.
_ASSERTE(g_pDebugger->IsStopped());
}
// DebuggerUserBreakpoint has a special case of safety. See that ctor for details.
StackTraceTicket::StackTraceTicket(DebuggerUserBreakpoint * p)
{
_ASSERTE(p != NULL);
}
//void ControllerStackInfo::GetStackInfo(): GetStackInfo
// is invoked by the user to trigger the stack walk. This will
// cause the stack walk detailed in the class description to happen.
// Thread* thread: The thread to do the stack walk on.
// void* targetFP: Can be either NULL (meaning that the bottommost
// frame is the target), or an frame pointer, meaning that the
// caller wants information about a specific frame.
// CONTEXT* pContext: A pointer to a CONTEXT structure. Can be null,
// we use our temp context.
// bool suppressUMChainFromCLRToCOMMethodFrameGeneric - A ridiculous flag that is trying to narrowly
// target a fix for issue 650903.
// StackTraceTicket - ticket to ensure that we actually have permission for this stacktrace
void ControllerStackInfo::GetStackInfo(
StackTraceTicket ticket,
Thread *thread,
FramePointer targetFP,
CONTEXT *pContext,
bool suppressUMChainFromCLRToCOMMethodFrameGeneric
)
{
_ASSERTE(thread != NULL);
BOOL contextValid = (pContext != NULL);
if (!contextValid)
{
// We're assuming the thread is protected w/ a frame (which includes the redirection
// case). The stackwalker will use that protection to prime the context.
pContext = &this->m_tempContext;
}
else
{
// If we provided an explicit context for this thread, it better not be redirected.
_ASSERTE(!ISREDIRECTEDTHREAD(thread));
}
// Mark this stackwalk as valid so that it can in turn be used to grandfather
// in other stackwalks.
INDEBUG(m_dbgExecuted = true);
m_activeFound = false;
m_returnFound = false;
m_bottomFP = LEAF_MOST_FRAME;
m_targetFP = targetFP;
m_targetFrameFound = (m_targetFP == LEAF_MOST_FRAME);
m_specialChainReason = CHAIN_NONE;
m_suppressUMChainFromCLRToCOMMethodFrameGeneric = suppressUMChainFromCLRToCOMMethodFrameGeneric;
int result = DebuggerWalkStack(thread,
LEAF_MOST_FRAME,
pContext,
contextValid,
WalkStack,
(void *) this,
FALSE);
_ASSERTE(m_activeFound); // All threads have at least one unmanaged frame
if (result == SWA_DONE)
{
_ASSERTE(!HasReturnFrame()); // We didn't find a managed return frame
_ASSERTE(HasReturnFrame(true)); // All threads have at least one unmanaged frame
}
}
//---------------------------------------------------------------------------------------
//
// This function "undoes" an unwind, i.e. it takes the active frame (the current frame)
// and sets it to be the return frame (the caller frame). Currently it is only used by
// the stepper to step out of an LCG method. See DebuggerStepper::DetectHandleLCGMethods()
// for more information.
//
// Assumptions:
// The current frame is valid on entry.
//
// Notes:
// After this function returns, the active frame on this instance of ControllerStackInfo will no longer be valid.
//
// This function is specifically for DebuggerStepper::DetectHandleLCGMethods(). Using it in other scencarios may
// require additional changes.
//
void ControllerStackInfo::SetReturnFrameWithActiveFrame()
{
// Copy the active frame into the return frame.
m_returnFound = true;
m_returnFrame = m_activeFrame;
// Invalidate the active frame.
m_activeFound = false;
m_activeFrame = {};
m_activeFrame.fp = LEAF_MOST_FRAME;
}
// Fill in a controller-stack info.
StackWalkAction ControllerStackInfo::WalkStack(FrameInfo *pInfo, void *data)
{
LIMITED_METHOD_CONTRACT;
_ASSERTE(!pInfo->HasStubFrame()); // we didn't ask for stub frames.
ControllerStackInfo *i = (ControllerStackInfo *) data;
// save this info away for later use.
if (i->m_bottomFP == LEAF_MOST_FRAME)
i->m_bottomFP = pInfo->fp;
// This is part of the targeted fix for issue 650903 (see the other
// parts in code:TrackUMChain and code:DebuggerStepper::TrapStepOut).
//
// pInfo->fIgnoreThisFrameIfSuppressingUMChainFromCLRToCOMMethodFrameGeneric has been
// set by TrackUMChain to help us remember that the current frame we're looking at is
// CLRToCOMMethodFrameGeneric (we can't rely on looking at pInfo->frame to check
// this), and i->m_suppressUMChainFromCLRToCOMMethodFrameGeneric has been set by the
// dude initiating this walk to remind us that our goal in life is to do a Step Out
// during managed-only debugging. These two things together tell us we should ignore
// this frame, rather than erroneously identifying it as the target frame.
//
#ifdef FEATURE_COMINTEROP
if(i->m_suppressUMChainFromCLRToCOMMethodFrameGeneric &&
(pInfo->chainReason == CHAIN_ENTER_UNMANAGED) &&
(pInfo->fIgnoreThisFrameIfSuppressingUMChainFromCLRToCOMMethodFrameGeneric))
{
return SWA_CONTINUE;
}
#endif // FEATURE_COMINTEROP
//have we reached the correct frame yet?
if (!i->m_targetFrameFound &&
IsEqualOrCloserToLeaf(i->m_targetFP, pInfo->fp))
{
i->m_targetFrameFound = true;
}
if (i->m_targetFrameFound )
{
// Ignore Enter-managed chains.
if (pInfo->chainReason == CHAIN_ENTER_MANAGED)
{
return SWA_CONTINUE;
}
if (i->m_activeFound )
{
if (pInfo->chainReason == CHAIN_CLASS_INIT)
i->m_specialChainReason = pInfo->chainReason;
if (pInfo->fp != i->m_activeFrame.fp) // avoid dups
{
i->m_returnFrame = *pInfo;
#if defined(FEATURE_EH_FUNCLETS)
CopyREGDISPLAY(&(i->m_returnFrame.registers), &(pInfo->registers));
#endif // FEATURE_EH_FUNCLETS
i->m_returnFound = true;
// We care if the current frame is unmanaged
// Continue unless we found a managed return frame.
return pInfo->managed ? SWA_ABORT : SWA_CONTINUE;
}
}
else
{
i->m_activeFrame = *pInfo;
#if defined(FEATURE_EH_FUNCLETS)
CopyREGDISPLAY(&(i->m_activeFrame.registers), &(pInfo->registers));
#endif // FEATURE_EH_FUNCLETS
i->m_activeFound = true;
return SWA_CONTINUE;
}
}
return SWA_CONTINUE;
}
//
// Note that patches may be reallocated - do not keep a pointer to a patch.
//
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForMethodDef(DebuggerController *controller,
Module *module,
mdMethodDef md,
MethodDesc* pMethodDescFilter,
size_t offset,
BOOL offsetIsIL,
DebuggerPatchKind kind,
FramePointer fp,
AppDomain *pAppDomain,
SIZE_T primaryEnCVersion,
DebuggerJitInfo *dji)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
LOG( (LF_CORDB,LL_INFO10000,"DPT:APFMD 0x%x with dji %p, %s offset 0x%zx controller:%p AD:%p\n",
md, dji, (offsetIsIL ? "IL" : "native"), offset, controller, pAppDomain));
DebuggerFunctionKey key;
key.module = module;
key.md = md;
// Get a new uninitialized patch object
DebuggerControllerPatch *patch = (DebuggerControllerPatch *) Add(HashKey(&key));
if (patch == NULL)
ThrowOutOfMemory();
#ifndef FEATURE_EMULATE_SINGLESTEP
patch->Initialize();
#endif // !FEATURE_EMULATE_SINGLESTEP
//initialize the patch data structure.
InitializePRD(&(patch->opcode));
patch->controller = controller;
patch->key.module = module;
patch->key.md = md;
patch->pMethodDescFilter = pMethodDescFilter;
patch->offset = offset;
patch->offsetIsIL = offsetIsIL;
patch->address = NULL;
patch->fp = fp;
patch->trace.Bad_SetTraceType(DPT_DEFAULT_TRACE_TYPE); // TRACE_OTHER
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
patch->patchId = m_patchId++;
if (kind == PATCH_KIND_IL_PRIMARY)
{
_ASSERTE(dji == NULL);
patch->encVersion = primaryEnCVersion;
}
else
{
patch->dji = dji;
}
patch->kind = kind;
if (dji != NULL)
{
LOG((LF_CORDB,LL_INFO10000,"DPT:APFMD w/ encVersion 0x%zx, patchId:0x%zx\n",
dji->m_encVersion, patch->patchId));
}
else if (kind == PATCH_KIND_IL_PRIMARY)
{
LOG((LF_CORDB,LL_INFO10000,"DPT:APFMD w/ encVersion 0x%zx, patchId:0x%zx (primary)\n",
primaryEnCVersion, patch->patchId));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"DPT:APFMD w/ no dji or dmi, patchId:0x%zx\n",
patch->patchId));
}
// This patch is not yet bound or activated
_ASSERTE( !patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL primary patch.
_ASSERTE(patch->IsILPrimaryPatch() || patch->offsetIsIL == FALSE);
// The only kind of patch that allows a MethodDescFilter is the IL primary patch
_ASSERTE(patch->IsILPrimaryPatch() || patch->pMethodDescFilter == NULL);
// Zero is the only native offset that we allow to bind across different jitted
// code bodies. There isn't any sensible meaning to binding at some other native offset.
// Even if all the code bodies had an instruction that started at that offset there is
// no guarantee those instructions represent a semantically equivalent point in the
// method's execution.
_ASSERTE(!(patch->IsILPrimaryPatch() && !patch->offsetIsIL && patch->offset != 0));
return patch;
}
// Create and bind a patch to the specified address
// The caller should immediately activate the patch since we typically expect bound patches
// will always be activated.
DebuggerControllerPatch *DebuggerPatchTable::AddPatchForAddress(DebuggerController *controller,
MethodDesc *fd,
size_t offset,
DebuggerPatchKind kind,
CORDB_ADDRESS_TYPE *address,
FramePointer fp,
AppDomain *pAppDomain,
DebuggerJitInfo *dji,
SIZE_T patchId,
TraceType traceType)
{
CONTRACTL
{
THROWS;
MODE_ANY;
GC_NOTRIGGER;
}
CONTRACTL_END;
_ASSERTE(kind == PATCH_KIND_NATIVE_MANAGED || kind == PATCH_KIND_NATIVE_UNMANAGED);
LOG((LF_CORDB,LL_INFO10000,"DCP:AddPatchForAddress bound "
"absolute to 0x%p with dji 0x%p (mdDef:0x%x) "
"controller:0x%p AD:0x%p\n",
address, dji, (fd!=NULL?fd->GetMemberDef():0), controller,
pAppDomain));
// get new uninitialized patch object
DebuggerControllerPatch *patch =
(DebuggerControllerPatch *) Add(HashAddress(address));
if (patch == NULL)
{
ThrowOutOfMemory();
}
#ifndef FEATURE_EMULATE_SINGLESTEP
patch->Initialize();
#endif // !FEATURE_EMULATE_SINGLESTEP
// initialize the patch data structure
InitializePRD(&(patch->opcode));
patch->controller = controller;
if (fd == NULL)
{
patch->key.module = NULL;
patch->key.md = mdTokenNil;
}
else
{
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
patch->pMethodDescFilter = NULL;
patch->offset = offset;
patch->offsetIsIL = FALSE;
patch->address = address;
patch->fp = fp;
patch->trace.Bad_SetTraceType(traceType);
patch->refCount = 1; // AddRef()
patch->fSaveOpcode = false;
patch->pAppDomain = pAppDomain;
if (patchId == DCP_PATCHID_INVALID)
patch->patchId = m_patchId++;
else
patch->patchId = patchId;
patch->dji = dji;
patch->kind = kind;
if (dji == NULL)
{
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version with no dji, patchId:0x%zx\n", patch->patchId));
}
else
{
LOG((LF_CORDB,LL_INFO10000,"AddPatchForAddress w/ version 0x%zx, "
"patchId:0x%zx\n", dji->m_methodInfo->GetCurrentEnCVersion(), patch->patchId));
_ASSERTE( fd==NULL || fd == dji->m_nativeCodeVersion.GetMethodDesc() );
}
SortPatchIntoPatchList(&patch);
// This patch is bound but not yet activated
_ASSERTE( patch->IsBound() );
_ASSERTE( !patch->IsActivated() );
// The only kind of patch with IL offset is the IL primary patch.
_ASSERTE(patch->IsILPrimaryPatch() || patch->offsetIsIL == FALSE);
return patch;
}
// Set the native address for this patch.
void DebuggerPatchTable::BindPatch(DebuggerControllerPatch *patch, CORDB_ADDRESS_TYPE *address)
{
_ASSERTE(patch != NULL);
_ASSERTE(address != NULL);
_ASSERTE( !patch->IsILPrimaryPatch() );
_ASSERTE(!patch->IsBound() );
//Since the actual patch doesn't move, we don't have to worry about
//zeroing out the opcode field (see lengthy comment above)
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete(HashKey(&patch->key), ItemIndex((HASHENTRY*)patch));
patch->address = address;
CHashTable::Add(HashAddress(address), ItemIndex((HASHENTRY*)patch));
SortPatchIntoPatchList(&patch);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
}
// Disassociate a patch from a specific code address.
void DebuggerPatchTable::UnbindPatch(DebuggerControllerPatch *patch)
{
_ASSERTE(patch != NULL);
_ASSERTE(patch->kind != PATCH_KIND_IL_PRIMARY);
_ASSERTE(patch->IsBound() );
_ASSERTE(!patch->IsActivated() );
//<REVISIT_TODO>@todo We're hosed if the patch hasn't been primed with
// this info & we can't get it...</REVISIT_TODO>
if (patch->key.module == NULL ||
patch->key.md == mdTokenNil)
{
MethodDesc *fd = g_pEEInterface->GetNativeCodeMethodDesc(
dac_cast<PCODE>(patch->address));
_ASSERTE( fd != NULL );
patch->key.module = g_pEEInterface->MethodDescGetModule(fd);
patch->key.md = fd->GetMemberDef();
}
// Update it's index entry in the table to use it's unbound key
// Since the patch is double-hashed based off Address, if we change the address,
// we must remove and reinsert the patch.
CHashTable::Delete( HashAddress(patch->address),
ItemIndex((HASHENTRY*)patch));
patch->address = NULL; // we're no longer bound to this address
CHashTable::Add( HashKey(&patch->key),
ItemIndex((HASHENTRY*)patch));
_ASSERTE(!patch->IsBound() );
}
void DebuggerPatchTable::RemovePatch(DebuggerControllerPatch *patch)
{
// Since we're deleting this patch, it must not be activated (i.e. it must not have a stored opcode)
_ASSERTE( !patch->IsActivated() );
#ifndef FEATURE_EMULATE_SINGLESTEP
patch->DoCleanup();
#endif // !FEATURE_EMULATE_SINGLESTEP
//
// Because of the implementation of CHashTable, we can safely
// delete elements while iterating through the table. This
// behavior is relied upon - do not change to a different
// implementation without considering this fact.
//
Delete(Hash(patch), (HASHENTRY *) patch);
}
DebuggerControllerPatch *DebuggerPatchTable::GetNextPatch(DebuggerControllerPatch *prev)
{
ULONG iNext;
HASHENTRY *psEntry;
// Start at the next entry in the chain.
// @todo - note that: EntryPtr(ItemIndex(x)) == x
iNext = EntryPtr(ItemIndex((HASHENTRY*)prev))->iNext;
// Search until we hit the end.
while (iNext != UINT32_MAX)
{
// Compare the keys.
psEntry = EntryPtr(iNext);
// Careful here... we can hash the entries in this table
// by two types of keys. In this type of search, the type
// of the second key (psEntry) does not necessarily
// indicate the type of the first key (prev), so we have
// to check for sure.
DebuggerControllerPatch *pc2 = (DebuggerControllerPatch*)psEntry;
if (((pc2->address == NULL) && (prev->address == NULL)) ||
((pc2->address != NULL) && (prev->address != NULL)))
if (!Cmp(Key(prev), psEntry))
return pc2;
// Advance to the next item in the chain.
iNext = psEntry->iNext;
}
return NULL;
}
#ifdef _DEBUG
void DebuggerPatchTable::CheckPatchTable()
{
if ((TADDR)NULL != m_pcEntries)
{
LOG((LF_CORDB,LL_INFO1000, "DPT:CPT: %u\n", m_iEntries));
DebuggerControllerPatch *dcp;
ULONG i = 0;
while (i++ < m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->opcode != 0 )
{
dcp->LogInstance();
}
}
}
}
#endif // _DEBUG
// Count how many patches are in the table.
// Use for asserts
int DebuggerPatchTable::GetNumberOfPatches()
{
int total = 0;
if ((TADDR)NULL != m_pcEntries)
{
DebuggerControllerPatch *dcp;
ULONG i = 0;
while (i++ <m_iEntries)
{
dcp = (DebuggerControllerPatch*)&(((DebuggerControllerPatch *)m_pcEntries)[i]);
if (dcp->IsActivated() || !dcp->IsFree())
total++;
}
}
return total;
}
#if defined(_DEBUG)
//-----------------------------------------------------------------------------
// Debug check that we only have 1 thread-starter per thread.
// pNew - the new DTS. We'll make sure there's not already a DTS on this thread.
//-----------------------------------------------------------------------------
void DebuggerController::EnsureUniqueThreadStarter(DebuggerThreadStarter * pNew)
{
// This lock should be safe to take since our base class ctor takes it.
ControllerLockHolder lockController;
DebuggerController * pExisting = g_controllers;
while(pExisting != NULL)
{
if (pExisting->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (pExisting != pNew)
{
// If we have 2 thread starters, they'd better be on different threads.
_ASSERTE((pExisting->GetThread() != pNew->GetThread()));
}
}
pExisting = pExisting->m_next;
}
}
#endif
//-----------------------------------------------------------------------------
// If we have a thread-starter on the given EE thread, make sure it's cancel.
// Thread-Starters normally delete themselves when they fire. But if the EE
// destroys the thread before it fires, then we'd still have an active DTS.
//-----------------------------------------------------------------------------
void DebuggerController::CancelOutstandingThreadStarter(Thread * pThread)
{
_ASSERTE(pThread != NULL);
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter - checking on thread=%p\n", pThread));
ControllerLockHolder lockController;
DebuggerController * p = g_controllers;
while(p != NULL)
{
if (p->GetDCType() == DEBUGGER_CONTROLLER_THREAD_STARTER)
{
if (p->GetThread() == pThread)
{
LOG((LF_CORDB, LL_EVERYTHING, "DC:CancelOutstandingThreadStarter Found=%p\n", p));
// There's only 1 DTS per thread, so once we find it, we can quit.
p->Delete();
p = NULL;
break;
}
}
p = p->m_next;
}
// The common case is that our DTS hit its patch and did a SendEvent (and
// deleted itself). So usually we'll get through the whole list w/o deleting anything.
}
//void DebuggerController::Initialize() Sets up the static
// variables for the static DebuggerController class.
// How: initializes the critical section
HRESULT DebuggerController::Initialize()
{
CONTRACT(HRESULT)
{
THROWS;
GC_NOTRIGGER;
// This can be called in an "early attach" case, so DebuggerIsInvolved()
// will be b/c we don't realize the debugger's attaching to us.
//PRECONDITION(DebuggerIsInvolved());
POSTCONDITION(CheckPointer(g_patches));
POSTCONDITION(RETVAL == S_OK);
}
CONTRACT_END;
if (g_patches == NULL)
{
ZeroMemory(&g_criticalSection, sizeof(g_criticalSection)); // Init() expects zero-init memory.
// NOTE: CRST_UNSAFE_ANYMODE prevents a GC mode switch when entering this crst.
// If you remove this flag, we will switch to preemptive mode when entering
// g_criticalSection, which means all functions that enter it will become
// GC_TRIGGERS. (This includes all uses of ControllerLockHolder.) So be sure
// to update the contracts if you remove this flag.
g_criticalSection.Init(CrstDebuggerController,
(CrstFlags)(CRST_UNSAFE_ANYMODE | CRST_REENTRANCY | CRST_DEBUGGER_THREAD));
g_patches = new (interopsafe) DebuggerPatchTable();
_ASSERTE(g_patches != NULL); // throws on oom
HRESULT hr = g_patches->Init();
if (FAILED(hr))
{
DeleteInteropSafe(g_patches);
ThrowHR(hr);
}
g_patchTableValid = TRUE;
TRACE_ALLOC(g_patches);
}
_ASSERTE(g_patches != NULL);
RETURN (S_OK);
}
//---------------------------------------------------------------------------------------
//
// Constructor for a controller
//
// Arguments:
// pThread - thread that controller has affinity to. NULL if no thread - affinity.
// pAppdomain - appdomain that controller has affinity to. NULL if no AD affinity.
//
//
// Notes:
// "Affinity" is per-controller specific. Affinity is generally passed on to
// any patches the controller creates. So if a controller has affinity to Thread X,
// then any patches it creates will only fire on Thread-X.
//
//---------------------------------------------------------------------------------------
DebuggerController::DebuggerController(Thread * pThread, AppDomain * pAppDomain)
: m_pAppDomain(pAppDomain),
m_thread(pThread),
m_singleStep(false),
m_exceptionHook(false),
m_traceCall(0),
m_traceCallFP(ROOT_MOST_FRAME),
m_unwindFP(LEAF_MOST_FRAME),
m_eventQueuedCount(0),
m_deleted(false),
m_fEnableMethodEnter(false),
m_multicastDelegateHelper(false),
m_externalMethodFixup(false)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
CONSTRUCTOR_CHECK;
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO10000, "DC::DC %p m_eventQueuedCount=%d\n", this, m_eventQueuedCount));
ControllerLockHolder lockController;
{
m_next = g_controllers;
g_controllers = this;
}
}
//---------------------------------------------------------------------------------------
//
// Debugger::Controller::DeleteAllControlers - deletes all debugger contollers
//
// Arguments:
// None
//
// Return Value:
// None
//
// Notes:
// This is used at detach time to remove all DebuggerControllers. This will remove all
// patches and do whatever other cleanup individual DebuggerControllers consider
// necessary to allow the debugger to detach and the process to run normally.
//
void DebuggerController::DeleteAllControllers()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
ControllerLockHolder lockController;
DebuggerController * pDebuggerController = g_controllers;
DebuggerController * pNextDebuggerController = NULL;
while (pDebuggerController != NULL)