-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathXDbgController.cpp
1359 lines (1120 loc) · 33.9 KB
/
XDbgController.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
#include <Windows.h>
#include <Psapi.h>
#include <assert.h>
#include "XDbgController.h"
#include "common.h"
#include "Utils.h"
#include "detours.h"
#include <vector>
extern UINT debug_if;
extern UINT api_hook_mask;
extern UINT inject_method;
extern UINT32 ignore_dbgstr;
extern UINT simu_attach_bp;
std::vector<AutoDebug* > autoDebugHandlers;
//////////////////////////////////////////////////////////////////////////
XDbgController::XDbgController(void)
{
_pid = 0;
_hPipe = INVALID_HANDLE_VALUE;
_hApiPipe = INVALID_HANDLE_VALUE;
_pending = false;
_hProcess = NULL;
_ContextFlags = 0;
_hInst = 0;
resetDbgEvent();
}
XDbgController::~XDbgController(void)
{
disconnectInferior();
}
bool XDbgController::initialize(HMODULE hInst, bool hookApi)
{
_hInst = hInst;
if (hookApi)
return hookDbgApi();
return true;
}
HANDLE XDbgController::connectPipe(const std::string& name)
{
HANDLE hPipe = INVALID_HANDLE_VALUE;
for (int i = 0; i < 10; i ++) {
hPipe = CreateFile(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
0 /*FILE_FLAG_OVERLAPPED*/, NULL);
if (hPipe == INVALID_HANDLE_VALUE) {
if (GetLastError() != ERROR_PIPE_BUSY) {
// log error
Sleep(100);
continue;
}
if (!WaitNamedPipe(name.c_str(), NMPWAIT_USE_DEFAULT_WAIT)) {
MyTrace("%s() cannot wait to to '%s'(event pipe)", __FUNCTION__, name.c_str());
return INVALID_HANDLE_VALUE;
}
} else
break;
}
return hPipe;
}
bool XDbgController::connectInferior(DWORD pid)
{
std::string name = makePipeName(pid);
_hPipe = connectPipe(name);
if (_hPipe == INVALID_HANDLE_VALUE) {
assert(false);
return false;
}
if (!connectRemoteApi(pid)) {
disconnectInferior();
assert(false);
return false;
}
MyTrace("%s(): _hPipe = %x, _hApiPipe = %x", __FUNCTION__, _hPipe, _hApiPipe);
return true;
}
bool XDbgController::connectRemoteApi(DWORD pid)
{
std::string apiName = makeApiPipeName(pid);
_hApiPipe = connectPipe(apiName);
MyTrace("%s(): hApiPipe = %x", __FUNCTION__, _hApiPipe);
_pid = pid;
return true;
}
void XDbgController::disconnectRemoteApi()
{
if (_hApiPipe != INVALID_HANDLE_VALUE) {
CloseHandle(_hApiPipe);
_hApiPipe = INVALID_HANDLE_VALUE;
}
_pid = 0;
}
void XDbgController::disconnectInferior()
{
if (_hPipe != INVALID_HANDLE_VALUE) {
CloseHandle(_hPipe);
_hPipe = INVALID_HANDLE_VALUE;
}
disconnectRemoteApi();
}
BOOL XDbgController::sendApiCall(const ApiCallPacket& outPkt)
{
DWORD len;
if (!WriteFile(_hApiPipe, &outPkt, sizeof(outPkt), &len, NULL)) {
return FALSE;
}
return TRUE;
}
BOOL XDbgController::recvApiReturn(ApiReturnPakcet& inPkt)
{
DWORD len;
if (!ReadFile(_hApiPipe, &inPkt, sizeof(inPkt), &len, NULL)) {
// assert(false);
return FALSE;
}
return TRUE;
}
BOOL XDbgController::sendApiCall(const ApiCallPacket& outPkt, ApiReturnPakcet& inPkt)
{
MutexGuard guard(&_apiMutex);
if (!sendApiCall(outPkt)) {
return false;
}
return recvApiReturn(inPkt);
}
BOOL XDbgController::injectDll(DWORD pid, HMODULE hInst)
{
if (inject_method == 0)
return injectDllByRemoteThread(pid, hInst);
else if (inject_method == 1)
return injectDllByWinHook(pid, hInst);
else {
assert(false);
return FALSE;
}
}
bool XDbgController::attach(DWORD pid, BOOL createProcess, DWORD tid)
{
MyTrace("%s()", __FUNCTION__);
if (_pid)
stop(_pid);
if (!connectInferior(pid)) {
assert(false);
return false;
}
_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (_hProcess == NULL ) {
disconnectInferior();
MyTrace("%s() OpenProcess(%u)", __FUNCTION__, pid);
return false;
}
_pid = pid;
DEBUG_EVENT event;
if (!waitEvent(&event)) { // SEND FIRST MSG TO VERIFY CONNECTION
MyTrace("%s(): connection is unavailable");
disconnectInferior();
CloseHandle(_hProcess);
_hProcess = NULL;
assert(false);
return false;
}
assert(event.dwDebugEventCode == ATTACHED_EVENT);
DbgAttachArgs args;
args.ignore_dbgstr = ignore_dbgstr;
args.inject_method = inject_method;
args.createProcess = createProcess;
args.simu_attach_bp = simu_attach_bp;
continueAttachEvent(event.dwProcessId, tid ? tid : event.dwThreadId, DBG_CONTINUE, args);
return true;
}
extern UINT exec_mode;
bool XDbgController::stop(DWORD pid)
{
assert(_pid == pid);
if (getEventCode() != 0) {
continueEvent(pid, getEventThreadId(), DBG_CONTINUE);
}
if (_hProcess) {
CloseHandle(_hProcess);
_hProcess = NULL;
}
if (_hPipe != INVALID_HANDLE_VALUE) {
CloseHandle(_hPipe);
_hPipe = INVALID_HANDLE_VALUE;
}
if (_hApiPipe != INVALID_HANDLE_VALUE) {
CloseHandle(_hApiPipe);
_hApiPipe = INVALID_HANDLE_VALUE;
}
resetDbgEvent();
_pid = 0;
return true;
}
extern BOOL(__stdcall * Real_ReadProcessMemory)(HANDLE a0,
LPCVOID a1,
LPVOID a2,
DWORD_PTR a3,
PDWORD_PTR a4);
bool XDbgController::waitEvent(LPDEBUG_EVENT lpDebugEvent, DWORD dwMilliseconds)
{
MyTrace("%s()", __FUNCTION__);
DWORD len;
if (!_pending) {
// memset(&_overlap, 0, sizeof(_overlap));
if (ReadFile(_hPipe, &_event, sizeof(_event), &len, NULL /* &_overlap */))
_pending = false;
else
if (GetLastError() == ERROR_IO_PENDING)
_pending = true;
else {
MyTrace("%s(): read pipe failed, pipe: %p", __FUNCTION__, _hPipe);
_pending = false;
return false;
}
}
if (_pending) {
DWORD waitResult = WaitForSingleObject(_hPipe, dwMilliseconds);
if (waitResult == WAIT_FAILED) {
_pending = false;
return false;
} else if (waitResult == WAIT_TIMEOUT) {
SetLastError(ERROR_SEM_TIMEOUT);
return false;
} else if (waitResult == WAIT_OBJECT_0) {
_pending = false;
} else {
_pending = false;
return false;
}
}
*lpDebugEvent = _event.event;
MyTrace("%s(): tid: %d, lastPc: %p, event_code: %x", __FUNCTION__, lpDebugEvent->dwThreadId,
CTX_PC_REG(&_event.ctx), lpDebugEvent->dwDebugEventCode);
switch (lpDebugEvent->dwDebugEventCode) {
case CREATE_PROCESS_DEBUG_EVENT:
{
char fileName[MAX_PATH + 1];
/* GetModuleFileNameEx(_hProcess, (HMODULE)lpDebugEvent->u.CreateProcessInfo.lpBaseOfImage,
fileName, MAX_PATH); */
SIZE_T len;
ReadProcessMemory(_hProcess, lpDebugEvent->u.CreateProcessInfo.lpImageName, fileName,
sizeof(fileName) - 1, &len);
DuplicateHandle(GetCurrentProcess(), _hProcess, GetCurrentProcess(),
&lpDebugEvent->u.CreateProcessInfo.hProcess, 0, FALSE, DUPLICATE_SAME_ACCESS);
lpDebugEvent->u.CreateProcessInfo.hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
lpDebugEvent->dwThreadId);
MyTrace("%s(): threadId: %d, threadHandle: %x", __FUNCTION__, lpDebugEvent->dwThreadId,
lpDebugEvent->u.CreateProcessInfo.hThread);
assert(lpDebugEvent->u.CreateProcessInfo.hThread);
lpDebugEvent->u.CreateProcessInfo.hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL);
assert(lpDebugEvent->u.CreateProcessInfo.hFile != INVALID_HANDLE_VALUE);
MyTrace("%s(): CREATE_PROCESS_DEBUG_EVENT: hFile = %x, hProcess = %x, hThread = %x, fileName = %s",
__FUNCTION__, lpDebugEvent->u.CreateProcessInfo.hFile,
lpDebugEvent->u.CreateProcessInfo.hProcess, lpDebugEvent->u.CreateProcessInfo.hThread,
fileName);
}
break;
case CREATE_THREAD_DEBUG_EVENT:
{
lpDebugEvent->u.CreateThread.hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, lpDebugEvent->dwThreadId);
MyTrace("%s(): CREATE_THREAD_DEBUG_EVENT. hThread: %x, tid: %u", __FUNCTION__,
lpDebugEvent->u.CreateThread.hThread, lpDebugEvent->dwThreadId);
}
break;
case EXIT_THREAD_DEBUG_EVENT:
{
// delThread(lpDebugEvent->dwThreadId);
}
break;
case LOAD_DLL_DEBUG_EVENT:
{
SIZE_T len;
if (lpDebugEvent->u.LoadDll.fUnicode){
wchar_t buf[MAX_PATH];
if (!GetModuleFileNameExW(_hProcess, (HMODULE)lpDebugEvent->u.LoadDll.lpBaseOfDll, buf, sizeof(buf) - 1)) {
assert(false);
break;
}
lpDebugEvent->u.LoadDll.hFile = CreateFileW((LPCWSTR)buf, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
MyTrace("%s(): LOAD_DLL_DEBUG_EVENT. dll: %S, hFile: %x", __FUNCTION__,
buf, lpDebugEvent->u.LoadDll.hFile);
}
else {
char buf[MAX_PATH];
if (!ReadProcessMemory(_hProcess, lpDebugEvent->u.LoadDll.lpImageName, buf, sizeof(buf), &len)) {
assert(false);
break;
}
lpDebugEvent->u.LoadDll.hFile = CreateFileA((LPCSTR)buf, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
MyTrace("%s(): LOAD_DLL_DEBUG_EVENT. dll: %s, hFile: %x", __FUNCTION__,
buf, lpDebugEvent->u.LoadDll.hFile);
}
assert(lpDebugEvent->u.LoadDll.hFile != INVALID_HANDLE_VALUE);
}
break;
case EXCEPTION_DEBUG_EVENT:
{
MyTrace("%s(): exception code: %p, addr: %x", __FUNCTION__,
lpDebugEvent->u.Exception.ExceptionRecord.ExceptionCode,
lpDebugEvent->u.Exception.ExceptionRecord.ExceptionAddress);
if (lpDebugEvent->u.Exception.ExceptionRecord.ExceptionCode == STATUS_SINGLE_STEP) {
MyTrace("STATUS_SINGLE_STEP");
}
}
break;
default:
break;
}
MyTrace("DEBUG_EVENT: %u", lpDebugEvent->dwDebugEventCode);
return true;
}
bool XDbgController::continueEvent(DWORD dwProcessId, DWORD dwThreadId, DWORD dwContinueStatus)
{
MyTrace("%s(): CONTINUE_EVENT: %x", __FUNCTION__, dwContinueStatus);
DebugAckPacket ack;
ack.dwProcessId = dwProcessId;
ack.dwThreadId = dwThreadId;
ack.dwContinueStatus = dwContinueStatus;
ack.ctx = _event.ctx;
ack.ContextFlags = _ContextFlags;
DWORD len;
if (!WriteFile(_hPipe, &ack, sizeof(ack), &len, NULL)) {
return false;
}
resetDbgEvent();
return true;
}
bool XDbgController::continueAttachEvent(DWORD dwProcessId, DWORD dwThreadId,
DWORD dwContinueStatus, const DbgAttachArgs& args)
{
MyTrace("%s(): CONTINUE_EVENT: %x", __FUNCTION__, dwContinueStatus);
DebugAckPacket ack;
ack.dwProcessId = dwProcessId;
ack.dwThreadId = dwThreadId;
ack.dwContinueStatus = dwContinueStatus;
ack.args = args;
DWORD len;
if (!WriteFile(_hPipe, &ack, sizeof(ack), &len, NULL)) {
return false;
}
resetDbgEvent();
return true;
}
//////////////////////////////////////////////////////////////////////////
BOOL(__stdcall * Real_CreateProcessA)(LPCSTR a0,
LPSTR a1,
LPSECURITY_ATTRIBUTES a2,
LPSECURITY_ATTRIBUTES a3,
BOOL a4,
DWORD a5,
LPVOID a6,
LPCSTR a7,
LPSTARTUPINFOA a8,
LPPROCESS_INFORMATION a9)
= CreateProcessA;
BOOL(__stdcall * Real_CreateProcessW)(LPCWSTR a0,
LPWSTR a1,
LPSECURITY_ATTRIBUTES a2,
LPSECURITY_ATTRIBUTES a3,
BOOL a4,
DWORD a5,
LPVOID a6,
LPCWSTR a7,
LPSTARTUPINFOW a8,
LPPROCESS_INFORMATION a9)
= CreateProcessW;
BOOL(__stdcall * Real_DebugActiveProcess)(DWORD a0)
= DebugActiveProcess;
BOOL(__stdcall * Real_DebugActiveProcessStop)(DWORD a0)
= DebugActiveProcessStop;
BOOL(__stdcall * Real_WaitForDebugEvent)(LPDEBUG_EVENT a0,
DWORD a1)
= WaitForDebugEvent;
BOOL(__stdcall * Real_ContinueDebugEvent)(DWORD a0,
DWORD a1,
DWORD a2)
= ContinueDebugEvent;
BOOL(__stdcall * Real_GetThreadContext)(HANDLE a0,
LPCONTEXT a1)
= GetThreadContext;
BOOL(__stdcall * Real_SetThreadContext)(HANDLE a0,
CONST CONTEXT* a1)
= SetThreadContext;
LPVOID(__stdcall * Real_VirtualAllocEx)(HANDLE a0,
LPVOID a1,
SIZE_T a2,
DWORD a3,
DWORD a4)
= VirtualAllocEx;
BOOL(__stdcall * Real_VirtualFreeEx)(HANDLE a0,
LPVOID a1,
SIZE_T a2,
DWORD a3)
= VirtualFreeEx;
BOOL(__stdcall * Real_VirtualProtectEx)(HANDLE a0,
LPVOID a1,
SIZE_T a2,
DWORD a3,
PDWORD a4)
= VirtualProtectEx;
DWORD_PTR(__stdcall * Real_VirtualQueryEx)(HANDLE a0,
LPCVOID a1,
PMEMORY_BASIC_INFORMATION a2,
DWORD_PTR a3)
= VirtualQueryEx;
BOOL(__stdcall * Real_ReadProcessMemory)(HANDLE a0,
LPCVOID a1,
LPVOID a2,
DWORD_PTR a3,
PDWORD_PTR a4)
= ReadProcessMemory;
BOOL(__stdcall * Real_WriteProcessMemory)(HANDLE a0,
LPVOID a1,
LPCVOID a2,
DWORD_PTR a3,
PDWORD_PTR a4)
= WriteProcessMemory;
DWORD(WINAPI * Real_GetModuleFileNameExW)(HANDLE hProcess,
HMODULE hModule,
LPWSTR lpFilename,
DWORD nSize)
= GetModuleFileNameExW;
/* NTSTATUS(NTAPI * Real_NtQueryInformationProcess)(
HANDLE ProcessHandle,
ULONG_PTR ProcessInformationClass,
PVOID ProcessInformation,
ULONG ProcessInformationLength,
PULONG ReturnLength)
= (NTSTATUS(NTAPI * )(HANDLE, ULONG_PTR, PVOID, ULONG, PULONG))
GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQueryInformationProcess"); */
/* BOOL(__stdcall * Real_DuplicateHandle)(HANDLE a0,
HANDLE a1,
HANDLE a2,
LPHANDLE a3,
DWORD a4,
BOOL a5,
DWORD a6)
= DuplicateHandle; */
/* HANDLE(__stdcall * Real_OpenProcess)(DWORD a0,
BOOL a1,
DWORD a2)
= OpenProcess; */
DWORD(__stdcall * Real_SuspendThread)(HANDLE a0)
= SuspendThread;
DWORD(__stdcall * Real_ResumeThread)(HANDLE a0)
= ResumeThread;
BOOL (WINAPI* Real_DebugBreakProcess)(HANDLE hProcess)
= DebugBreakProcess;
HANDLE(__stdcall * Real_CreateRemoteThread)(HANDLE a0,
LPSECURITY_ATTRIBUTES a1,
ULONG_PTR a2,
LPTHREAD_START_ROUTINE a3,
LPVOID a4,
DWORD a5,
LPDWORD a6)
= CreateRemoteThread;
//////////////////////////////////////////////////////////////////////////
BOOL __stdcall Mine_CreateProcessA(LPCSTR a0,
LPSTR a1,
LPSECURITY_ATTRIBUTES a2,
LPSECURITY_ATTRIBUTES a3,
BOOL a4,
DWORD dwCreationFlags,
LPVOID a6,
LPCSTR a7,
LPSTARTUPINFOA a8,
LPPROCESS_INFORMATION a9)
{
MyTrace("%s()", __FUNCTION__);
if (debug_if == 1)
return Real_CreateProcessA(a0, a1, a2, a3, a4, dwCreationFlags, a6, a7, a8, a9);
XDbgController& dbgctl = XDbgController::instance();
DWORD flags = dwCreationFlags;
if (DEBUG_PROCESS & dwCreationFlags) {
dwCreationFlags &= ~DEBUG_PROCESS;
}
if (DEBUG_ONLY_THIS_PROCESS & dwCreationFlags)
dwCreationFlags &= ~DEBUG_ONLY_THIS_PROCESS;
dwCreationFlags |= CREATE_SUSPENDED;
if (!Real_CreateProcessA(a0, a1, a2, a3, a4, dwCreationFlags, a6, a7, a8, a9)){
return FALSE;
}
if (dbgctl.injectDll(a9->dwProcessId, dbgctl.getModuleHandle())) {
int i;
for (i = 30; i > 0; i--) {
if (dbgctl.attach(a9->dwProcessId, TRUE, a9->dwThreadId))
break;
Sleep(100);
}
if (i == 0)
return FALSE;
}
if ((flags & CREATE_SUSPENDED) == 0) {
ResumeThread(a9->hThread);
}
return TRUE;
}
BOOL __stdcall Mine_CreateProcessW(LPCWSTR a0,
LPWSTR a1,
LPSECURITY_ATTRIBUTES a2,
LPSECURITY_ATTRIBUTES a3,
BOOL a4,
DWORD dwCreationFlags,
LPVOID a6,
LPCWSTR a7,
LPSTARTUPINFOW a8,
LPPROCESS_INFORMATION a9)
{
MyTrace("%s()", __FUNCTION__);
if (debug_if == 1)
return Real_CreateProcessW(a0, a1, a2, a3, a4, dwCreationFlags, a6, a7, a8, a9);
DWORD flags = dwCreationFlags;
XDbgController& dbgctl = XDbgController::instance();
if (DEBUG_PROCESS & dwCreationFlags) {
dwCreationFlags &= ~DEBUG_PROCESS;
}
if (DEBUG_ONLY_THIS_PROCESS & dwCreationFlags)
dwCreationFlags &= ~DEBUG_ONLY_THIS_PROCESS;
dwCreationFlags |= CREATE_SUSPENDED;
if (!Real_CreateProcessW(a0, a1, a2, a3, a4, dwCreationFlags, a6, a7, a8, a9)){
return FALSE;
}
if (dbgctl.injectDll(a9->dwProcessId, dbgctl.getModuleHandle())) {
int i;
for (i = 30; i > 0; i--) {
if (dbgctl.attach(a9->dwProcessId, TRUE, a9->dwThreadId))
break;
Sleep(100);
}
if (i == 0)
return FALSE;
}
if ((flags & CREATE_SUSPENDED) == 0) {
ResumeThread(a9->hThread);
}
return TRUE;
}
BOOL __stdcall Mine_DebugActiveProcess(DWORD a0)
{
MyTrace("%s()", __FUNCTION__);
if (debug_if == 1)
return Real_DebugActiveProcess(a0);
XDbgController& dbgctl = XDbgController::instance();
if (!dbgctl.injectDll(a0, dbgctl.getModuleHandle())) {
MyTrace("%s(): injectDll() failed.", __FUNCTION__);
}
int i;
for (i = 30; i > 0; i--) {
if (dbgctl.attach(a0, FALSE, GetProcessMainThread(a0)))
break;
Sleep(100);
}
if (i == 0)
return FALSE;
return TRUE;
}
BOOL __stdcall Mine_DebugActiveProcessStop(DWORD a0)
{
MyTrace("%s()", __FUNCTION__);
if (!XDbgController::instance().isDebugging())
return Real_DebugActiveProcessStop(a0);
XDbgController& dbgctl = XDbgController::instance();
return dbgctl.stop(a0);
}
//////////////////////////////////////////////////////////////////////////
#ifdef _DEBUG
static DWORD eventSerial = 0;
void dumpDebugEvent(LPDEBUG_EVENT lpDebugEvent)
{
switch (lpDebugEvent->dwDebugEventCode) {
case CREATE_PROCESS_DEBUG_EVENT:
MyTrace("DUMP[%d]: CREATE_PROCESS_DEBUG_EVENT [%d][start at %p]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.CreateProcessInfo.lpStartAddress);
break;
case EXIT_PROCESS_DEBUG_EVENT:
MyTrace("DUMP[%d]: EXIT_PROCESS_DEBUG_EVENT [%d][exit code %d]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.ExitProcess.dwExitCode);
break;
case CREATE_THREAD_DEBUG_EVENT:
MyTrace("DUMP[%d]: CREATE_THREAD_DEBUG_EVENT [%d][start at %p]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.CreateThread.lpStartAddress);
break;
case EXIT_THREAD_DEBUG_EVENT:
MyTrace("DUMP[%d]: EXIT_THREAD_DEBUG_EVENT [%d][exit code %d]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.ExitThread.dwExitCode);
break;
case LOAD_DLL_DEBUG_EVENT:
MyTrace("DUMP[%d]: LOAD_DLL_DEBUG_EVENT [%d][base %p]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.LoadDll.lpBaseOfDll);
break;
case UNLOAD_DLL_DEBUG_EVENT:
MyTrace("DUMP[%d]: UNLOAD_DLL_DEBUG_EVENT [%d][base %p]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.UnloadDll.lpBaseOfDll);
break;
case EXCEPTION_DEBUG_EVENT:
MyTrace("DUMP[%d]: EXCEPTION_DEBUG_EVENT [%d][code %x, address %p, firstChance: %d]",
lpDebugEvent->dwThreadId, ++eventSerial,
lpDebugEvent->u.Exception.ExceptionRecord.ExceptionCode,
lpDebugEvent->u.Exception.ExceptionRecord.ExceptionAddress,
lpDebugEvent->u.Exception.dwFirstChance);
break;
case OUTPUT_DEBUG_STRING_EVENT:
MyTrace("DUMP[%d]: OUTPUT_DEBUG_STRING_EVENT [%d][base %p]", lpDebugEvent->dwThreadId,
++eventSerial, lpDebugEvent->u.DebugString.lpDebugStringData);
break;
case RIP_EVENT:
MyTrace("DUMP[%d]: RIP_EVENT [%d][err %x]", lpDebugEvent->dwThreadId, ++eventSerial,
lpDebugEvent->u.RipInfo.dwError);
break;
default:
MyTrace("DUMP[%d]: UNKNOWN EVENT [%d][eventId %x]", lpDebugEvent->dwThreadId, ++eventSerial,
lpDebugEvent->dwDebugEventCode);
break;
}
}
#endif
//////////////////////////////////////////////////////////////////////////
BOOL __stdcall Mine_ContinueDebugEvent(DWORD a0,
DWORD a1,
DWORD a2);
BOOL __stdcall Mine_ReadProcessMemory(HANDLE a0,
LPCVOID a1,
LPVOID a2,
DWORD_PTR a3,
PDWORD_PTR a4);
BOOL __stdcall Mine_WriteProcessMemory(HANDLE a0,
LPVOID a1,
LPVOID a2,
DWORD_PTR a3,
PDWORD_PTR a4);
DWORD_PTR __stdcall Mine_VirtualQueryEx(HANDLE a0,
LPCVOID a1,
PMEMORY_BASIC_INFORMATION a2,
DWORD_PTR a3);
BOOL __stdcall Mine_VirtualProtectEx(HANDLE a0,
LPVOID a1,
SIZE_T a2,
DWORD a3,
PDWORD a4);
DWORD WINAPI Mine_GetModuleFileNameExW(HANDLE hProcess,
HMODULE hModule,
LPWSTR lpFilename,
DWORD nSize);
BOOL WINAPI Mine_DebugBreakProcess(HANDLE hProcess);
HANDLE __stdcall Mine_CreateRemoteThread(HANDLE a0,
LPSECURITY_ATTRIBUTES a1,
ULONG_PTR a2,
LPTHREAD_START_ROUTINE a3,
LPVOID a4,
DWORD a5,
LPDWORD a6);
BOOL __stdcall Mine_WaitForDebugEvent(LPDEBUG_EVENT a0,
DWORD a1)
{
MyTrace("%s(%p, %u)", __FUNCTION__, a0, a1);
if (!XDbgController::instance().isDebugging())
return Real_WaitForDebugEvent(a0, a1);
BOOL result;
bool ignore;
do {
ignore = false;
result = XDbgController::instance().waitEvent(a0, a1) ? TRUE : FALSE;
if (result) {
#ifdef _DEBUG
dumpDebugEvent(a0);
#endif
std::vector<AutoDebug* >::iterator it;
for (it = autoDebugHandlers.begin(); it != autoDebugHandlers.end(); it++) {
DWORD continueStatus;
if (!(*it)->peekDebugEvent(a0, &continueStatus)) {
XDbgController::instance().continueEvent(a0->dwProcessId, a0->dwThreadId, continueStatus);
ignore = true;
}
}
} else
break;
} while (ignore);
return result;
}
BOOL __stdcall Mine_ContinueDebugEvent(DWORD a0,
DWORD a1,
DWORD a2)
{
MyTrace("%s(%u, %u, %x)", __FUNCTION__, a0, a1, a2);
if (!XDbgController::instance().isDebugging())
return Real_ContinueDebugEvent(a0, a1, a2);
return XDbgController::instance().continueEvent(a0, a1, a2) ? TRUE : FALSE;
}
BOOL __stdcall Mine_SetThreadContext(HANDLE a0,
CONTEXT* a1)
{
MyTrace("%s(%p, %p)", __FUNCTION__, a0, a1);
if (!XDbgController::instance().isDebugging())
return Real_SetThreadContext(a0, a1);
XDbgController& dbgctl = XDbgController::instance();
return dbgctl.setThreadContext(a0, a1) ? TRUE: FALSE;
}
BOOL __stdcall Mine_GetThreadContext(HANDLE a0,
LPCONTEXT a1)
{
// MyTrace("%s(%p, %p)", __FUNCTION__, a0, a1);
if (debug_if == 1)
return Real_GetThreadContext(a0, a1);
XDbgController& dbgctl = XDbgController::instance();
if (!dbgctl.getThreadContext(a0, a1))
return FALSE;
#if 0
if ((dbgctl.getContextFlags() & CONTEXT_CONTROL) != CONTEXT_CONTROL) {
if (dbgctl.getExceptCode() == STATUS_BREAKPOINT) {
// CTX_PC_REG(a1) = (DWORD)dbgctl.getExceptAddress() + 1;
CTX_PC_REG(a1) = CTX_PC_REG(a1) + 1;
} /* else {
// CTX_PC_REG(a1) = (DWORD)dbgctl.getExceptAddress();
} */
}
#endif
return TRUE;
}
DWORD __stdcall Mine_SuspendThread(HANDLE a0);
DWORD __stdcall Mine_ResumeThread(HANDLE a0);
bool XDbgController::hookDbgApi()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)Real_CreateProcessA, &(PVOID&)Mine_CreateProcessA);
DetourAttach(&(PVOID&)Real_CreateProcessW, &(PVOID&)Mine_CreateProcessW);
DetourAttach(&(PVOID&)Real_DebugActiveProcess, &(PVOID&)Mine_DebugActiveProcess);
DetourAttach(&(PVOID&)Real_DebugActiveProcessStop, &(PVOID&)Mine_DebugActiveProcessStop);
DetourAttach(&(PVOID&)Real_WaitForDebugEvent, &(PVOID&)Mine_WaitForDebugEvent);
DetourAttach(&(PVOID&)Real_ContinueDebugEvent, &(PVOID&)Mine_ContinueDebugEvent);
DetourAttach(&(PVOID&)Real_GetThreadContext, &(PVOID&)Mine_GetThreadContext);
DetourAttach(&(PVOID&)Real_SetThreadContext, &(PVOID&)Mine_SetThreadContext);
DetourAttach(&(PVOID&)Real_DebugBreakProcess, &(PVOID&)Mine_DebugBreakProcess);
//////////////////////////////////////////////////////////////////////////
// optional hooking api
if (api_hook_mask & ID_ReadProcessMemory) {
DetourAttach(&(PVOID&)Real_ReadProcessMemory, &(PVOID&)Mine_ReadProcessMemory);
}
if (api_hook_mask & ID_WriteProcessMemory) {
DetourAttach(&(PVOID&)Real_WriteProcessMemory, &(PVOID&)Mine_WriteProcessMemory);
}
if (api_hook_mask & ID_SuspendThread) {
DetourAttach(&(PVOID&)Real_SuspendThread, &(PVOID&)Mine_SuspendThread);
}
if (api_hook_mask & ID_ResumeThread) {
DetourAttach(&(PVOID&)Real_ResumeThread, &(PVOID&)Mine_ResumeThread);
}
if (api_hook_mask & ID_VirtualQueryEx) {
DetourAttach(&(PVOID&)Real_VirtualQueryEx, &(PVOID&)Mine_VirtualQueryEx);
}
if (api_hook_mask & ID_VirtualProtectEx) {
DetourAttach(&(PVOID&)Real_VirtualProtectEx, &(PVOID&)Mine_VirtualProtectEx);
}
if (api_hook_mask & ID_GetModuleFileNameExW) {
DetourAttach(&(PVOID&)Real_GetModuleFileNameExW, &(PVOID&)Mine_GetModuleFileNameExW);
}
if (api_hook_mask & ID_CreateRemoteThread) {
DetourAttach(&(PVOID&)Real_CreateRemoteThread, &(PVOID&)Mine_CreateRemoteThread);
}
return DetourTransactionCommit() == NO_ERROR;
}
bool XDbgController::setThreadContext(HANDLE hThread, const CONTEXT* ctx)
{
DWORD currentThreadId = getEventThreadId();
DWORD threadId = GetThreadIdFromHandle(hThread);
if (threadId == 0) {
// assert(false);
return Real_SetThreadContext(hThread, ctx) == TRUE;
}
if (currentThreadId) {
if (threadId == currentThreadId && getEventCode() == EXCEPTION_DEBUG_EVENT) {
_ContextFlags |= ctx->ContextFlags;
cloneThreadContext(&_event.ctx, ctx, ctx->ContextFlags);
return true;
}
}
// THIS IS A BUG IN X64DBG, FIX IT AT HERE.
if (getEventCode() == 0 && (ctx->ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL) {
if (ctx->EFlags & SINGLE_STEP_FLAG)
*(PDWORD)&ctx->EFlags &= ~SINGLE_STEP_FLAG;
}
return _setThreadContext(threadId, hThread, ctx);
}
bool XDbgController::getThreadContext(HANDLE hThread, CONTEXT* ctx)
{
DWORD currentThreadId = getEventThreadId();
DWORD threadId = GetThreadIdFromHandle(hThread);
if (threadId == 0) {
// assert(false);
return Real_GetThreadContext(hThread, ctx) == TRUE;
}
if (currentThreadId) {
if (threadId == currentThreadId && getEventCode() == EXCEPTION_DEBUG_EVENT) {
cloneThreadContext(ctx, &_event.ctx, ctx->ContextFlags);
if ((getContextFlags() & CONTEXT_CONTROL) != CONTEXT_CONTROL) {
if (getExceptCode() == STATUS_BREAKPOINT) {
CTX_PC_REG(ctx) = CTX_PC_REG(ctx) + 1;
}
}
return true;
}
}
return _getThreadContext(threadId, hThread, ctx);
}
bool XDbgController::_setThreadContext(DWORD threadId, HANDLE hThread, const CONTEXT* ctx)
{
if (isRemoteApi() && (api_hook_mask & ID_SetThreadContext)) {
ApiCallPacket outPkt;
ApiReturnPakcet inPkt;
outPkt.apiId = ID_SetThreadContext;
outPkt.SetThreadContext.threadId = threadId;