-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
controller.h
2115 lines (1738 loc) · 79.8 KB
/
controller.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.
//*****************************************************************************
// File: controller.h
//
//
// Debugger control flow object
//
//*****************************************************************************
#ifndef CONTROLLER_H_
#define CONTROLLER_H_
/* ========================================================================= */
#if !defined(DACCESS_COMPILE)
#include "frameinfo.h"
/* ------------------------------------------------------------------------- *
* Forward declarations
* ------------------------------------------------------------------------- */
class DebuggerPatchSkip;
class DebuggerThreadStarter;
class DebuggerController;
class DebuggerControllerQueue;
struct DebuggerControllerPatch;
class DebuggerUserBreakpoint;
class ControllerStackInfo;
typedef struct _DR6 *PDR6;
typedef struct _DR6 {
DWORD B0 : 1;
DWORD B1 : 1;
DWORD B2 : 1;
DWORD B3 : 1;
DWORD Pad1 : 9;
DWORD BD : 1;
DWORD BS : 1;
DWORD BT : 1;
} DR6;
typedef struct _DR7 *PDR7;
typedef struct _DR7 {
DWORD L0 : 1;
DWORD G0 : 1;
DWORD L1 : 1;
DWORD G1 : 1;
DWORD L2 : 1;
DWORD G2 : 1;
DWORD L3 : 1;
DWORD G3 : 1;
DWORD LE : 1;
DWORD GE : 1;
DWORD Pad1 : 3;
DWORD GD : 1;
DWORD Pad2 : 1;
DWORD Pad3 : 1;
DWORD Rwe0 : 2;
DWORD Len0 : 2;
DWORD Rwe1 : 2;
DWORD Len1 : 2;
DWORD Rwe2 : 2;
DWORD Len2 : 2;
DWORD Rwe3 : 2;
DWORD Len3 : 2;
} DR7;
// Ticket for ensuring that it's safe to get a stack trace.
class StackTraceTicket
{
public:
// Each ctor is a rule for why it's safety to run a stacktrace.
// Safe if we're at certain types of patches.
StackTraceTicket(DebuggerControllerPatch * patch);
// Safe if there was already another stack trace at this spot. (Grandfather clause)
StackTraceTicket(ControllerStackInfo * info);
// Safe it we're at a Synchronized point point.
StackTraceTicket(Thread * pThread);
// Safe b/c the context shows we're in native managed code
StackTraceTicket(const BYTE * ip);
// DebuggerUserBreakpoint has a special case of safety.
StackTraceTicket(DebuggerUserBreakpoint * p);
// This is like a contract violation.
// Unsafe tickets. Use as:
// StackTraceTicket ticket(StackTraceTicket::UNSAFE_TICKET);
enum EUNSAFE {
// Ticket is unsafe. Potential issue.
UNSAFE_TICKET = 0,
// For some wacky reason, it's safe to take a stacktrace here, but
// there's not an easily verifiable rule. Use this ticket very sparingly
// because it's much more difficult to verify.
SPECIAL_CASE_TICKET = 1
};
StackTraceTicket(EUNSAFE e) { };
private:
// Tickets can't be copied around. Hide these definitions so to enforce that.
// We still need the Copy ctor so that it can be passed in as a parameter.
void operator=(StackTraceTicket & other);
};
/* ------------------------------------------------------------------------- *
* ControllerStackInfo utility
* ------------------------------------------------------------------------- *
* class ControllerStackInfo is a class designed
* to simply obtain a two-frame stack trace: it will obtain the bottommost
* framepointer (m_bottomFP), a given target frame (m_activeFrame), and the
* frame above the target frame (m_returnFrame). Note that the target frame
* may be the bottommost, 'active' frame, or it may be a frame higher up in
* the stack. ControllerStackInfo accomplishes this by starting at the
* bottommost frame and walking upwards until it reaches the target frame,
* whereupon it records the m_activeFrame info, gets called once more to
* fill in the m_returnFrame info, and thereafter stops the stack walk.
*
* public:
* void * m_bottomFP: Frame pointer for the
* bottommost (most active)
* frame. We can add more later, if we need it. Currently just used in
* TrapStep. NULL indicates an uninitialized value.
*
* void * m_targetFP: The frame pointer to the frame
* that we actually want the info of.
*
* bool m_targetFrameFound: Set to true if
* WalkStack finds the frame indicated by targetFP handed to GetStackInfo
* false otherwise.
*
* FrameInfo m_activeFrame: A FrameInfo
* describing the target frame. This should always be valid after a
* call to GetStackInfo.
*
* private:
* bool m_activeFound: Set to true if we found the target frame.
* bool m_returnFound: Set to true if we found the target's return frame.
*
* FrameInfo m_returnFrame: A FrameInfo
* describing the frame above the target frame, if target's
* return frame were found (call HasReturnFrame() to see if this is
* valid). Otherwise, this will be the same as m_activeFrame, above
*/
class ControllerStackInfo
{
public:
friend class StackTraceTicket;
ControllerStackInfo()
{
INDEBUG(m_dbgExecuted = false);
}
FramePointer m_bottomFP;
FramePointer m_targetFP;
bool m_targetFrameFound;
FrameInfo m_activeFrame;
CorDebugChainReason m_specialChainReason;
// static StackWalkAction ControllerStackInfo::WalkStack() The
// callback that will be invoked by the DebuggerWalkStackProc.
// Note that the data argument is the "this" pointer to the
// ControllerStackInfo.
static StackWalkAction WalkStack(FrameInfo *pInfo, void *data);
//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 ensuring that we have permission to call this.
void GetStackInfo(
StackTraceTicket ticket,
Thread *thread,
FramePointer targetFP,
CONTEXT *pContext,
bool suppressUMChainFromCLRToCOMMethodFrameGeneric = false
);
//bool ControllerStackInfo::HasReturnFrame() Returns
// true if m_returnFrame is valid. Returns false
// if m_returnFrame is set to m_activeFrame
bool HasReturnFrame(bool allowUnmanaged = false) {LIMITED_METHOD_CONTRACT; return m_returnFound && (allowUnmanaged || m_returnFrame.managed); }
FrameInfo& GetReturnFrame(bool allowUnmanaged = false) {LIMITED_METHOD_CONTRACT; return HasReturnFrame(allowUnmanaged) ? m_returnFrame : m_activeFrame; }
// 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.
void SetReturnFrameWithActiveFrame();
private:
// If we don't have a valid context, then use this temp cache.
CONTEXT m_tempContext;
bool m_activeFound;
bool m_returnFound;
FrameInfo m_returnFrame;
// A ridiculous flag that is targeting a very narrow fix at issue 650903
// (4.5.1/Blue). This is set for the duration of a stackwalk designed to
// help us "Step Out" to a managed frame (i.e., managed-only debugging).
bool m_suppressUMChainFromCLRToCOMMethodFrameGeneric;
// Track if this stackwalk actually happened.
// This is used by the StackTraceTicket(ControllerStackInfo * info) ticket.
INDEBUG(bool m_dbgExecuted);
};
#endif // !DACCESS_COMPILE
/* ------------------------------------------------------------------------- *
* DebuggerController routines
* ------------------------------------------------------------------------- */
// simple ref-counted buffer that's shared among DebuggerPatchSkippers for a
// given DebuggerControllerPatch. upon creation the refcount will be 1. when
// the last skipper and controller are cleaned up the buffer will be released.
// note that there isn't a clear owner of this buffer since a controller can be
// cleaned up while the final skipper is still in flight.
class SharedPatchBypassBuffer
{
public:
SharedPatchBypassBuffer() : m_refCount(1)
{
#ifdef _DEBUG
DWORD cbToProtect = MAX_INSTRUCTION_LENGTH;
_ASSERTE(DbgIsExecutable((BYTE*)PatchBypass, cbToProtect));
#endif // _DEBUG
// sentinel value indicating uninitialized data
*(reinterpret_cast<DWORD*>(PatchBypass)) = SentinelValue;
#ifdef TARGET_AMD64
*(reinterpret_cast<DWORD*>(BypassBuffer)) = SentinelValue;
RipTargetFixup = 0;
RipTargetFixupSize = 0;
#elif defined(TARGET_ARM64)
RipTargetFixup = 0;
#endif
}
~SharedPatchBypassBuffer()
{
// trap deletes that don't go through Release()
_ASSERTE(m_refCount == 0);
}
LONG AddRef()
{
#if !defined(DACCESS_COMPILE) && defined(HOST_OSX) && defined(HOST_ARM64)
ExecutableWriterHolder<LONG> refCountWriterHolder(&m_refCount, sizeof(LONG));
LONG *pRefCountRW = refCountWriterHolder.GetRW();
#else // !DACCESS_COMPILE && HOST_OSX && HOST_ARM64
LONG *pRefCountRW = &m_refCount;
#endif // !DACCESS_COMPILE && HOST_OSX && HOST_ARM64
LONG newRefCount = InterlockedIncrement(pRefCountRW);
_ASSERTE(newRefCount > 0);
return newRefCount;
}
LONG Release()
{
#if !DACCESS_COMPILE && HOST_OSX && HOST_ARM64
ExecutableWriterHolder<LONG> refCountWriterHolder(&m_refCount, sizeof(LONG));
LONG *pRefCountRW = refCountWriterHolder.GetRW();
#else // !DACCESS_COMPILE && HOST_OSX && HOST_ARM64
LONG *pRefCountRW = &m_refCount;
#endif // !DACCESS_COMPILE && HOST_OSX && HOST_ARM64
LONG newRefCount = InterlockedDecrement(pRefCountRW);
_ASSERTE(newRefCount >= 0);
if (newRefCount == 0)
{
TRACE_FREE(this);
DeleteInteropSafeExecutable(this);
}
return newRefCount;
}
// "PatchBypass" must be the first field of this class for alignment to be correct.
BYTE PatchBypass[MAX_INSTRUCTION_LENGTH];
#if defined(TARGET_AMD64)
// If you update this value, make sure that it fits in the data payload of a
// DebuggerHeapExecutableMemoryChunk.
const static int cbBufferBypass = 0x40;
BYTE BypassBuffer[cbBufferBypass];
UINT_PTR RipTargetFixup;
BYTE RipTargetFixupSize;
#elif defined(TARGET_ARM64)
UINT_PTR RipTargetFixup;
#endif
private:
const static DWORD SentinelValue = 0xffffffff;
LONG m_refCount;
};
// struct DebuggerFunctionKey: Provides a means of hashing unactivated
// breakpoints, it's used mainly for the case where the function to put
// the breakpoint in hasn't been JITted yet.
// Module* module: Module that the method belongs to.
// mdMethodDef md: meta data token for the method.
struct DebuggerFunctionKey1
{
PTR_Module module;
mdMethodDef md;
};
typedef DebuggerFunctionKey1 UNALIGNED DebuggerFunctionKey;
// IL Primary: Breakpoints on IL code may need to be applied to multiple
// copies of code. Historically generics was the only way IL code was JITTed
// multiple times but more recently the CodeVersionManager and tiered compilation
// provide more open-ended mechanisms to have multiple native code bodies derived
// from a single IL method body.
// The "primary" is a patch we keep to record the IL offset or native offset, and
// is used to create new "replica" patches. For native offsets only offset 0 is allowed
// because that is the only one that we think would have a consistent semantic
// meaning across different code bodies.
// There can also be multiple IL bodies for the same method given EnC or ReJIT.
// A given primary breakpoint is tightly bound to one particular IL body determined
// by encVersion. ReJIT + breakpoints isn't currently supported.
//
//
// IL Replica: The replicas created from Primary patches. If the primary used an IL offset
// then the replica also initially has an IL offset that will later become a native offset.
// If the primary uses a native offset (0) then the replica will also have a native offset (0).
// These patches always resolve to addresses in jitted code.
//
//
// NativeManaged: A patch we apply to managed code, usually for walkers etc. If this code
// is jitted then these patches are always bound to one exact jitted code body.
// If you need to be 100% sure I suggest you do more code review but I believe we also
// use this for managed code from other code generators such as a stub or statically compiled
// code that executes in cooperative mode.
//
//
// NativeUnmanaged: A patch applied to any kind of native code.
enum DebuggerPatchKind { PATCH_KIND_IL_PRIMARY, PATCH_KIND_IL_REPLICA, PATCH_KIND_NATIVE_MANAGED, PATCH_KIND_NATIVE_UNMANAGED };
// struct DebuggerControllerPatch: An entry in the patch (hash) table,
// this should contain all the info that's needed over the course of a
// patch's lifetime.
//
// FREEHASHENTRY entry: Three ULONGs, this is required
// by the underlying hashtable implementation
// DWORD opcode: A nonzero opcode && address field means that
// the patch has been applied to something. This may not be a full
// opcode, it is possible it is a partial opcode.
// A patch with a zero'd opcode field means that the patch isn't
// actually tracking a valid break opcode. See DebuggerPatchTable
// for more details.
// DebuggerController *controller: The controller that put this
// patch here.
// BOOL fSaveOpcode: If true, then unapply patch will save
// a copy of the opcode in opcodeSaved, and apply patch will
// copy opcodeSaved to opcode rather than grabbing the opcode
// from the instruction. This is useful mainly when the JIT
// has moved code, and we don't want to erroneously pick up the
// user break instruction.
// Full story:
// FJIT moves the code. Once that's done, it calls Debugger->MoveCode(MethodDesc
// *) to let us know the code moved. At that point, unbind all the breakpoints
// in the method. Then we whip over all the patches, and re-bind all the
// patches in the method. However, we can't guarantee that the code will exist
// in both the old & new locations exclusively of each other (the method could
// be 0xFF bytes big, and get moved 0x10 bytes in one direction), so instead of
// simply re-using the unbind/rebind logic as it is, we need a special case
// wherein the old method isn't valid. Instead, we'll copy opcode into
// opcodeSaved, and then zero out opcode (we need to zero out opcode since that
// tells us that the patch is invalid, if the right side sees it). Thus the run-
// around.
// DebuggerPatchKind: see above
// DWORD opcodeSaved: Contains an opcode if fSaveOpcode == true
// SIZE_T nVersion: If the patch is stored by IL offset, then we
// must also store the version ID so that we know which version
// this is supposed to be applied to. Note that this will only
// be set for DebuggerBreakpoints & DebuggerEnCBreakpoints. For
// others, it should be set to DMI_VERSION_INVALID. For constants,
// see DebuggerJitInfo
// DebuggerJitInfo dji: A pointer to the debuggerJitInfo that describes
// the method (and version) that this patch is applied to. This field may
// also have the value DebuggerJitInfo::DMI_VERSION_INVALID
// SIZE_T patchId: Within a given patch table, all patches have a
// semi-unique ID. There should be one and only 1 patch for a given
// {pid,nVersion} tuple, thus ensuring that we don't duplicate
// patches from multiple, previous versions.
// AppDomain * pAppDomain: Either NULL (patch applies to all appdomains
// that the debugger is attached to)
// or contains a pointer to an AppDomain object (patch applies only to
// that A.D.)
// NOTE: due to unkind abuse of type system you cannot add ctor/dtor to this
// type and expect them to be automatically invoked!
struct DebuggerControllerPatch
{
friend class DebuggerPatchTable;
friend class DebuggerController;
FREEHASHENTRY entry;
DebuggerController *controller;
DebuggerFunctionKey key;
SIZE_T offset;
PTR_CORDB_ADDRESS_TYPE address;
FramePointer fp;
PRD_TYPE opcode; // See description above.
BOOL fSaveOpcode;
PRD_TYPE opcodeSaved;
BOOL offsetIsIL;
TraceDestination trace;
MethodDesc* pMethodDescFilter; // used for IL Primary patches that should only bind to jitted
// code versions for a single generic instantiation
private:
DebuggerPatchKind kind;
int refCount;
union
{
SIZE_T encVersion; // used for Primary patches, to record which EnC version this Primary applies to
DebuggerJitInfo *dji; // used for Replica and native patches, though only when tracking JIT Info
};
#ifndef FEATURE_EMULATE_SINGLESTEP
// this is shared among all the skippers for this controller. see the comments
// right before the definition of SharedPatchBypassBuffer for lifetime info.
SharedPatchBypassBuffer* m_pSharedPatchBypassBuffer;
#endif // !FEATURE_EMULATE_SINGLESTEP
public:
SIZE_T patchId;
AppDomain *pAppDomain;
BOOL IsNativePatch();
BOOL IsManagedPatch();
BOOL IsILPrimaryPatch();
BOOL IsILReplicaPatch();
DebuggerPatchKind GetKind();
// A patch has DJI if it was created with it or if it has been mapped to a
// function that has been jitted while JIT tracking was on. It does not
// necessarily mean the patch is bound. ILPrimary patches never have DJIs.
// Patches will never have DJIs if we are not tracking JIT information.
//
// Patches can also be unbound, e.g. in UnbindFunctionPatches. Any DJI gets cleared
// when the patch is unbound. This appears to be used as an indicator
// to Debugger::MapAndBindFunctionPatches to make sure that
// we don't skip the patch when we get new code.
BOOL HasDJI()
{
return (!IsILPrimaryPatch() && dji != NULL);
}
DebuggerJitInfo *GetDJI()
{
_ASSERTE(!IsILPrimaryPatch());
return dji;
}
// Determine if the patch is related to EnC remap logic.
BOOL IsEnCRemapPatch();
// These tell us which EnC version a patch relates to. They are used
// to determine if we are mapping a patch to a new version.
//
BOOL HasEnCVersion()
{
return (IsILPrimaryPatch() || HasDJI());
}
SIZE_T GetEnCVersion()
{
_ASSERTE(HasEnCVersion());
return (IsILPrimaryPatch() ? encVersion : (HasDJI() ? GetDJI()->m_encVersion : CorDB_DEFAULT_ENC_FUNCTION_VERSION));
}
// We set the DJI explicitly after mapping a patch
// to freshly jitted code or to a new version. The Unbind/Bind/MovedCode mess
// for the FJIT will also set the DJI to NULL as an indicator that Debugger::MapAndBindFunctionPatches
// should not skip the patch.
void SetDJI(DebuggerJitInfo *newDJI)
{
_ASSERTE(!IsILPrimaryPatch());
dji = newDJI;
}
// A patch is bound if we've mapped it to a real honest-to-goodness
// native address.
// Note that we currently activate all patches immediately after binding them, and
// delete all patches after unactivating them. This means that the window where
// a patch is bound but not active is very small (and should always be protected by
// a lock). We rely on this correlation in a few places, and ASSERT it explicitly there.
BOOL IsBound()
{
if( address == NULL ) {
// patch is unbound, cannot be active
_ASSERTE( PRDIsEmpty(opcode) );
return FALSE;
}
// IL Primary patches are never bound.
_ASSERTE( !IsILPrimaryPatch() );
return TRUE;
}
// It would be nice if we never needed IsBreakpointPatch or IsStepperPatch,
// but a few bits of the existing code look at which controller type is involved.
BOOL IsBreakpointPatch();
BOOL IsStepperPatch();
bool IsActivated()
{
// Patch is activate if we've stored a non-zero opcode
// Note: this might be a problem as opcode 0 may be a valid opcode (see issue 366221).
if( PRDIsEmpty(opcode) ) {
return FALSE;
}
// Patch is active, so it must also be bound
_ASSERTE( address != NULL );
return TRUE;
}
bool IsFree() {return (refCount == 0);}
bool IsTriggering() {return (refCount > 1);}
// Is this patch at a position at which it's safe to take a stack?
bool IsSafeForStackTrace();
#ifndef FEATURE_EMULATE_SINGLESTEP
// gets a pointer to the shared buffer
SharedPatchBypassBuffer* GetOrCreateSharedPatchBypassBuffer();
// entry point for general initialization when the controller is being created
void Initialize()
{
m_pSharedPatchBypassBuffer = NULL;
}
// entry point for general cleanup when the controller is being removed from the patch table
void DoCleanup()
{
if (m_pSharedPatchBypassBuffer != NULL)
m_pSharedPatchBypassBuffer->Release();
}
#endif // !FEATURE_EMULATE_SINGLESTEP
void LogInstance()
{
LOG((LF_CORDB, LL_INFO10000, " DCP: %p\n"
" patchId: 0x%zx\n"
" offset: 0x%zx\n"
" address: %p\n"
" offsetIsIL: %s\n"
" refCount: %d\n"
" kind: %d\n"
" IsBound: %s\n"
" IsNativePatch: %s\n"
" IsManagedPatch: %s\n"
" IsILPrimaryPatch: %s\n"
" IsILReplicaPatch: %s\n",
this, patchId, offset, address, (offsetIsIL ? "true" : "false"), refCount, GetKind(),
(IsBound() ? "true" : "false"),
(IsNativePatch() ? "true" : "false"),
(IsManagedPatch() ? "true" : "false"),
(IsILPrimaryPatch() ? "true" : "false"),
(IsILReplicaPatch() ? "true" : "false")));
}
};
typedef DPTR(DebuggerControllerPatch) PTR_DebuggerControllerPatch;
/* class DebuggerPatchTable: This is the table that contains
* information about the patches (breakpoints) maintained by the
* debugger for a variety of purposes.
* The only tricky part is that
* patches can be hashed either by the address that they're applied to,
* or by DebuggerFunctionKey. If address is equal to zero, then the
* patch is hashed by DebuggerFunctionKey.
*
* Patch table inspection scheme:
*
* We have to be able to inspect memory (read/write) from the right
* side w/o the help of the left side. When we do unmanaged debugging,
* we need to be able to R/W memory out of a debuggee s.t. the debugger
* won't see our patches. So we have to be able to read our patch table
* from the left side, which is problematic since we know that the left
* side will be arbitrarily frozen, but we don't know where.
*
* So our scheme is this:
* we'll send a pointer to the g_patches table over in startup,
* and when we want to inspect it at runtime, we'll freeze the left side,
* then read-memory the "data" (m_pcEntries) array over to the right. We'll
* iterate through the array & assume that anything with a non-zero opcode
* and address field is valid. To ensure that the assumption is ok, we
* use the zeroing allocator which zeros out newly created space, and
* we'll be very careful about zeroing out the opcode field during the
* Unapply operation
*
* NOTE: Don't mess with the memory protections on this while the
* left side is frozen (ie, no threads are executing).
* WriteMemory depends on being able to write the patchtable back
* if it was read successfully.
*/
#define DPT_INVALID_SLOT (UINT32_MAX)
#define DPT_DEFAULT_TRACE_TYPE TRACE_OTHER
/* Although CHashTableAndData can grow, we always use a fixed number of buckets.
* This is problematic for tables like the patch table which are usually small, but
* can become huge. When the number of entries far exceeds the number of buckets,
* lookup and addition basically degrade into linear searches. There is a trade-off
* here between wasting memory for unused buckets, and performance of large tables.
* Also note that the number of buckets should be a prime number.
*/
#define DPT_HASH_BUCKETS 1103
class DebuggerPatchTable : private CHashTableAndData<CNewZeroData>
{
VPTR_BASE_CONCRETE_VTABLE_CLASS(DebuggerPatchTable);
public:
virtual ~DebuggerPatchTable() = default;
friend class DebuggerRCThread;
private:
//incremented so that we can get DPT-wide unique PIDs.
// pid = Patch ID.
SIZE_T m_patchId;
// Given a patch, retrieves the correct key. The return value of this function is passed to Cmp(), Find(), etc.
SIZE_T Key(DebuggerControllerPatch *patch)
{
LIMITED_METHOD_DAC_CONTRACT;
// Most clients of CHashTable pass a host pointer as the key. However, the key really could be
// anything. In our case, the key can either be a host pointer of type DebuggerFunctionKey or
// the address of the patch.
if (patch->address == NULL)
{
return (SIZE_T)(&patch->key);
}
else
{
return (SIZE_T)(dac_cast<TADDR>(patch->address));
}
}
// Given two DebuggerControllerPatches, tells
// whether they are equal or not. Does this by comparing the correct
// key.
// BYTE* pc1: If pc2 is hashed by address,
// pc1 is an address. If
// pc2 is hashed by DebuggerFunctionKey,
// pc1 is a DebuggerFunctionKey
//Returns true if the two patches are equal, false otherwise
BOOL Cmp(SIZE_T k1, const HASHENTRY * pc2)
{
LIMITED_METHOD_DAC_CONTRACT;
DebuggerControllerPatch * pPatch2 = dac_cast<PTR_DebuggerControllerPatch>(const_cast<HASHENTRY *>(pc2));
if (pPatch2->address == NULL)
{
// k1 is a host pointer of type DebuggerFunctionKey.
DebuggerFunctionKey * pKey1 = reinterpret_cast<DebuggerFunctionKey *>(k1);
return ((pKey1->module != pPatch2->key.module) || (pKey1->md != pPatch2->key.md));
}
else
{
return ((SIZE_T)(dac_cast<TADDR>(pPatch2->address)) != k1);
}
}
//Computes a hash value based on an address
ULONG HashAddress(PTR_CORDB_ADDRESS_TYPE address)
{
LIMITED_METHOD_DAC_CONTRACT;
return (ULONG)(SIZE_T)(dac_cast<TADDR>(address));
}
//Computes a hash value based on a DebuggerFunctionKey
ULONG HashKey(DebuggerFunctionKey * pKey)
{
SUPPORTS_DAC;
return HashPtr(pKey->md, pKey->module);
}
//Computes a hash value from a patch, using the address field
// if the patch is hashed by address, using the DebuggerFunctionKey
// otherwise
ULONG Hash(DebuggerControllerPatch * pPatch)
{
SUPPORTS_DAC;
if (pPatch->address == NULL)
return HashKey(&(pPatch->key));
else
return HashAddress(pPatch->address);
}
//Public Members
public:
enum {
DCP_PATCHID_INVALID,
DCP_PATCHID_FIRST_VALID,
};
#ifndef DACCESS_COMPILE
DebuggerPatchTable() : CHashTableAndData<CNewZeroData>(DPT_HASH_BUCKETS) { }
HRESULT Init()
{
WRAPPER_NO_CONTRACT;
m_patchId = DCP_PATCHID_FIRST_VALID;
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
return NewInit(17, sizeof(DebuggerControllerPatch), 101);
}
// Assuming that the chain of patches (as defined by all the
// GetNextPatch from this patch) are either sorted or NULL, take the given
// patch (which should be the first patch in the chain). This
// is called by AddPatch to make sure that the order of the
// patches is what we want for things like EnC, DePatchSkips,etc.
void SortPatchIntoPatchList(DebuggerControllerPatch **ppPatch);
void SpliceOutOfList(DebuggerControllerPatch *patch);
void SpliceInBackOf(DebuggerControllerPatch *patchAppend,
DebuggerControllerPatch *patchEnd);
//
// Note that patches may be reallocated - do not keep a pointer to a patch.
//
DebuggerControllerPatch *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);
DebuggerControllerPatch *AddPatchForAddress(DebuggerController *controller,
MethodDesc *fd,
size_t offset,
DebuggerPatchKind kind,
CORDB_ADDRESS_TYPE *address,
FramePointer fp,
AppDomain *pAppDomain,
DebuggerJitInfo *dji = NULL,
SIZE_T patchId = DCP_PATCHID_INVALID,
TraceType traceType = DPT_DEFAULT_TRACE_TYPE);
// Set the native address for this patch.
void BindPatch(DebuggerControllerPatch *patch, CORDB_ADDRESS_TYPE *address);
void UnbindPatch(DebuggerControllerPatch *patch);
void RemovePatch(DebuggerControllerPatch *patch);
// This is a sad legacy workaround. The patch table (implemented as this
// class) is shared across process. We publish the runtime offsets of
// some key fields. Since those fields are private, we have to provide
// accessors here. So if you're not using these functions, don't start.
// We can hopefully remove them.
static SIZE_T GetOffsetOfEntries()
{
// assert that we the offsets of these fields in the base class is
// the same as the offset of this field in this class.
_ASSERTE((void*)(DebuggerPatchTable*)NULL == (void*)(CHashTableAndData<CNewZeroData>*)NULL);
return helper_GetOffsetOfEntries();
}
static SIZE_T GetOffsetOfCount()
{
_ASSERTE((void*)(DebuggerPatchTable*)NULL == (void*)(CHashTableAndData<CNewZeroData>*)NULL);
return helper_GetOffsetOfCount();
}
// GetPatch find the first patch in the hash table
// that is hashed by matching the {Module,mdMethodDef} to the
// patch's DebuggerFunctionKey. This will NOT find anything
// hashed by address, even if that address is within the
// method specified.
// You can use GetNextPatch to iterate through all the patches keyed by
// this Module,mdMethodDef pair
DebuggerControllerPatch *GetPatch(Module *module, mdToken md)
{
DebuggerFunctionKey key;
key.module = module;
key.md = md;
return reinterpret_cast<DebuggerControllerPatch *>(Find(HashKey(&key), (SIZE_T)&key));
}
#endif // #ifndef DACCESS_COMPILE
// GetPatch will translate find the first patch in the hash
// table that is hashed by address. It will NOT find anything hashed
// by {Module,mdMethodDef}, or by MethodDesc.
DebuggerControllerPatch * GetPatch(PTR_CORDB_ADDRESS_TYPE address)
{
SUPPORTS_DAC;
ARM_ONLY(_ASSERTE(dac_cast<TADDR>(address) & THUMB_CODE));
DebuggerControllerPatch * pPatch =
dac_cast<PTR_DebuggerControllerPatch>(Find(HashAddress(address), (SIZE_T)(dac_cast<TADDR>(address))));
return pPatch;
}
DebuggerControllerPatch *GetNextPatch(DebuggerControllerPatch *prev);
// Find the first patch in the patch table, and store
// index info in info. Along with GetNextPatch, this can
// iterate through the whole patch table. Note that since the
// hashtable operates via iterating through all the contents
// of all the buckets, if you add an entry while iterating
// through the table, you may or may not iterate across
// the new entries. You will iterate through all the entries
// that were present at the beginning of the run. You
// safely delete anything you've already iterated by, anything
// else is kinda risky.
DebuggerControllerPatch * GetFirstPatch(HASHFIND * pInfo)
{
SUPPORTS_DAC;
return dac_cast<PTR_DebuggerControllerPatch>(FindFirstEntry(pInfo));
}
// Along with GetFirstPatch, this can iterate through
// the whole patch table. See GetFirstPatch for more info
// on the rules of iterating through the table.
DebuggerControllerPatch * GetNextPatch(HASHFIND * pInfo)
{
SUPPORTS_DAC;
return dac_cast<PTR_DebuggerControllerPatch>(FindNextEntry(pInfo));
}
// Used by DebuggerController to translate an index
// of a patch into a direct pointer.
inline HASHENTRY * GetEntryPtr(ULONG iEntry)
{
SUPPORTS_DAC;
return EntryPtr(iEntry);
}
// Used by DebuggerController to grab indices of patches
// rather than holding direct pointers to them.
inline ULONG GetItemIndex(HASHENTRY * p)
{
SUPPORTS_DAC;
return ItemIndex(p);
}
#ifdef _DEBUG
public:
// DEBUG An internal debugging routine, it iterates
// through the hashtable, stopping at every
// single entry, no matter what it's state.
void CheckPatchTable();
#endif // _DEBUG
// Count how many patches are in the table.
// Use for asserts
int GetNumberOfPatches();
};
typedef VPTR(class DebuggerPatchTable) PTR_DebuggerPatchTable;
#if !defined(DACCESS_COMPILE)
// DebuggerControllerPage|Will eventually be used for
// 'break when modified' behaviour'
typedef struct DebuggerControllerPage
{
DebuggerControllerPage *next;
const BYTE *start, *end;
DebuggerController *controller;
bool readable;
} DebuggerControllerPage;
// DEBUGGER_CONTROLLER_TYPE: Identifies the type of the controller.
// It exists b/c we have RTTI turned off.
// Note that the order of these is important - SortPatchIntoPatchList
// relies on this ordering.
//
// DEBUGGER_CONTROLLER_STATIC|Base class response. Should never be
// seen, since we shouldn't be asking the base class about this.
// DEBUGGER_CONTROLLER_BREAKPOINT|DebuggerBreakpoint
// DEBUGGER_CONTROLLER_STEPPER|DebuggerStepper
// DEBUGGER_CONTROLLER_THREAD_STARTER|DebuggerThreadStarter
// DEBUGGER_CONTROLLER_ENC|DebuggerEnCBreakpoint
// DEBUGGER_CONTROLLER_PATCH_SKIP|DebuggerPatchSkip
// DEBUGGER_CONTROLLER_JMC_STEPPER|DebuggerJMCStepper - steps through Just-My-Code
// DEBUGGER_CONTROLLER_CONTINUABLE_EXCEPTION|DebuggerContinuableExceptionBreakpoint
enum DEBUGGER_CONTROLLER_TYPE
{
DEBUGGER_CONTROLLER_THREAD_STARTER,
DEBUGGER_CONTROLLER_ENC,
DEBUGGER_CONTROLLER_PATCH_SKIP,
DEBUGGER_CONTROLLER_BREAKPOINT,
DEBUGGER_CONTROLLER_STEPPER,
DEBUGGER_CONTROLLER_FUNC_EVAL_COMPLETE,
DEBUGGER_CONTROLLER_USER_BREAKPOINT, // UserBreakpoints are used by Runtime threads to
// send that they've hit a user breakpoint to the Right Side.
DEBUGGER_CONTROLLER_JMC_STEPPER, // Stepper that only stops in JMC-functions.
DEBUGGER_CONTROLLER_CONTINUABLE_EXCEPTION,
DEBUGGER_CONTROLLER_DATA_BREAKPOINT,
DEBUGGER_CONTROLLER_STATIC,
};
enum TP_RESULT
{
TPR_TRIGGER, // This controller wants to SendEvent
TPR_IGNORE, // This controller doesn't want to SendEvent
TPR_TRIGGER_ONLY_THIS, // This, and only this controller, should be triggered.
// Right now, only the DebuggerEnCRemap controller
// returns this, the remap patch should be the first
// patch in the list.
TPR_TRIGGER_ONLY_THIS_AND_LOOP,
// This, and only this controller, should be triggered.
// Right now, only the DebuggerEnCRemap controller
// returns this, the remap patch should be the first
// patch in the list.
// After triggering this, DPOSS should skip the
// ActivatePatchSkip call, so we hit the other
// breakpoints at this location.
TPR_IGNORE_AND_STOP, // Don't SendEvent, and stop asking other
// controllers if they want to.
// Service any previous triggered controllers.
};
enum SCAN_TRIGGER
{
ST_PATCH = 0x1, // Only look for patches
ST_SINGLE_STEP = 0x2, // Look for patches, and single-steps.
} ;
enum TRIGGER_WHY
{
TY_NORMAL = 0x0,
TY_SHORT_CIRCUIT= 0x1, // EnC short circuit - see DispatchPatchOrSingleStep
} ;
// the return value for DebuggerController::DispatchPatchOrSingleStep
enum DPOSS_ACTION
{
// the following enum has been carefully ordered to optimize the helper
// functions below. Do not re-order them w/o changing the helper funcs.
DPOSS_INVALID = 0x0, // invalid action value
DPOSS_DONT_CARE = 0x1, // don't care about this exception
DPOSS_USED_WITH_NO_EVENT = 0x2, // Care about this exception but won't send event to RS
DPOSS_USED_WITH_EVENT = 0x3, // Care about this exception and will send event to RS
};
// helper function
inline bool IsInUsedAction(DPOSS_ACTION action)
{
_ASSERTE(action != DPOSS_INVALID);
return (action >= DPOSS_USED_WITH_NO_EVENT);
}
inline void VerifyExecutableAddress(const BYTE* address)
{
// TODO: : when can we apply this to x86?
#if defined(HOST_64BIT)
#if defined(_DEBUG)
#ifndef TARGET_UNIX
MEMORY_BASIC_INFORMATION mbi;