forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrcthread.cpp
More file actions
1875 lines (1552 loc) · 64.2 KB
/
rcthread.cpp
File metadata and controls
1875 lines (1552 loc) · 64.2 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.
// See the LICENSE file in the project root for more information.
//*****************************************************************************
// File: RCThread.cpp
//
//
// Runtime Controller Thread
//
//*****************************************************************************
#include "stdafx.h"
#include "threadsuspend.h"
#ifndef FEATURE_PAL
#include "securitywrapper.h"
#endif
#include <aclapi.h>
#include <hosting.h>
#include "eemessagebox.h"
#ifndef SM_REMOTESESSION
#define SM_REMOTESESSION 0x1000
#endif
#include <limits.h>
#ifdef _DEBUG
// Declare statics
EEThreadId DebuggerRCThread::s_DbgHelperThreadId;
#endif
//
// Constructor
//
DebuggerRCThread::DebuggerRCThread(Debugger * pDebugger)
: m_debugger(pDebugger),
m_pDCB(NULL),
m_thread(NULL),
m_run(true),
m_threadControlEvent(NULL),
m_helperThreadCanGoEvent(NULL),
m_fDetachRightSide(false)
{
CONTRACTL
{
WRAPPER(THROWS);
GC_NOTRIGGER;
CONSTRUCTOR_CHECK;
}
CONTRACTL_END;
_ASSERTE(pDebugger != NULL);
for( int i = 0; i < IPC_TARGET_COUNT;i++)
{
m_rgfInitRuntimeOffsets[i] = true;
}
// Initialize this here because we Destroy it in the DTOR.
// Note that this function can't fail.
}
//
// Destructor. Cleans up all of the open handles the RC thread uses.
// This expects that the RC thread has been stopped and has terminated
// before being called.
//
DebuggerRCThread::~DebuggerRCThread()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
DESTRUCTOR_CHECK;
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO1000, "DebuggerRCThread::~DebuggerRCThread\n"));
// We explicitly leak the debugger object on shutdown. See Debugger::StopDebugger for details.
_ASSERTE(!"RCThread dtor should not be called.");
}
//---------------------------------------------------------------------------------------
//
// Close the IPC events associated with a debugger connection
//
// Notes:
// The only IPC connection supported is OOP.
//
//---------------------------------------------------------------------------------------
void DebuggerRCThread::CloseIPCHandles()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
if( m_pDCB != NULL)
{
m_pDCB->m_rightSideProcessHandle.Close();
}
}
//-----------------------------------------------------------------------------
// Helper to get the proper decorated name
// Caller ensures that pBufSize is large enough. We'll assert just to check,
// but no runtime failure.
// pBuf - the output buffer to write the decorated name in
// cBufSizeInChars - the size of the buffer in characters, including the null.
// pPrefx - The undecorated name of the event.
//-----------------------------------------------------------------------------
void GetPidDecoratedName(__out_ecount(cBufSizeInChars) WCHAR * pBuf,
int cBufSizeInChars,
const WCHAR * pPrefix)
{
LIMITED_METHOD_CONTRACT;
DWORD pid = GetCurrentProcessId();
GetPidDecoratedName(pBuf, cBufSizeInChars, pPrefix, pid);
}
//-----------------------------------------------------------------------------
// Simple wrapper to create win32 events.
// This helps make DebuggerRCThread::Init pretty, beccause we
// create lots of events there.
// These will either:
// 1) Create/Open and return an event
// 2) or throw an exception.
// @todo - should these be CLREvents? ClrCreateManualEvent / ClrCreateAutoEvent
//-----------------------------------------------------------------------------
HANDLE CreateWin32EventOrThrow(
LPSECURITY_ATTRIBUTES lpEventAttributes,
EEventResetType eType,
BOOL bInitialState
)
{
CONTRACT(HANDLE)
{
THROWS;
GC_NOTRIGGER;
PRECONDITION(CheckPointer(lpEventAttributes, NULL_OK));
POSTCONDITION(RETVAL != NULL);
}
CONTRACT_END;
HANDLE h = NULL;
h = WszCreateEvent(lpEventAttributes, (BOOL) eType, bInitialState, NULL);
if (h == NULL)
ThrowLastError();
RETURN h;
}
//-----------------------------------------------------------------------------
// Open an event. Another helper for DebuggerRCThread::Init
//-----------------------------------------------------------------------------
HANDLE OpenWin32EventOrThrow(
DWORD dwDesiredAccess,
BOOL bInheritHandle,
LPCWSTR lpName
)
{
CONTRACT(HANDLE)
{
THROWS;
GC_NOTRIGGER;
POSTCONDITION(RETVAL != NULL);
}
CONTRACT_END;
HANDLE h = WszOpenEvent(
dwDesiredAccess,
bInheritHandle,
lpName
);
if (h == NULL)
ThrowLastError();
RETURN h;
}
//---------------------------------------------------------------------------------------
//
// Init
//
// Initialize the IPC block.
//
// Arguments:
// hRsea - Handle to Right-Side Event Available event.
// hRser - Handle to Right-Side Event Read event.
// hLsea - Handle to Left-Side Event Available event.
// hLser - Handle to Left-Side Event Read event.
// hLsuwe - Handle to Left-Side unmanaged wait event.
//
// Notes:
// The Init method works since there are no virtual functions - don't add any virtual functions without
// changing this!
// We assume ownership of the handles as soon as we're called; regardless of our success.
// On failure, we throw.
// Initialization of the debugger control block occurs partly on the left side and partly on
// the right side. This initialization occurs in parallel, so it's unsafe to make assumptions about
// the order in which the fields will be initialized.
//
//
//---------------------------------------------------------------------------------------
HRESULT DebuggerIPCControlBlock::Init(
HANDLE hRsea,
HANDLE hRser,
HANDLE hLsea,
HANDLE hLser,
HANDLE hLsuwe
)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
}
CONTRACTL_END;
// NOTE this works since there are no virtual functions - don't add any without changing this!
// Although we assume the IPC block is zero-initialized by the OS upon creation, we still need to clear
// the memory here to protect ourselves from DOS attack. One scenario is when a malicious debugger
// pre-creates a bogus IPC block. This means that our synchronization scheme won't work in DOS
// attack scenarios, but we will be messed up anyway.
// WARNING!!! m_DCBSize is used as a semaphore and is set to non-zero to signal that initialization of the
// WARNING!!! DCB is complete. if you remove the below memset be sure to initialize m_DCBSize to zero in the ctor!
memset( this, 0, sizeof( DebuggerIPCControlBlock) );
// Setup version checking info.
m_verMajor = CLR_BUILD_VERSION;
m_verMinor = CLR_BUILD_VERSION_QFE;
#ifdef _DEBUG
m_checkedBuild = true;
#else
m_checkedBuild = false;
#endif
m_bHostingInFiber = false;
// Are we in fiber mode? In Whidbey, we do not support launch a fiber mode process
// nor do we support attach to a fiber mode process.
//
if (g_CORDebuggerControlFlags & DBCF_FIBERMODE)
{
m_bHostingInFiber = true;
}
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
// Copy RSEA and RSER into the control block.
if (!m_rightSideEventAvailable.SetLocal(hRsea))
{
ThrowLastError();
}
if (!m_rightSideEventRead.SetLocal(hRser))
{
ThrowLastError();
}
if (!m_leftSideUnmanagedWaitEvent.SetLocal(hLsuwe))
{
ThrowLastError();
}
#endif // !FEATURE_DBGIPC_TRANSPORT_VM
// Mark the debugger special thread list as not dirty, empty and null.
m_specialThreadListDirty = false;
m_specialThreadListLength = 0;
m_specialThreadList = NULL;
m_shutdownBegun = false;
return S_OK;
}
void DebuggerRCThread::WatchForStragglers(void)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_threadControlEvent != NULL);
LOG((LF_CORDB,LL_INFO100000, "DRCT::WFS:setting event to watch "
"for stragglers\n"));
SetEvent(m_threadControlEvent);
}
//---------------------------------------------------------------------------------------
//
// Init sets up all the objects that the RC thread will need to run.
//
//
// Return Value:
// S_OK on success. May also throw.
//
// Assumptions:
// Called during startup, even if we're not debugging.
//
//
//---------------------------------------------------------------------------------------
HRESULT DebuggerRCThread::Init(void)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
PRECONDITION(!ThisIsHelperThreadWorker()); // initialized by main thread
}
CONTRACTL_END;
LOG((LF_CORDB, LL_EVERYTHING, "DebuggerRCThreadInit called\n"));
DWORD dwStatus;
if (m_debugger == NULL)
{
ThrowHR(E_INVALIDARG);
}
// Init should only be called once.
if (g_pRCThread != NULL)
{
ThrowHR(E_FAIL);
}
g_pRCThread = this;
m_favorData.Init(); // throws
// Create the thread control event.
m_threadControlEvent = CreateWin32EventOrThrow(NULL, kAutoResetEvent, FALSE);
// Create the helper thread can go event.
m_helperThreadCanGoEvent = CreateWin32EventOrThrow(NULL, kManualResetEvent, TRUE);
m_pDCB = new(nothrow) DebuggerIPCControlBlock;
// Don't fail out because the shared memory failed to create
#if _DEBUG
if (m_pDCB == NULL)
{
LOG((LF_CORDB, LL_INFO10000,
"DRCT::I: Failed to get Debug IPC block.\n"));
}
#endif // _DEBUG
HRESULT hr;
#if defined(FEATURE_DBGIPC_TRANSPORT_VM)
if (m_pDCB)
{
hr = m_pDCB->Init(NULL, NULL, NULL, NULL, NULL);
_ASSERTE(SUCCEEDED(hr)); // throws on error.
}
#else //FEATURE_DBGIPC_TRANSPORT_VM
// Create the events that the thread will need to receive events
// from the out of process piece on the right side.
// We will not fail out if CreateEvent fails for RSEA or RSER. Because
// the worst case is that debugger cannot attach to debuggee.
//
HandleHolder rightSideEventAvailable(WszCreateEvent(NULL, (BOOL) kAutoResetEvent, FALSE, NULL));
// Security fix:
// We need to check the last error to see if the event was precreated or not
// If so, we need to release the handle right now.
//
dwStatus = GetLastError();
if (dwStatus == ERROR_ALREADY_EXISTS)
{
// clean up the handle now
rightSideEventAvailable.Clear();
}
HandleHolder rightSideEventRead(WszCreateEvent(NULL, (BOOL) kAutoResetEvent, FALSE, NULL));
// Security fix:
// We need to check the last error to see if the event was precreated or not
// If so, we need to release the handle right now.
//
dwStatus = GetLastError();
if (dwStatus == ERROR_ALREADY_EXISTS)
{
// clean up the handle now
rightSideEventRead.Clear();
}
HandleHolder leftSideUnmanagedWaitEvent(CreateWin32EventOrThrow(NULL, kManualResetEvent, FALSE));
// Copy RSEA and RSER into the control block only if shared memory is created without error.
if (m_pDCB)
{
// Since Init() gets ownership of handles as soon as it's called, we can
// release our ownership now.
rightSideEventAvailable.SuppressRelease();
rightSideEventRead.SuppressRelease();
leftSideUnmanagedWaitEvent.SuppressRelease();
// NOTE: initialization of the debugger control block occurs partly on the left side and partly on
// the right side. This initialization occurs in parallel, so it's unsafe to make assumptions about
// the order in which the fields will be initialized.
hr = m_pDCB->Init(rightSideEventAvailable,
rightSideEventRead,
NULL,
NULL,
leftSideUnmanagedWaitEvent);
_ASSERTE(SUCCEEDED(hr)); // throws on error.
}
#endif //FEATURE_DBGIPC_TRANSPORT_VM
if(m_pDCB)
{
// We have to ensure that most of the runtime offsets for the out-of-proc DCB are initialized right away. This is
// needed to support certian races during an interop attach. Since we can't know whether an interop attach will ever
// happen or not, we are forced to do this now. Note: this is really too early, as some data structures haven't been
// initialized yet!
hr = EnsureRuntimeOffsetsInit(IPC_TARGET_OUTOFPROC);
_ASSERTE(SUCCEEDED(hr)); // throw on error
// Note: we have to mark that we need the runtime offsets re-initialized for the out-of-proc DCB. This is because
// things like the patch table aren't initialized yet. Calling NeedRuntimeOffsetsReInit() ensures that this happens
// before we really need the patch table.
NeedRuntimeOffsetsReInit(IPC_TARGET_OUTOFPROC);
m_pDCB->m_helperThreadStartAddr = (void *) DebuggerRCThread::ThreadProcStatic;
m_pDCB->m_helperRemoteStartAddr = (void *) DebuggerRCThread::ThreadProcRemote;
m_pDCB->m_leftSideProtocolCurrent = CorDB_LeftSideProtocolCurrent;
m_pDCB->m_leftSideProtocolMinSupported = CorDB_LeftSideProtocolMinSupported;
LOG((LF_CORDB, LL_INFO10,
"DRCT::I: version info: %d.%d.%d current protocol=%d, min protocol=%d\n",
m_pDCB->m_verMajor,
m_pDCB->m_verMinor,
m_pDCB->m_checkedBuild,
m_pDCB->m_leftSideProtocolCurrent,
m_pDCB->m_leftSideProtocolMinSupported));
// Left-side always creates helper-thread.
// @dbgtodo inspection - by end of V3, LS will never create helper-thread :)
m_pDCB->m_rightSideShouldCreateHelperThread = false;
// m_DCBSize is used as a semaphore to indicate that the DCB is fully initialized.
// let's ensure that it's updated after all the other fields.
MemoryBarrier();
m_pDCB->m_DCBSize = sizeof(DebuggerIPCControlBlock);
}
return S_OK;
}
//---------------------------------------------------------------------------------------
//
// Setup the Runtime Offsets struct.
//
// Arguments:
// pDebuggerIPCControlBlock - Pointer to the debugger's portion of the IPC
// block, which this routine will write into the offsets of various parts of
// the runtime.
//
// Return Value:
// S_OK on success.
//
//---------------------------------------------------------------------------------------
HRESULT DebuggerRCThread::SetupRuntimeOffsets(DebuggerIPCControlBlock * pDebuggerIPCControlBlock)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
PRECONDITION(ThisMaybeHelperThread());
}
CONTRACTL_END;
// Allocate the struct if needed. We just fill in any existing one.
DebuggerIPCRuntimeOffsets * pDebuggerRuntimeOffsets = pDebuggerIPCControlBlock->m_pRuntimeOffsets;
if (pDebuggerRuntimeOffsets == NULL)
{
// Perhaps we should preallocate this. This is the only allocation
// that would force SendIPCEvent to throw an exception. It'd be very
// nice to have
CONTRACT_VIOLATION(ThrowsViolation);
pDebuggerRuntimeOffsets = new DebuggerIPCRuntimeOffsets();
_ASSERTE(pDebuggerRuntimeOffsets != NULL); // throws on oom
}
// Fill out the struct.
#ifdef FEATURE_INTEROP_DEBUGGING
pDebuggerRuntimeOffsets->m_genericHijackFuncAddr = Debugger::GenericHijackFunc;
// Set flares - these only exist for interop debugging.
pDebuggerRuntimeOffsets->m_signalHijackStartedBPAddr = (void*) SignalHijackStartedFlare;
pDebuggerRuntimeOffsets->m_excepForRuntimeHandoffStartBPAddr = (void*) ExceptionForRuntimeHandoffStartFlare;
pDebuggerRuntimeOffsets->m_excepForRuntimeHandoffCompleteBPAddr = (void*) ExceptionForRuntimeHandoffCompleteFlare;
pDebuggerRuntimeOffsets->m_signalHijackCompleteBPAddr = (void*) SignalHijackCompleteFlare;
pDebuggerRuntimeOffsets->m_excepNotForRuntimeBPAddr = (void*) ExceptionNotForRuntimeFlare;
pDebuggerRuntimeOffsets->m_notifyRSOfSyncCompleteBPAddr = (void*) NotifyRightSideOfSyncCompleteFlare;
pDebuggerRuntimeOffsets->m_debuggerWordTLSIndex = g_debuggerWordTLSIndex;
#if !defined(FEATURE_CORESYSTEM)
// Grab the address of RaiseException in kernel32 because we have to play some games with exceptions
// that are generated there (just another reason why mixed mode debugging is shady). See bug 476768.
HMODULE hModule = WszGetModuleHandle(W("kernel32.dll"));
_ASSERTE(hModule != NULL);
PREFAST_ASSUME(hModule != NULL);
pDebuggerRuntimeOffsets->m_raiseExceptionAddr = GetProcAddress(hModule, "RaiseException");
_ASSERTE(pDebuggerRuntimeOffsets->m_raiseExceptionAddr != NULL);
hModule = NULL;
#else
pDebuggerRuntimeOffsets->m_raiseExceptionAddr = NULL;
#endif
#endif // FEATURE_INTEROP_DEBUGGING
pDebuggerRuntimeOffsets->m_pPatches = DebuggerController::GetPatchTable();
pDebuggerRuntimeOffsets->m_pPatchTableValid = (BOOL*)DebuggerController::GetPatchTableValidAddr();
pDebuggerRuntimeOffsets->m_offRgData = DebuggerPatchTable::GetOffsetOfEntries();
pDebuggerRuntimeOffsets->m_offCData = DebuggerPatchTable::GetOffsetOfCount();
pDebuggerRuntimeOffsets->m_cbPatch = sizeof(DebuggerControllerPatch);
pDebuggerRuntimeOffsets->m_offAddr = offsetof(DebuggerControllerPatch, address);
pDebuggerRuntimeOffsets->m_offOpcode = offsetof(DebuggerControllerPatch, opcode);
pDebuggerRuntimeOffsets->m_cbOpcode = sizeof(PRD_TYPE);
pDebuggerRuntimeOffsets->m_offTraceType = offsetof(DebuggerControllerPatch, trace.type);
pDebuggerRuntimeOffsets->m_traceTypeUnmanaged = TRACE_UNMANAGED;
// @dbgtodo inspection - this should all go away or be obtained from DacDbi Primitives.
g_pEEInterface->GetRuntimeOffsets(&pDebuggerRuntimeOffsets->m_TLSIndex,
&pDebuggerRuntimeOffsets->m_TLSIsSpecialIndex,
&pDebuggerRuntimeOffsets->m_TLSCantStopIndex,
&pDebuggerRuntimeOffsets->m_EEThreadStateOffset,
&pDebuggerRuntimeOffsets->m_EEThreadStateNCOffset,
&pDebuggerRuntimeOffsets->m_EEThreadPGCDisabledOffset,
&pDebuggerRuntimeOffsets->m_EEThreadPGCDisabledValue,
&pDebuggerRuntimeOffsets->m_EEThreadFrameOffset,
&pDebuggerRuntimeOffsets->m_EEThreadMaxNeededSize,
&pDebuggerRuntimeOffsets->m_EEThreadSteppingStateMask,
&pDebuggerRuntimeOffsets->m_EEMaxFrameValue,
&pDebuggerRuntimeOffsets->m_EEThreadDebuggerFilterContextOffset,
&pDebuggerRuntimeOffsets->m_EEThreadCantStopOffset,
&pDebuggerRuntimeOffsets->m_EEFrameNextOffset,
&pDebuggerRuntimeOffsets->m_EEIsManagedExceptionStateMask);
// Remember the struct in the control block.
pDebuggerIPCControlBlock->m_pRuntimeOffsets = pDebuggerRuntimeOffsets;
return S_OK;
}
struct DebugFilterParam
{
DebuggerIPCEvent *event;
};
// Filter called when we throw an exception while Handling events.
static LONG _debugFilter(LPEXCEPTION_POINTERS ep, PVOID pv)
{
LOG((LF_CORDB, LL_INFO10,
"Unhandled exception in Debugger::HandleIPCEvent\n"));
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
#if defined(_DEBUG) || !defined(FEATURE_CORESYSTEM)
DebuggerIPCEvent *event = ((DebugFilterParam *)pv)->event;
DWORD pid = GetCurrentProcessId();
DWORD tid = GetCurrentThreadId();
DebuggerIPCEventType type = (DebuggerIPCEventType) (event->type & DB_IPCE_TYPE_MASK);
#endif // _DEBUG || !FEATURE_CORESYSTEM
// We should never AV here. In a debug build, throw up an assert w/ lots of useful (private) info.
#ifdef _DEBUG
{
// We can't really use SStrings on the helper thread; though if we're at this point, we've already died.
// So go ahead and risk it and use them anyways.
SString sStack;
StackScratchBuffer buffer;
GetStackTraceAtContext(sStack, ep->ContextRecord);
const CHAR *string = NULL;
EX_TRY
{
string = sStack.GetANSI(buffer);
}
EX_CATCH
{
string = "*Could not retrieve stack*";
}
EX_END_CATCH(RethrowTerminalExceptions);
CONSISTENCY_CHECK_MSGF(false,
("Unhandled exception on the helper thread.\nEvent=%s(0x%x)\nCode=0x%0x, Ip=0x%p, .cxr=%p, .exr=%p.\n pid=0x%x (%d), tid=0x%x (%d).\n-----\nStack of exception:\n%s\n----\n",
IPCENames::GetName(type), type,
ep->ExceptionRecord->ExceptionCode, GetIP(ep->ContextRecord), ep->ContextRecord, ep->ExceptionRecord,
pid, pid, tid, tid,
string));
}
#endif
// this message box doesn't work well on coresystem... we actually get in a recursive exception handling loop
#ifndef FEATURE_CORESYSTEM
// We took an AV on the helper thread. This is a catastrophic situation so we can
// simply call the EE's catastrophic message box to display the error.
EEMessageBoxCatastrophic(
IDS_DEBUG_UNHANDLEDEXCEPTION_IPC, IDS_DEBUG_SERVICE_CAPTION,
type,
ep->ExceptionRecord->ExceptionCode,
GetIP(ep->ContextRecord),
pid, pid, tid, tid);
#endif
// For debugging, we can change the behavior by manually setting eax.
// EXCEPTION_EXECUTE_HANDLER=1, EXCEPTION_CONTINUE_SEARCH=0, EXCEPTION_CONTINUE_EXECUTION=-1
return EXCEPTION_CONTINUE_SEARCH;
}
//---------------------------------------------------------------------------------------
//
// Primary function of the Runtime Controller thread. First, we let
// the Debugger Interface know that we're up and running. Then, we run
// the main loop.
//
//---------------------------------------------------------------------------------------
void DebuggerRCThread::ThreadProc(void)
{
CONTRACTL
{
NOTHROW;
GC_TRIGGERS; // Debugger::SuspendComplete can trigger GC
// Although we're the helper thread, we haven't set it yet.
DISABLED(PRECONDITION(ThisIsHelperThreadWorker()));
INSTANCE_CHECK;
}
CONTRACTL_END;
STRESS_LOG_RESERVE_MEM (0);
// This message actually serves a purpose (which is why it is always run)
// The Stress log is run during hijacking, when other threads can be suspended
// at arbitrary locations (including when holding a lock that NT uses to serialize
// all memory allocations). By sending a message now, we insure that the stress
// log will not allocate memory at these critical times an avoid deadlock.
{
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
STRESS_LOG0(LF_CORDB|LF_ALWAYS, LL_ALWAYS, "Debugger Thread spinning up\n");
// Call this to force creation of the TLS slots on helper-thread.
IsDbgHelperSpecialThread();
}
#ifdef _DEBUG
// Track the helper thread.
s_DbgHelperThreadId.SetToCurrentThread();
#endif
CantAllocHolder caHolder;
#ifdef _DEBUG
// Cause wait in the helper thread startup. This lets us test against certain races.
// 1 = 6 sec. (shorter than Poll)
// 2 = 12 sec (longer than Poll).
// 3 = infinite - never comes up.
static int fDelayHelper = -1;
if (fDelayHelper == -1)
{
fDelayHelper = UnsafeGetConfigDWORD(CLRConfig::INTERNAL_DbgDelayHelper);
}
if (fDelayHelper)
{
DWORD dwSleep = 6000;
switch(fDelayHelper)
{
case 1: dwSleep = 6000; break;
case 2: dwSleep = 12000; break;
case 3: dwSleep = INFINITE; break;
}
ClrSleepEx(dwSleep, FALSE);
}
#endif
LOG((LF_CORDB, LL_INFO1000, "DRCT::TP: helper thread spinning up...\n"));
// In case the shared memory is not initialized properly, it will be noop
if (m_pDCB == NULL)
{
return;
}
// Lock the debugger before spinning up.
Debugger::DebuggerLockHolder debugLockHolder(m_debugger);
if (m_pDCB->m_helperThreadId != 0)
{
// someone else has created a helper thread, we're outta here
// the most likely scenario here is that there was some kind of
// race between remotethread creation and localthread creation
LOG((LF_CORDB, LL_EVERYTHING, "Second debug helper thread creation detected, thread will safely suicide\n"));
// dbgLockHolder goes out of scope - implicit Release
return;
}
// this thread took the lock and there is no existing m_helperThreadID therefore
// this *IS* the helper thread and nobody else can be the helper thread
// the handle was created by the Start method
_ASSERTE(m_thread != NULL);
#ifdef _DEBUG
// Make sure that we have the proper permissions.
{
DWORD dwWaitResult = WaitForSingleObject(m_thread, 0);
_ASSERTE(dwWaitResult == WAIT_TIMEOUT);
}
#endif
// Mark that we're the true helper thread. Now that we've marked
// this, no other threads will ever become the temporary helper
// thread.
m_pDCB->m_helperThreadId = GetCurrentThreadId();
LOG((LF_CORDB, LL_INFO1000, "DRCT::TP: helper thread id is 0x%x helperThreadId\n",
m_pDCB->m_helperThreadId));
// If there is a temporary helper thread, then we need to wait for
// it to finish being the helper thread before we can become the
// helper thread.
if (m_pDCB->m_temporaryHelperThreadId != 0)
{
LOG((LF_CORDB, LL_INFO1000,
"DRCT::TP: temporary helper thread 0x%x is in the way, "
"waiting...\n",
m_pDCB->m_temporaryHelperThreadId));
debugLockHolder.Release();
// Wait for the temporary helper thread to finish up.
DWORD dwWaitResult = WaitForSingleObject(m_helperThreadCanGoEvent, INFINITE);
(void)dwWaitResult; //prevent "unused variable" error from GCC
LOG((LF_CORDB, LL_INFO1000, "DRCT::TP: done waiting for temp help to finish up.\n"));
_ASSERTE(dwWaitResult == WAIT_OBJECT_0);
_ASSERTE(m_pDCB->m_temporaryHelperThreadId==0);
}
else
{
LOG((LF_CORDB, LL_INFO1000, "DRCT::TP: no temp help in the way...\n"));
debugLockHolder.Release();
}
// Run the main loop as the true helper thread.
MainLoop();
}
void DebuggerRCThread::RightSideDetach(void)
{
_ASSERTE( m_fDetachRightSide == false );
m_fDetachRightSide = true;
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
CloseIPCHandles();
#endif // !FEATURE_DBGIPC_TRANSPORT_VM
}
//
// These defines control how many times we spin while waiting for threads to sync and how often. Note its higher in
// debug builds to allow extra time for threads to sync.
//
#define CorDB_SYNC_WAIT_TIMEOUT 20 // 20ms
#ifdef _DEBUG
#define CorDB_MAX_SYNC_SPIN_COUNT (10000 / CorDB_SYNC_WAIT_TIMEOUT) // (10 seconds)
#else
#define CorDB_MAX_SYNC_SPIN_COUNT (3000 / CorDB_SYNC_WAIT_TIMEOUT) // (3 seconds)
#endif
//
// NDPWhidbey issue 10749 - Due to a compiler change for vc7.1,
// Don't inline this function!
// PAL_TRY allocates space on the stack and so can not be used within a loop,
// else we'll slowly leak stack space w/ each interation and get an overflow.
// So make this its own function to enforce that we free the stack space between
// iterations.
//
bool HandleIPCEventWrapper(Debugger* pDebugger, DebuggerIPCEvent *e)
{
struct Param : DebugFilterParam
{
Debugger* pDebugger;
bool wasContinue;
} param;
param.event = e;
param.pDebugger = pDebugger;
param.wasContinue = false;
PAL_TRY(Param *, pParam, ¶m)
{
pParam->wasContinue = pParam->pDebugger->HandleIPCEvent(pParam->event);
}
PAL_EXCEPT_FILTER(_debugFilter)
{
LOG((LF_CORDB, LL_INFO10, "Unhandled exception caught in Debugger::HandleIPCEvent\n"));
}
PAL_ENDTRY
return param.wasContinue;
}
bool DebuggerRCThread::HandleRSEA()
{
CONTRACTL
{
NOTHROW;
if (g_pEEInterface->GetThread() != NULL) { GC_TRIGGERS; } else { GC_NOTRIGGER; }
PRECONDITION(ThisIsHelperThreadWorker());
}
CONTRACTL_END;
LOG((LF_CORDB,LL_INFO10000, "RSEA from out of process (right side)\n"));
DebuggerIPCEvent * e;
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
// Make room for any Right Side event on the stack.
BYTE buffer[CorDBIPC_BUFFER_SIZE];
e = (DebuggerIPCEvent *) buffer;
// If the RSEA is signaled, then handle the event from the Right Side.
memcpy(e, GetIPCEventReceiveBuffer(), CorDBIPC_BUFFER_SIZE);
#else
// Be sure to fetch the event into the official receive buffer since some event handlers assume it's there
// regardless of the the event buffer pointer passed to them.
e = GetIPCEventReceiveBuffer();
g_pDbgTransport->GetNextEvent(e, CorDBIPC_BUFFER_SIZE);
#endif // !FEATURE_DBGIPC_TRANSPOPRT
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
// If no reply is required, then let the Right Side go since we've got a copy of the event now.
_ASSERTE(!e->asyncSend || !e->replyRequired);
if (!e->replyRequired && !e->asyncSend)
{
LOG((LF_CORDB, LL_INFO1000, "DRCT::ML: no reply required, letting Right Side go.\n"));
BOOL succ = SetEvent(m_pDCB->m_rightSideEventRead);
if (!succ)
CORDBDebuggerSetUnrecoverableWin32Error(m_debugger, 0, true);
}
#ifdef LOGGING
else if (e->asyncSend)
LOG((LF_CORDB, LL_INFO1000, "DRCT::ML: async send.\n"));
else
LOG((LF_CORDB, LL_INFO1000, "DRCT::ML: reply required, holding Right Side...\n"));
#endif
#endif // !FEATURE_DBGIPC_TRANSPORT_VM
// Pass the event to the debugger for handling. Returns true if the event was a Continue event and we can
// stop looking for stragglers. We wrap this whole thing in an exception handler to help us debug faults.
bool wasContinue = false;
wasContinue = HandleIPCEventWrapper(m_debugger, e);
return wasContinue;
}
//---------------------------------------------------------------------------------------
//
// Main loop of the Runtime Controller thread. It waits for IPC events
// and dishes them out to the Debugger object for processing.
//
// Some of this logic is copied in Debugger::VrpcToVls
//
//---------------------------------------------------------------------------------------
void DebuggerRCThread::MainLoop()
{
// This function can only be called on native Debugger helper thread.
//
CONTRACTL
{
NOTHROW;
PRECONDITION(m_thread != NULL);
PRECONDITION(ThisIsHelperThreadWorker());
PRECONDITION(IsDbgHelperSpecialThread()); // Can only be called on native debugger helper thread
PRECONDITION((!ThreadStore::HoldingThreadStore()) || g_fProcessDetach);
}
CONTRACTL_END;
LOG((LF_CORDB, LL_INFO1000, "DRCT::ML:: running main loop\n"));
// Anybody doing helper duty is in a can't-stop range, period.
// Our helper thread is already in a can't-stop range, so this is particularly useful for
// threads doing helper duty.
CantStopHolder cantStopHolder;
HANDLE rghWaitSet[DRCT_COUNT_FINAL];
#ifdef _DEBUG
DWORD dwSyncSpinCount = 0;
#endif
// We start out just listening on RSEA and the thread control event...
unsigned int cWaitCount = DRCT_COUNT_INITIAL;
DWORD dwWaitTimeout = INFINITE;
rghWaitSet[DRCT_CONTROL_EVENT] = m_threadControlEvent;
rghWaitSet[DRCT_FAVORAVAIL] = GetFavorAvailableEvent();
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
rghWaitSet[DRCT_RSEA] = m_pDCB->m_rightSideEventAvailable;
#else
rghWaitSet[DRCT_RSEA] = g_pDbgTransport->GetIPCEventReadyEvent();
#endif // !FEATURE_DBGIPC_TRANSPORT_VM
CONTRACT_VIOLATION(ThrowsViolation);// HndCreateHandle throws, and this loop is not backstopped by any EH
// Lock holder. Don't take it yet. We take lock on this when we succeeded suspended runtime.
// We will release the lock later when continue happens and runtime resumes
Debugger::DebuggerLockHolder debugLockHolderSuspended(m_debugger, false);
while (m_run)
{
LOG((LF_CORDB, LL_INFO1000, "DRCT::ML: waiting for event.\n"));
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
// If there is a debugger attached, wait on its handle, too...
if ((cWaitCount == DRCT_COUNT_INITIAL) &&
m_pDCB->m_rightSideProcessHandle.ImportToLocalProcess() != NULL)
{
_ASSERTE((cWaitCount + 1) == DRCT_COUNT_FINAL);
rghWaitSet[DRCT_DEBUGGER_EVENT] = m_pDCB->m_rightSideProcessHandle;
cWaitCount = DRCT_COUNT_FINAL;
}
#endif // !FEATURE_DBGIPC_TRANSPORT_VM
if (m_fDetachRightSide)
{
m_fDetachRightSide = false;
#if !defined(FEATURE_DBGIPC_TRANSPORT_VM)
_ASSERTE(cWaitCount == DRCT_COUNT_FINAL);
_ASSERTE((cWaitCount - 1) == DRCT_COUNT_INITIAL);
rghWaitSet[DRCT_DEBUGGER_EVENT] = NULL;
cWaitCount = DRCT_COUNT_INITIAL;
#endif // !FEATURE_DBGIPC_TRANSPORT_VM
}
// Wait for an event from the Right Side.
DWORD dwWaitResult = WaitForMultipleObjectsEx(cWaitCount, rghWaitSet, FALSE, dwWaitTimeout, FALSE);
if (!m_run)
{
continue;
}
if (dwWaitResult == WAIT_OBJECT_0 + DRCT_DEBUGGER_EVENT)
{
// If the handle of the right side process is signaled, then we've lost our controlling debugger. We
// terminate this process immediatley in such a case.
LOG((LF_CORDB, LL_INFO1000, "DRCT::ML: terminating this process. Right Side has exited.\n"));
SUPPRESS_ALLOCATION_ASSERTS_IN_THIS_SCOPE;
EEPOLICY_HANDLE_FATAL_ERROR(0);
_ASSERTE(!"Should never reach this point.");
}
else if (dwWaitResult == WAIT_OBJECT_0 + DRCT_FAVORAVAIL)
{
// execute the callback set by DoFavor()
FAVORCALLBACK fpCallback = GetFavorFnPtr();
// We never expect the callback to be null unless some other component
// wrongly signals our event (see DD 463807).
// In case we messed up, we will not set the FavorReadEvent and will hang favor requesting thread.
if (fpCallback)
{
(*fpCallback)(GetFavorData());
SetEvent(GetFavorReadEvent());
}