-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
dbgtransportsession.cpp
2750 lines (2309 loc) · 111 KB
/
dbgtransportsession.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "dbgtransportsession.h"
#if (!defined(RIGHT_SIDE_COMPILE) && defined(FEATURE_DBGIPC_TRANSPORT_VM)) || (defined(RIGHT_SIDE_COMPILE) && defined(FEATURE_DBGIPC_TRANSPORT_DI))
// This is the entry type for the IPC event queue owned by the transport.
// Each entry contains the multiplexing type of the IPC event plus the
// IPC event itself.
struct DbgEventBufferEntry
{
public:
IPCEventType m_type;
BYTE m_event[CorDBIPC_BUFFER_SIZE]; // buffer for the IPC event
};
//
// Provides a robust and secure transport session between a debugger and a debuggee that are potentially on
// different machines.
//
// See DbgTransportSession.h for further detailed comments.
//
#ifndef RIGHT_SIDE_COMPILE
// The one and only transport instance for the left side. Allocated and initialized during EE startup (from
// Debugger::Startup() in debugger.cpp).
DbgTransportSession *g_pDbgTransport = NULL;
#include "ddmarshalutil.h"
#endif // !RIGHT_SIDE_COMPILE
DbgTransportSession::~DbgTransportSession()
{
DbgTransportLog(LC_Proxy, "DbgTransportSession::~DbgTransportSession() called");
// No other threads are now using session resources. We're free to deallocate them as we wish (if they
// were allocated in the first place).
if (m_hTransportThread)
CloseHandle(m_hTransportThread);
if (m_rghEventReadyEvent[IPCET_OldStyle])
CloseHandle(m_rghEventReadyEvent[IPCET_OldStyle]);
if (m_rghEventReadyEvent[IPCET_DebugEvent])
CloseHandle(m_rghEventReadyEvent[IPCET_DebugEvent]);
if (m_pEventBuffers)
delete [] m_pEventBuffers;
#ifdef RIGHT_SIDE_COMPILE
if (m_hSessionOpenEvent)
CloseHandle(m_hSessionOpenEvent);
if (m_hProcessExited)
CloseHandle(m_hProcessExited);
#endif // RIGHT_SIDE_COMPILE
if (m_fInitStateLock)
m_sStateLock.Destroy();
}
// Allocates initial resources (including starting the transport thread). The session will start in the
// SS_Opening state. That is, the RS will immediately start trying to Connect() a connection while the LS will
// perform an accept()/Accept() to wait for a connection request. The RS needs an IP address and port number
// to initiate connections. These should be given in host byte order. The LS, on the other hand, requires the
// addresses of a couple of runtime data structures to service certain debugger requests that may be delivered
// once the session is established.
#ifdef RIGHT_SIDE_COMPILE
HRESULT DbgTransportSession::Init(const ProcessDescriptor& pd, HANDLE hProcessExited)
#else // RIGHT_SIDE_COMPILE
HRESULT DbgTransportSession::Init(DebuggerIPCControlBlock *pDCB, AppDomainEnumerationIPCBlock *pADB)
#endif // RIGHT_SIDE_COMPILE
{
_ASSERTE(m_eState == SS_Closed);
// Start with a blank slate so that Shutdown() on a partially initialized instance will only do the
// cleanup necessary.
*this = {};
// Because of the above memset the embedded classes/structs need to be reinitialized especially
// the two way pipe; it expects the in/out handles to be -1 instead of 0.
m_ref = 1;
m_pipe = TwoWayPipe();
m_sStateLock = DbgTransportLock();
// Initialize all per-session state variables.
InitSessionState();
#ifdef RIGHT_SIDE_COMPILE
// The RS randomly allocates a session ID which is sent to the LS in the SessionRequest message. In the
// case of network errors during session formation this allows the LS to tell SessionRequest re-sends from
// a new request from a different RS.
HRESULT hr = CoCreateGuid(&m_sSessionID);
if (FAILED(hr))
return hr;
#endif // RIGHT_SIDE_COMPILE
#ifdef RIGHT_SIDE_COMPILE
m_pd = pd;
if (!DuplicateHandle(GetCurrentProcess(),
hProcessExited,
GetCurrentProcess(),
&m_hProcessExited,
0, // ignored since we are going to pass DUPLICATE_SAME_ACCESS
FALSE,
DUPLICATE_SAME_ACCESS))
{
return HRESULT_FROM_GetLastError();
}
m_fDebuggerAttached = false;
#else // RIGHT_SIDE_COMPILE
m_pDCB = pDCB;
m_pADB = pADB;
#endif // RIGHT_SIDE_COMPILE
m_sStateLock.Init();
m_fInitStateLock = true;
#ifdef RIGHT_SIDE_COMPILE
m_hSessionOpenEvent = WszCreateEvent(NULL, TRUE, FALSE, NULL); // Manual reset, not signalled
if (m_hSessionOpenEvent == NULL)
return E_OUTOFMEMORY;
#else // RIGHT_SIDE_COMPILE
ProcessDescriptor pd = ProcessDescriptor::FromCurrentProcess();
if (!m_pipe.CreateServer(pd)) {
return E_OUTOFMEMORY;
}
#endif // RIGHT_SIDE_COMPILE
// Allocate some buffers to receive incoming events. The initial number is chosen arbitrarily, tune as
// necessary. This array will need to grow if it fills with unread events (it takes our client a little
// time to process each incoming receive). In general, however, one side will not send an unbounded stream
// of events to the other without waiting for some kind of response. More usual are small bursts of events
// to represent variable sized data (such as a stack trace).
m_cEventBuffers = 10;
m_pEventBuffers = (DbgEventBufferEntry *)new (nothrow) BYTE[m_cEventBuffers * sizeof(DbgEventBufferEntry)];
if (m_pEventBuffers == NULL)
return E_OUTOFMEMORY;
m_rghEventReadyEvent[IPCET_OldStyle] = WszCreateEvent(NULL, FALSE, FALSE, NULL); // Auto reset, not signalled
if (m_rghEventReadyEvent[IPCET_OldStyle] == NULL)
return E_OUTOFMEMORY;
m_rghEventReadyEvent[IPCET_DebugEvent] = WszCreateEvent(NULL, FALSE, FALSE, NULL); // Auto reset, not signalled
if (m_rghEventReadyEvent[IPCET_DebugEvent] == NULL)
return E_OUTOFMEMORY;
// Start the transport thread which handles forming and re-forming connections, driving the session
// state to SS_Open and receiving and initially processing all incoming traffic.
AddRef();
m_hTransportThread = CreateThread(NULL, 0, TransportWorkerStatic, this, 0, NULL);
if (m_hTransportThread == NULL)
{
Release();
return E_OUTOFMEMORY;
}
return S_OK;
}
// Drive the session to the SS_Closed state, which will deallocate all remaining transport resources
// (including terminating the transport thread). If this is the RS and the session state is SS_Open at the
// time of this call a graceful disconnect will be attempted (which tells the LS to go back to SS_Opening to
// look for a new RS rather than interpreting the disconnection as a temporary error and going into
// SS_Resync). On either side the session will no longer be functional after this call returns (though Init()
// may be called again to start over from the beginning).
void DbgTransportSession::Shutdown()
{
DbgTransportLog(LC_Proxy, "DbgTransportSession::Shutdown() called");
// The transport thread is allocated last in Init() (since it uses all the other resources that Init()
// prepares). Don't do any transport related stuff unless this was allocated (which can happen if
// Shutdown() is called after an Init() failure).
if (m_hTransportThread)
{
// From SS_Open state try a graceful disconnect.
if (m_eState == SS_Open)
{
DbgTransportLog(LC_Session, "Sending 'SessionClose'");
DBG_TRANSPORT_INC_STAT(SentSessionClose);
Message sMessage;
sMessage.Init(MT_SessionClose);
SendMessage(&sMessage, false);
}
// Must take the state lock to make a state transition.
{
TransportLockHolder sLockHolder(&m_sStateLock);
// Remember previous state and transition to SS_Closed.
SessionState ePreviousState = m_eState;
m_eState = SS_Closed;
if (ePreviousState != SS_Closed)
{
m_pipe.Disconnect();
}
} // Leave m_sStateLock
#ifdef RIGHT_SIDE_COMPILE
// Signal the m_hSessionOpenEvent now to quickly error out any callers of WaitForSessionToOpen().
SetEvent(m_hSessionOpenEvent);
#endif // RIGHT_SIDE_COMPILE
}
// The transport instance is no longer valid
Release();
}
#ifndef RIGHT_SIDE_COMPILE
// Cleans up the named pipe connection so no tmp files are left behind. Does only
// the minimum and must be safe to call at any time. Called during PAL ExitProcess,
// TerminateProcess and for unhandled native exceptions and asserts.
void DbgTransportSession::AbortConnection()
{
m_pipe.Disconnect();
}
// API used only by the LS to drive the transport into a state where it won't accept connections. This is used
// when no proxy is detected at startup but it's too late to shutdown all of the debugging system easily. It's
// mainly paranoia to increase the protection of your system when the proxy isn't started.
void DbgTransportSession::Neuter()
{
// Simply set the session state to SS_Closed. The transport thread will switch itself off if it ever gets
// a connection but the rest of the transport resources remain valid (so the debugger helper thread won't
// AV on a deallocated handle, which might happen if we simply called Shutdown()).
m_eState = SS_Closed;
}
#else // RIGHT_SIDE_COMPILE
// Used by debugger side (RS) to cleanup the target (LS) named pipes
// and semaphores when the debugger detects the debuggee process exited.
void DbgTransportSession::CleanupTargetProcess()
{
m_pipe.CleanupTargetProcess();
}
// On the RS it may be useful to wait and see if the session can reach the SS_Open state. If the target
// runtime has terminated for some reason then we'll never reach the open state. So the method below gives the
// RS a way to try and establish a connection for a reasonable amount of time and to time out otherwise. They
// could then call Shutdown on the session and report an error back to the rest of the debugger. The method
// returns true if the session opened within the time given (in milliseconds) and false otherwise.
bool DbgTransportSession::WaitForSessionToOpen(DWORD dwTimeout)
{
DWORD dwRet = WaitForSingleObject(m_hSessionOpenEvent, dwTimeout);
if (m_eState == SS_Closed)
return false;
if (dwRet == WAIT_TIMEOUT)
DbgTransportLog(LC_Proxy, "DbgTransportSession::WaitForSessionToOpen(%u) timed out", dwTimeout);
return dwRet == WAIT_OBJECT_0;
}
//---------------------------------------------------------------------------------------
//
// A valid ticket is returned if no other client is currently acting as the debugger.
// If the caller passes in a valid ticket, this function will return true without invalidating the ticket.
//
// Arguments:
// pTicket - out parameter; set to a valid ticket if the client has successfully registered as the debugger
//
// Return Value:
// Return true if the client has successfully registered as the debugger.
//
bool DbgTransportSession::UseAsDebugger(DebugTicket * pTicket)
{
TransportLockHolder sLockHolder(&m_sStateLock);
if (m_fDebuggerAttached)
{
if (pTicket->IsValid())
{
// The client already holds a valid ticket.
return true;
}
else
{
// Another client of this session has already indicated that it's using this session to debug.
_ASSERTE(!pTicket->IsValid());
return false;
}
}
else
{
m_fDebuggerAttached = true;
pTicket->SetValid();
return true;
}
}
//---------------------------------------------------------------------------------------
//
// A valid ticket is required in order for this function to succeed. After this function succeeds,
// another client can request to be the debugger.
//
// Arguments:
// pTicket - the client's ticket; must be valid for this function to succeed
//
// Return Value:
// Return true if the client has successfully unregistered as the debugger.
// Return false if no client is currently acting as the debugger or if the client's ticket is invalid.
//
bool DbgTransportSession::StopUsingAsDebugger(DebugTicket * pTicket)
{
TransportLockHolder sLockHolder(&m_sStateLock);
if (m_fDebuggerAttached && pTicket->IsValid())
{
// The caller is indeed the owner of the debug ticket.
m_fDebuggerAttached = false;
pTicket->SetInvalid();
return true;
}
else
{
return false;
}
}
#endif // RIGHT_SIDE_COMPILE
// Sends a pre-initialized event to the other side.
HRESULT DbgTransportSession::SendEvent(DebuggerIPCEvent *pEvent)
{
DbgTransportLog(LC_Events, "Sending '%s'", IPCENames::GetName(pEvent->type));
DBG_TRANSPORT_INC_STAT(SentEvent);
return SendEventWorker(pEvent, IPCET_OldStyle);
}
// Sends a pre-initialized event to the other side, but pretend that this is coming from the native pipeline.
// See code:IPCEventType for more information.
HRESULT DbgTransportSession::SendDebugEvent(DebuggerIPCEvent * pEvent)
{
DbgTransportLog(LC_Events, "Sending '%s' as DEBUG_EVENT", IPCENames::GetName(pEvent->type));
DBG_TRANSPORT_INC_STAT(SentEvent);
return SendEventWorker(pEvent, IPCET_DebugEvent);
}
// Retrieves the auto-reset handle which is signalled by the session each time a new event is received from
// the other side.
HANDLE DbgTransportSession::GetIPCEventReadyEvent()
{
return m_rghEventReadyEvent[IPCET_OldStyle];
}
// Retrieves the auto-reset handle which is signalled by the session each time a new event (disguised as a
// debug event) is received from the other side.
HANDLE DbgTransportSession::GetDebugEventReadyEvent()
{
return m_rghEventReadyEvent[IPCET_DebugEvent];
}
// Copies the last event received from the other side into the provided buffer. This should only be called
// (once) after the event returned from GetIPCEEventReadyEvent()/GetDebugEventReadyEvent() has been signalled.
void DbgTransportSession::GetNextEvent(DebuggerIPCEvent *pEvent, DWORD cbEvent)
{
_ASSERTE(cbEvent <= CorDBIPC_BUFFER_SIZE);
// Must acquire the state lock to synchronize us wrt to the transport thread (clients already guarantee
// they serialize calls to this and waiting on m_rghEventReadyEvent).
TransportLockHolder sLockHolder(&m_sStateLock);
// There must be at least one valid event waiting (this call does not block).
_ASSERTE(m_cValidEventBuffers);
// Copy the first valid event into the client's buffer.
memcpy(pEvent, &m_pEventBuffers[m_idxEventBufferHead].m_event, cbEvent);
// Move the index of the head of the valid list forward (which may in fact move it back to the start of
// the array since the list is circular). This reduces the number of valid entries by one. Note that these
// two adjustments do not affect the tail of the list in any way. In the limit case the head will end up
// pointing to the same event as the tail (and m_cValidEventBuffers will be zero).
m_idxEventBufferHead = (m_idxEventBufferHead + 1) % m_cEventBuffers;
m_cValidEventBuffers--;
_ASSERTE(((m_idxEventBufferHead + m_cValidEventBuffers) % m_cEventBuffers) == m_idxEventBufferTail);
// If there's at least one more valid event we can signal event ready now.
if (m_cValidEventBuffers)
{
SetEvent(m_rghEventReadyEvent[m_pEventBuffers[m_idxEventBufferHead].m_type]);
}
}
void MarshalDCBTransportToDCB(DebuggerIPCControlBlockTransport* pIn, DebuggerIPCControlBlock* pOut)
{
pOut->m_DCBSize = pIn->m_DCBSize;
pOut->m_verMajor = pIn->m_verMajor;
pOut->m_verMinor = pIn->m_verMinor;
pOut->m_checkedBuild = pIn->m_checkedBuild;
pOut->m_bHostingInFiber = pIn->m_bHostingInFiber;
pOut->padding2 = pIn->padding2;
pOut->padding3 = pIn->padding3;
pOut->m_leftSideProtocolCurrent = pIn->m_leftSideProtocolCurrent;
pOut->m_leftSideProtocolMinSupported = pIn->m_leftSideProtocolMinSupported;
pOut->m_rightSideProtocolCurrent = pIn->m_rightSideProtocolCurrent;
pOut->m_rightSideProtocolMinSupported = pIn->m_rightSideProtocolMinSupported;
pOut->m_errorHR = pIn->m_errorHR;
pOut->m_errorCode = pIn->m_errorCode;
#if defined(TARGET_64BIT)
pOut->padding4 = pIn->padding4;
#endif // TARGET_64BIT
//
//pOut->m_rightSideEventAvailable
//pOut->m_rightSideEventRead
//pOut->m_paddingObsoleteLSEA
//pOut->m_paddingObsoleteLSER
//pOut->m_rightSideProcessHandle
//pOut->m_leftSideUnmanagedWaitEvent
pOut->m_realHelperThreadId = pIn->m_realHelperThreadId;
pOut->m_helperThreadId = pIn->m_helperThreadId;
pOut->m_temporaryHelperThreadId = pIn->m_temporaryHelperThreadId;
pOut->m_CanaryThreadId = pIn->m_CanaryThreadId;
pOut->m_pRuntimeOffsets = pIn->m_pRuntimeOffsets;
pOut->m_helperThreadStartAddr = pIn->m_helperThreadStartAddr;
pOut->m_helperRemoteStartAddr = pIn->m_helperRemoteStartAddr;
pOut->m_specialThreadList = pIn->m_specialThreadList;
//
//pOut->m_receiveBuffer
//pOut->m_sendBuffer
pOut->m_specialThreadListLength = pIn->m_specialThreadListLength;
pOut->m_shutdownBegun = pIn->m_shutdownBegun;
pOut->m_rightSideIsWin32Debugger = pIn->m_rightSideIsWin32Debugger;
pOut->m_specialThreadListDirty = pIn->m_specialThreadListDirty;
pOut->m_rightSideShouldCreateHelperThread = pIn->m_rightSideShouldCreateHelperThread;
}
void MarshalDCBToDCBTransport(DebuggerIPCControlBlock* pIn, DebuggerIPCControlBlockTransport* pOut)
{
pOut->m_DCBSize = pIn->m_DCBSize;
pOut->m_verMajor = pIn->m_verMajor;
pOut->m_verMinor = pIn->m_verMinor;
pOut->m_checkedBuild = pIn->m_checkedBuild;
pOut->m_bHostingInFiber = pIn->m_bHostingInFiber;
pOut->padding2 = pIn->padding2;
pOut->padding3 = pIn->padding3;
pOut->m_leftSideProtocolCurrent = pIn->m_leftSideProtocolCurrent;
pOut->m_leftSideProtocolMinSupported = pIn->m_leftSideProtocolMinSupported;
pOut->m_rightSideProtocolCurrent = pIn->m_rightSideProtocolCurrent;
pOut->m_rightSideProtocolMinSupported = pIn->m_rightSideProtocolMinSupported;
pOut->m_errorHR = pIn->m_errorHR;
pOut->m_errorCode = pIn->m_errorCode;
#if defined(TARGET_64BIT)
pOut->padding4 = pIn->padding4;
#endif // TARGET_64BIT
pOut->m_realHelperThreadId = pIn->m_realHelperThreadId;
pOut->m_helperThreadId = pIn->m_helperThreadId;
pOut->m_temporaryHelperThreadId = pIn->m_temporaryHelperThreadId;
pOut->m_CanaryThreadId = pIn->m_CanaryThreadId;
pOut->m_pRuntimeOffsets = pIn->m_pRuntimeOffsets;
pOut->m_helperThreadStartAddr = pIn->m_helperThreadStartAddr;
pOut->m_helperRemoteStartAddr = pIn->m_helperRemoteStartAddr;
pOut->m_specialThreadList = pIn->m_specialThreadList;
pOut->m_specialThreadListLength = pIn->m_specialThreadListLength;
pOut->m_shutdownBegun = pIn->m_shutdownBegun;
pOut->m_rightSideIsWin32Debugger = pIn->m_rightSideIsWin32Debugger;
pOut->m_specialThreadListDirty = pIn->m_specialThreadListDirty;
pOut->m_rightSideShouldCreateHelperThread = pIn->m_rightSideShouldCreateHelperThread;
}
#ifdef RIGHT_SIDE_COMPILE
// Read and write memory on the LS from the RS.
HRESULT DbgTransportSession::ReadMemory(PBYTE pbRemoteAddress, PBYTE pbBuffer, SIZE_T cbBuffer)
{
DbgTransportLog(LC_Requests, "Sending 'ReadMemory(0x%08X, %u)'", pbRemoteAddress, cbBuffer);
DBG_TRANSPORT_INC_STAT(SentReadMemory);
Message sMessage;
sMessage.Init(MT_ReadMemory, NULL, 0, pbBuffer, (DWORD)cbBuffer);
sMessage.m_sHeader.TypeSpecificData.MemoryAccess.m_pbLeftSideBuffer = pbRemoteAddress;
sMessage.m_sHeader.TypeSpecificData.MemoryAccess.m_cbLeftSideBuffer = (DWORD)cbBuffer;
HRESULT hr = SendRequestMessageAndWait(&sMessage);
if (FAILED(hr))
return hr;
// If we reached here the send was successful but the actual memory operation may not have been (due to
// unmapped memory or page protections etc.). So the final result comes back to us in the reply.
return sMessage.m_sHeader.TypeSpecificData.MemoryAccess.m_hrResult;
}
HRESULT DbgTransportSession::WriteMemory(PBYTE pbRemoteAddress, PBYTE pbBuffer, SIZE_T cbBuffer)
{
DbgTransportLog(LC_Requests, "Sending 'WriteMemory(0x%08X, %u)'", pbRemoteAddress, cbBuffer);
DBG_TRANSPORT_INC_STAT(SentWriteMemory);
Message sMessage;
sMessage.Init(MT_WriteMemory, pbBuffer, (DWORD)cbBuffer);
sMessage.m_sHeader.TypeSpecificData.MemoryAccess.m_pbLeftSideBuffer = pbRemoteAddress;
sMessage.m_sHeader.TypeSpecificData.MemoryAccess.m_cbLeftSideBuffer = (DWORD)cbBuffer;
HRESULT hr = SendRequestMessageAndWait(&sMessage);
if (FAILED(hr))
return hr;
// If we reached here the send was successful but the actual memory operation may not have been (due to
// unmapped memory or page protections etc.). So the final result comes back to us in the reply.
return sMessage.m_sHeader.TypeSpecificData.MemoryAccess.m_hrResult;
}
HRESULT DbgTransportSession::VirtualUnwind(DWORD threadId, ULONG32 contextSize, PBYTE context)
{
DbgTransportLog(LC_Requests, "Sending 'VirtualUnwind'");
DBG_TRANSPORT_INC_STAT(SentVirtualUnwind);
Message sMessage;
sMessage.Init(MT_VirtualUnwind, context, contextSize, context, contextSize);
return SendRequestMessageAndWait(&sMessage);
}
// Read and write the debugger control block on the LS from the RS.
HRESULT DbgTransportSession::GetDCB(DebuggerIPCControlBlock *pDCB)
{
DbgTransportLog(LC_Requests, "Sending 'GetDCB'");
DBG_TRANSPORT_INC_STAT(SentGetDCB);
Message sMessage;
DebuggerIPCControlBlockTransport dcbt;
sMessage.Init(MT_GetDCB, NULL, 0, (PBYTE)&dcbt, sizeof(DebuggerIPCControlBlockTransport));
HRESULT ret = SendRequestMessageAndWait(&sMessage);
MarshalDCBTransportToDCB(&dcbt, pDCB);
return ret;
}
HRESULT DbgTransportSession::SetDCB(DebuggerIPCControlBlock *pDCB)
{
DbgTransportLog(LC_Requests, "Sending 'SetDCB'");
DBG_TRANSPORT_INC_STAT(SentSetDCB);
DebuggerIPCControlBlockTransport dcbt;
MarshalDCBToDCBTransport(pDCB, &dcbt);
Message sMessage;
sMessage.Init(MT_SetDCB, (PBYTE)&dcbt, sizeof(DebuggerIPCControlBlockTransport));
return SendRequestMessageAndWait(&sMessage);
}
// Read the AppDomain control block on the LS from the RS.
HRESULT DbgTransportSession::GetAppDomainCB(AppDomainEnumerationIPCBlock *pADB)
{
DbgTransportLog(LC_Requests, "Sending 'GetAppDomainCB'");
DBG_TRANSPORT_INC_STAT(SentGetAppDomainCB);
Message sMessage;
sMessage.Init(MT_GetAppDomainCB, NULL, 0, (PBYTE)pADB, sizeof(AppDomainEnumerationIPCBlock));
return SendRequestMessageAndWait(&sMessage);
}
#endif // RIGHT_SIDE_COMPILE
// Worker function for code:DbgTransportSession::SendEvent and code:DbgTransportSession::SendDebugEvent.
HRESULT DbgTransportSession::SendEventWorker(DebuggerIPCEvent * pEvent, IPCEventType type)
{
DWORD cbEvent = GetEventSize(pEvent);
_ASSERTE(cbEvent <= CorDBIPC_BUFFER_SIZE);
Message sMessage;
sMessage.Init(MT_Event, (PBYTE)pEvent, cbEvent);
// Store the event type in the header as well, it's sometimes useful for debugging.
sMessage.m_sHeader.TypeSpecificData.Event.m_eIPCEventType = type;
sMessage.m_sHeader.TypeSpecificData.Event.m_eType = pEvent->type;
return SendMessage(&sMessage, false);
}
// Sends a pre-formatted message (including the data block, if any). The fWaitsForReply indicates whether the
// caller is going to block until some sort of reply message is received (for instance an event that must be
// ack'd or a request such as MT_GetDCB that needs a reply). SendMessage() uses this to determine whether it
// needs to buffer the message before placing it on the send queue (since it may need to resend the message
// after a transitory network failure).
HRESULT DbgTransportSession::SendMessage(Message *pMessage, bool fWaitsForReply)
{
// Serialize the whole operation under the state lock. In particular we need to make allocating the
// message ID atomic wrt placing the message on the connection (to ensure our IDs are seen in order by the
// other side). We also need to hold the lock while manipulating the send queue (to prevent corruption)
// and while determining whether to send immediately or not depending on the session state (to avoid
// posting a send on a closed and possibly recycled socket).
{
TransportLockHolder sLockHolder(&m_sStateLock);
// Perform any last updates to the header or data block here since we might be about to encrypt them.
// Give this message a unique ID (useful both to track which messages need to be resent on a network
// failure and to match replies to the original message).
pMessage->m_sHeader.m_dwId = m_dwNextMessageId++;
// Use this message send to piggyback an acknowledgement of the last message we processed from the
// other side (this will allow the other side to discard one or more buffered messages from its send
// queue).
pMessage->m_sHeader.m_dwLastSeenId = m_dwLastMessageIdSeen;
// Check the session state.
if (m_eState == SS_Closed)
{
// SS_Closed is bad news, we'll never recover from that so error the send immediately.
return E_ABORT;
}
// If the caller isn't waiting around for a reply we must make a copy of the message to place on the
// send queue.
pMessage->m_pOrigMessage = pMessage;
Message *pMessageCopy = NULL;
PBYTE pDataBlockCopy = NULL;
if (!fWaitsForReply)
{
// Allocate a new message (includes an embedded message header).
pMessageCopy = new (nothrow) Message();
if (pMessageCopy == NULL)
return E_OUTOFMEMORY;
// Allocate a new data block if one is being used.
if (pMessage->m_pbDataBlock)
{
pDataBlockCopy = new (nothrow) BYTE[pMessage->m_cbDataBlock];
if (pDataBlockCopy == NULL)
{
delete pMessageCopy;
return E_OUTOFMEMORY;
}
}
// Copy the message descriptor over.
memcpy(pMessageCopy, pMessage, sizeof(Message));
// And the data block if applicable.
if (pDataBlockCopy)
memcpy(pDataBlockCopy, pMessage->m_pbDataBlock, pMessage->m_cbDataBlock);
// The message copy still points to the wrong data block (if there is one).
pMessageCopy->m_pbDataBlock = pDataBlockCopy;
// Point the copy back to the original message.
pMessageCopy->m_pOrigMessage = pMessage;
// From now on we'll use the copy.
pMessage = pMessageCopy;
}
// If the state is SS_Open we can send the message now.
if (m_eState == SS_Open)
{
// Send the message header block followed by the data block if it's provided. Any network error will
// be reported internally by SendBlock and result in a transition to the SS_Resync_NC state (and an
// eventual resend of the data).
if (SendBlock((PBYTE)&pMessage->m_sHeader, sizeof(MessageHeader)) && pMessage->m_pbDataBlock)
SendBlock(pMessage->m_pbDataBlock, pMessage->m_cbDataBlock);
}
// Don't queue session management messages. We always recreate these if we need to re-send them.
if (pMessage->m_sHeader.m_eType > MT_SessionClose)
{
// Regardless of session state we always queue the message for at least as long as it takes us to
// be sure the other side has received the message.
if (m_pSendQueueLast == NULL)
{
// Queue is currently empty.
m_pSendQueueFirst = pMessage;
m_pSendQueueLast = pMessage;
pMessage->m_pNext = NULL;
}
else
{
// Place on end of queue.
m_pSendQueueLast->m_pNext = pMessage;
m_pSendQueueLast = pMessage;
pMessage->m_pNext = NULL;
}
}
else
{
if (pMessageCopy)
delete pMessageCopy;
if (pDataBlockCopy)
delete [] pDataBlockCopy;
}
// If the state wasn't open there's nothing more to be done. The state will eventually transition to
// either SS_Open (in which case the transport thread will send all pending messages for us at the
// transition point) or SS_Closed (where the transport thread will drain the queue and discard each
// message, setting m_fAborted if necessary).
} // Leave m_sStateLock
return S_OK;
}
// Helper method for sending messages requiring a reply (such as MT_GetDCB) and waiting on the result.
HRESULT DbgTransportSession::SendRequestMessageAndWait(Message *pMessage)
{
// Allocate event to wait for reply on.
pMessage->m_hReplyEvent = WszCreateEvent(NULL, FALSE, FALSE, NULL); // Auto-reset, not signalled
if (pMessage->m_hReplyEvent == NULL)
return E_OUTOFMEMORY;
// Duplicate the handle to the event. It's necessary to have two handles to the same event because
// both this thread and the message pumping thread may be trying to access the handle at the same
// time (e.g. closing the handle). So we make a duplicate handle. This thread is responsible for
// closing hReplyEvent (the local variable) whereas the message pumping thread is responsible for
// closing the handle on the message.
HANDLE hReplyEvent = NULL;
if (!DuplicateHandle(GetCurrentProcess(),
pMessage->m_hReplyEvent,
GetCurrentProcess(),
&hReplyEvent,
0, // ignored since we are going to pass DUPLICATE_SAME_ACCESS
FALSE,
DUPLICATE_SAME_ACCESS))
{
return HRESULT_FROM_GetLastError();
}
// Send the request.
HRESULT hr = SendMessage(pMessage, true);
if (FAILED(hr))
{
// In this case, we need to close both handles since the message is never put into the send queue.
// This thread is the only one who has access to the message.
CloseHandle(pMessage->m_hReplyEvent);
CloseHandle(hReplyEvent);
return hr;
}
// At this point, the message pumping thread may receive the reply any time. It may even receive the
// reply message even before we wait on the event. Keep this in mind.
// Wait for a reply (by the time this event is signalled the message header will have been overwritten by
// the reply and any output buffer provided will have been filled in).
#if defined(RIGHT_SIDE_COMPILE)
HANDLE rgEvents[] = { hReplyEvent, m_hProcessExited };
#else // !RIGHT_SIDE_COMPILE
HANDLE rgEvents[] = { hReplyEvent };
#endif // RIGHT_SIDE_COMPILE
DWORD dwResult = WaitForMultipleObjectsEx(sizeof(rgEvents)/sizeof(rgEvents[0]), rgEvents, FALSE, INFINITE, FALSE);
if (dwResult == WAIT_OBJECT_0)
{
// This is the normal case. The message pumping thread receives a reply from the debuggee process.
// It signals the event to wake up this thread.
CloseHandle(hReplyEvent);
// Check whether the session aborted us due to a Shutdown().
if (pMessage->m_fAborted)
return E_ABORT;
}
#if defined(RIGHT_SIDE_COMPILE)
else if (dwResult == (WAIT_OBJECT_0 + 1))
{
// This is the complicated case. This thread wakes up because the debuggee process is terminated.
// At the same time, the message pumping thread may be in the process of handling the reply message.
// We need to be careful here because there is a race condition.
// Remove the original message from the send queue. This is because in the case of a blocking message,
// the message can be allocated on the stack. Thus, the message becomes invalid when we return from
// this function. The message pumping thread may have beaten this thread to it. That's ok since
// RemoveMessageFromSendQueue() takes the state lock.
Message * pOriginalMessage = RemoveMessageFromSendQueue(pMessage->m_sHeader.m_dwId);
_ASSERTE((pOriginalMessage == NULL) || (pOriginalMessage == pMessage));
// If the message pumping thread has beaten this thread to removing the original message, then this
// thread must wait until the message pumping thread is done with the message before returning.
// Otherwise, the message may become invalid when the message pumping thread is accessing it.
// Fortunately, in this case, we know the message pumping thread is going to signal the event.
if (pOriginalMessage == NULL)
{
WaitForSingleObject(hReplyEvent, INFINITE);
}
CloseHandle(hReplyEvent);
return CORDBG_E_PROCESS_TERMINATED;
}
#endif // RIGHT_SIDE_COMPILE
else
{
// Should never get here.
CloseHandle(hReplyEvent);
UNREACHABLE();
}
return S_OK;
}
// Sends a single contiguous buffer of host memory over the connection. The caller is responsible for holding
// the state lock and ensuring the session state is SS_Open. Returns false if the send failed (the error will
// have already caused the recovery logic to kick in, so handling it is not required, the boolean is just
// returned so that any further blocks in the message are not sent).
bool DbgTransportSession::SendBlock(PBYTE pbBuffer, DWORD cbBuffer)
{
_ASSERTE(m_eState == SS_Opening || m_eState == SS_Resync || m_eState == SS_Open);
_ASSERTE(m_pipe.GetState() == TwoWayPipe::ServerConnected || m_pipe.GetState() == TwoWayPipe::ClientConnected);
_ASSERTE(cbBuffer > 0);
DBG_TRANSPORT_INC_STAT(SentBlocks);
DBG_TRANSPORT_ADD_STAT(SentBytes, cbBuffer);
//DbgTransportLog(LC_Proxy, "SendBlock(%08X, %u)", pbBuffer, cbBuffer);
bool fSuccess;
if (DBG_TRANSPORT_SHOULD_INJECT_FAULT(Send))
fSuccess = false;
else
fSuccess = ((DWORD)m_pipe.Write(pbBuffer, cbBuffer) == cbBuffer);
if (!fSuccess)
{
DbgTransportLog(LC_NetErrors, "Network error on Send()");
DBG_TRANSPORT_INC_STAT(SendErrors);
HandleNetworkError(true);
return false;
}
return true;
}
// Receives a single contiguous buffer of host memory over the connection. No state lock needs to be held
// (receives are serialized by the fact they're only performed on the transport thread). Returns false if a
// network error is encountered (which will automatically transition the session into the correct retry
// state).
bool DbgTransportSession::ReceiveBlock(PBYTE pbBuffer, DWORD cbBuffer)
{
_ASSERTE(m_pipe.GetState() == TwoWayPipe::ServerConnected || m_pipe.GetState() == TwoWayPipe::ClientConnected);
_ASSERTE(cbBuffer > 0);
DBG_TRANSPORT_INC_STAT(ReceivedBlocks);
DBG_TRANSPORT_ADD_STAT(ReceivedBytes, cbBuffer);
//DbgTransportLog(LC_Proxy, "ReceiveBlock(%08X, %u)", pbBuffer, cbBuffer);
bool fSuccess;
if (DBG_TRANSPORT_SHOULD_INJECT_FAULT(Receive))
fSuccess = false;
else
fSuccess = ((DWORD)m_pipe.Read(pbBuffer, cbBuffer) == cbBuffer);
if (!fSuccess)
{
DbgTransportLog(LC_NetErrors, "Network error on Receive()");
DBG_TRANSPORT_INC_STAT(ReceiveErrors);
HandleNetworkError(false);
return false;
}
return true;
}
// Called upon encountering a network error (e.g. an error from Send() or Receive()). This handles pushing the
// session state into SS_Resync_NC or SS_Opening_NC in order to start the recovery process.
void DbgTransportSession::HandleNetworkError(bool fCallerHoldsStateLock)
{
_ASSERTE(m_eState == SS_Open || m_eState == SS_Opening || m_eState == SS_Resync || !fCallerHoldsStateLock);
// Check the easy cases first which don't require us to take the lock (because we don't transition the
// state). These are the SS_Closed state (a network error doesn't matter when we're closing down the
// session anyway) and the SS_*_NC states (which indicate someone else beat us to it, closed the
// connection and has started recovery).
if (m_eState == SS_Closed ||
m_eState == SS_Opening_NC ||
m_eState == SS_Resync_NC)
return;
// We need the state lock to perform a state transition.
if (!fCallerHoldsStateLock)
m_sStateLock.Enter();
switch (m_eState)
{
case SS_Closed:
case SS_Opening_NC:
case SS_Resync_NC:
// Still need to cope with the no-op states handled above since we could have transitioned into them
// before we took the lock.
break;
case SS_Opening:
// All work to transition SS_Opening to SS_Open is performed by the transport thread, so we know we're
// on that thread. Consequently it's just enough to set the state to SS_Opening_NC and the thread will
// notice the change when the SendMessage() or ReceiveBlock() call completes.
m_eState = SS_Opening_NC;
break;
case SS_Resync:
// Likewise, all the work to transition SS_Resync to SS_Open is performed by the transport thread, so
// we know we're on that thread.
m_eState = SS_Resync_NC;
break;
case SS_Open:
// The state change to SS_Resync_NC will prompt the transport thread (which might be this thread) that
// it should discard the current connection and reform a new one. It will also cause sends to be
// queued instead of sent. In case we're not the transport thread and instead it is currently stuck in
// a Receive (I don't entirely trust the connection to immediately fail these on a network problem)
// we'll call CancelReceive() to abort the operation. The transport thread itself will handle the
// actual Destroy() (having one thread do this management greatly simplifies things).
m_eState = SS_Resync_NC;
m_pipe.Disconnect();
break;
default:
_ASSERTE(!"Unknown session state");
}
if (!fCallerHoldsStateLock)
m_sStateLock.Leave();
}
// Scan the send queue and discard any messages which have been processed by the other side according to the
// specified ID). Messages waiting on a reply message (e.g. MT_GetDCB) will be retained until that reply is
// processed. FlushSendQueue will take the state lock.
void DbgTransportSession::FlushSendQueue(DWORD dwLastProcessedId)
{
// Must access the send queue under the state lock.
TransportLockHolder sLockHolder(&m_sStateLock);
// Note that message headers (and data blocks) may be encrypted. Use the cached fields in the Message
// structure to compare message IDs and types.
Message *pMsg = m_pSendQueueFirst;
Message *pLastMsg = NULL;
while (pMsg)
{
if (pMsg->m_sHeader.m_dwId <= dwLastProcessedId)
{
// Message has been seen and processed by other side.
// Check if we can discard it (i.e. it's not waiting on a reply message that needs the original
// request to hang around).
#ifdef RIGHT_SIDE_COMPILE
MessageType eType = pMsg->m_sHeader.m_eType;
if (eType != MT_ReadMemory &&
eType != MT_WriteMemory &&
eType != MT_VirtualUnwind &&
eType != MT_GetDCB &&
eType != MT_SetDCB &&
eType != MT_GetAppDomainCB)
#endif // RIGHT_SIDE_COMPILE
{
#ifdef RIGHT_SIDE_COMPILE
_ASSERTE(eType == MT_Event);
#endif // RIGHT_SIDE_COMPILE
// We can discard this message.
// Unlink it from the queue.
if (pLastMsg == NULL)
m_pSendQueueFirst = pMsg->m_pNext;
else
pLastMsg->m_pNext = pMsg->m_pNext;
if (m_pSendQueueLast == pMsg)
m_pSendQueueLast = pLastMsg;
Message *pDiscardMsg = pMsg;
pMsg = pMsg->m_pNext;
// If the message is a copy deallocate it (and the data block associated with it).
if (pDiscardMsg->m_pOrigMessage != pDiscardMsg)
{
if (pDiscardMsg->m_pbDataBlock)
delete [] pDiscardMsg->m_pbDataBlock;
delete pDiscardMsg;
}
continue;
}
}
pLastMsg = pMsg;
pMsg = pMsg->m_pNext;
}
}