-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathGhostDbg.hpp
1947 lines (1902 loc) · 85.8 KB
/
GhostDbg.hpp
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
#pragma once
/*
Copyright (c) 2020 Victor Sheinmann, [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
struct NGhDbg
{
typedef NShMem SHM; // Shorter and helps in case of renaming
//====================================================================================
enum EDatType {dtNone,dtNull=0x01,dtBool=0x02,dtBYTE=0x04,dtWORD=0x08,dtDWORD=0x10,dtQWORD=0x20,dtSigned=0x40,dtReal=0x80};
enum EMsgType {mtNone,mtDbgReq=0x01,mtDbgRsp=0x02,mtUsrReq=0x04,mtUsrRsp=0x08,mtInfo=0x10};
enum EMsgId {
// System
miNone,
miHello,
miGoodby,
// Debugging
miQueryInformationProcess,
miQueryInformationThread,
miProtectVirtualMemory,
miFlushVirtualMemory,
miQueryVirtualMemory,
miDebugActiveProcess,
miDebugActiveProcessStop,
miContinueDebugEvent,
miWaitForDebugEvent,
miDebugBreakProcess,
miGetThreadContext,
miSetThreadContext,
miReadVirtualMemory,
miWriteVirtualMemory,
miTerminateThread,
miTerminateProcess,
miSuspendThread,
miResumeThread,
// User
miDbgSetConfigs,
miDbgGetConfigs,
miDbgDetachNtfy,
miUserBase // Base inex for inspecified custom messages
};
struct DbgEvtEx: public DEBUG_EVENT
{
UINT PathSize; // In chars
wchar_t FilePath[1];
};
//====================================================================================
class CThreadList // TODO: Decompose or reorganize
{
public:
struct SThDesc
{
enum ThFlags {tfNone=0,tfTraceFlg=0x01,tfDbgCont=0x02,tfOpenedHnd=0x04,tfMarkedForRemove=0x08,tfSuspendedForAll=0x10, tfTraceFlagMsk=0x0100};
volatile DWORD Flags;
volatile DWORD Index;
volatile DWORD ThreadID; // Not WORD
volatile HANDLE hThread;
volatile PVOID pContext; // Non NULL only if thread is in Exception Handler (Suspended)
volatile TEB* pThTeb;
struct SHwBp
{
PBYTE Addr;
DWORD Size;
} volatile HwBpLst[4];
struct SDbgCtx
{
SIZE_T Dr0;
SIZE_T Dr1;
SIZE_T Dr2;
SIZE_T Dr3;
SIZE_T Dr6;
SIZE_T Dr7;
bool TrFlg; // Unreliable, because this flag can be accessed with pushf/popf
} volatile DbgCtx;
//------------------------------------------------------------------------------------
inline void SyncResFlags(DWORD Flg){_InterlockedAnd((long*)&this->Flags,~Flg);}
inline void SyncSetFlags(DWORD Flg){_InterlockedOr((long*)&this->Flags,Flg);}
inline DWORD SyncGetFlags(DWORD Flg){return this->Flags & Flg;}
inline void SetTraceFlagState(bool State)
{
if(State)this->SyncSetFlags(tfTraceFlg);
else this->SyncResFlags(tfTraceFlg);
}
//------------------------------------------------------------------------------------
inline void SetDbgContinueState(bool State)
{
if(State)this->SyncSetFlags(tfDbgCont);
else this->SyncResFlags(tfDbgCont);
}
//------------------------------------------------------------------------------------
};
private:
SHM::CGrowArr<SThDesc, 128> ThreadLst;
SHM::CArgPack<sizeof(DbgEvtEx) * 32> EvtStk;
SHM::CCritSectEx<> csec;
int TotalInStack;
//------------------------------------------------------------------------------------
void RemoveThreadFromListByIdx(DWORD Index)
{
if((this->ThreadLst[Index].Flags & SThDesc::tfOpenedHnd) && this->ThreadLst[Index].hThread)NtClose(this->ThreadLst[Index].hThread);
// DBGMSG("Index=%u, ThreadID=%u",Index,this->ThreadLst[Index].ThreadID);
this->ThreadLst[Index].hThread = NULL;
this->ThreadLst[Index].ThreadID = 0;
}
//------------------------------------------------------------------------------------
SThDesc* GetThreadDesc(UINT Index)
{
if(!this->IsThreadIndexExist(Index))return NULL;
return &this->ThreadLst[Index];
}
//------------------------------------------------------------------------------------
public:
UINT DbgEventCnt;
//------------------------------------------------------------------------------------
CThreadList(void)
{
this->TotalInStack = 0;
this->DbgEventCnt = 0;
this->Clear();
}
//------------------------------------------------------------------------------------
~CThreadList()
{
this->Clear();
}
//------------------------------------------------------------------------------------
void Lock(void)
{
// DBGMSG("Locking...");
this->csec.Lock();
// DBGMSG("Locked");
}
//------------------------------------------------------------------------------------
void UnLock(void)
{
// DBGMSG("UnLocking...");
this->csec.Unlock();
// DBGMSG("Unlocked");
}
//------------------------------------------------------------------------------------
int EventsInStack(void){return this->TotalInStack;}
//------------------------------------------------------------------------------------
DbgEvtEx* PushDbgEvent(UINT ExtraSize=0) // Requires ThreadList lock
{
this->TotalInStack++;
return (DbgEvtEx*)this->EvtStk.PushBlkEx(sizeof(DbgEvtEx) + ExtraSize);
}
//------------------------------------------------------------------------------------
DbgEvtEx* PopDbgEvent(UINT* Size=NULL) // Requires ThreadList lock
{
if(this->TotalInStack <= 0){DBGMSG("No events in stack!"); return NULL;}
this->TotalInStack--;
return (DbgEvtEx*)this->EvtStk.PopBlkEx(Size);
}
//------------------------------------------------------------------------------------
DbgEvtEx* GetDbgEventAt(UINT& Offset)
{
return (DbgEvtEx*)this->EvtStk.GetBlkAt(Offset);
}
//------------------------------------------------------------------------------------
// Windows Server 2003 and Windows XP: The value of the THREAD_ALL_ACCESS flag increased on Windows Server 2008 and Windows Vista. If an application compiled for Windows Server 2008 and
// Windows Vista is run on Windows Server 2003 or Windows XP, the THREAD_ALL_ACCESS flag contains access bits that are not supported and the function specifying this flag fails with ERROR_ACCESS_DENIED.
//
int AddThreadToList(TEB* pThTeb, DWORD ThreadID=0, HANDLE hThread=NULL, LARGE_INTEGER* CreateTime=NULL, bool CanOpen=true)
{
int NewThIdx = -1;
if(!ThreadID && pThTeb)ThreadID = (DWORD)pThTeb->ClientId.UniqueThread;
for(UINT ctr=0,total=this->ThreadLst.Count();ctr < total;ctr++)
{
SThDesc* ThDes = &this->ThreadLst[ctr];
if(ThreadID && (ThDes->ThreadID == ThreadID))return ctr; // Already in list
if(hThread && (ThDes->hThread == hThread ))return ctr; // Already in list
if(!ThDes->hThread)NewThIdx = ctr;
}
SThDesc* ThDes;
if(NewThIdx < 0) // Adding a new slot
{
NewThIdx = this->ThreadLst.Count();
ThDes = this->ThreadLst.Add(NULL);
}
else ThDes = &this->ThreadLst[NewThIdx]; // Reusing an empty slot
// DBGMSG("Adding a new thread: %u",NewThIdx);
ThDes->ThreadID = ThreadID;
ThDes->Index = NewThIdx;
ThDes->pContext = NULL;
ThDes->pThTeb = pThTeb;
if(CanOpen && !hThread)
{
CLIENT_ID CliID;
OBJECT_ATTRIBUTES ObjAttr;
CliID.UniqueThread = (HANDLE)SIZE_T(ThreadID);
CliID.UniqueProcess = 0;
ObjAttr.Length = sizeof(ObjAttr);
ObjAttr.RootDirectory = NULL;
ObjAttr.Attributes = 0; // bInheritHandle ? 2 : 0;
ObjAttr.ObjectName = NULL;
ObjAttr.SecurityDescriptor = ObjAttr.SecurityQualityOfService = NULL;
if(NTSTATUS stat = NtOpenThread((HANDLE*)&ThDes->hThread, SYNCHRONIZE|THREAD_GET_CONTEXT|THREAD_SET_CONTEXT|THREAD_QUERY_INFORMATION|THREAD_SET_INFORMATION|THREAD_SUSPEND_RESUME|THREAD_TERMINATE, &ObjAttr, &CliID))
{
ThDes->hThread = NULL;
ThDes->ThreadID = 0;
DBGMSG("Failed to open thread %u at %u: %08X",ThreadID,NewThIdx,stat);
return -1;
}
ThDes->Flags = SThDesc::tfOpenedHnd;
if(ThreadID != NtCurrentThreadId())
{
if(NTSTATUS stat = NtSuspendThread(ThDes->hThread, NULL)){DBGMSG("Failed to suspend: %08X",stat);}
else ThDes->Flags |= SThDesc::tfSuspendedForAll;
}
if(CreateTime)
{
KERNEL_USER_TIMES times;
ULONG RetLen = 0;
if(NTSTATUS stat = NtQueryInformationThread(ThDes->hThread,ThreadTimes,×,sizeof(times),&RetLen)){DBGMSG("Failed to query thread times: %08X",stat);} // A debugger will request this many times anyway
CreateTime->QuadPart = times.CreateTime.QuadPart;
}
}
else
{
ThDes->Flags = SThDesc::tfNone;
ThDes->hThread = hThread;
}
DBGMSG("ThreadID=%08X(%u), hThread=%08X, CreateTime=%016llX, Index=%u",ThDes->ThreadID,ThDes->ThreadID,ThDes->hThread,(CreateTime?CreateTime->QuadPart:0),NewThIdx);
return NewThIdx;
}
//------------------------------------------------------------------------------------
static bool IsCurrentThreadDesc(SThDesc* Desc, TEB* CurrTeb)
{
if(Desc->pThTeb != CurrTeb)return false;
if(Desc->ThreadID != (UINT)CurrTeb->ClientId.UniqueThread){DBGMSG("Inconsistent Thread entry %u for %u(%u)!",Desc->Index,Desc->ThreadID,(UINT)CurrTeb->ClientId.UniqueThread); return false;} // Current TEB has been reused!
return true;
}
//------------------------------------------------------------------------------------
bool IsThreadInList(DWORD ThreadID, HANDLE hThread=NULL){return (this->FindThreadIdxInList(NULL, ThreadID, hThread) >= 0);}
bool IsThreadIndexExist(UINT Index){return ((Index < this->ThreadLst.Count()) && this->ThreadLst[Index].hThread);}
//------------------------------------------------------------------------------------
PTEB GetTebByIndex(UINT Index)
{
PTEB val = NULL;
if(Index < this->ThreadLst.Count())val = (PTEB)this->ThreadLst[Index].pThTeb; // NULL if the slot is empty
return val;
}
//------------------------------------------------------------------------------------
HANDLE GetHandleByIndex(UINT Index)
{
HANDLE val = NULL;
if(Index < this->ThreadLst.Count())val = this->ThreadLst[Index].hThread; // NULL if the slot is empty
return val;
}
//------------------------------------------------------------------------------------
HANDLE GetHandleByID(UINT ThreadID)
{
int Idx = this->FindThreadIdxInList(NULL, ThreadID, NULL);
if(Idx < 0)return NULL;
if(Idx < (int)this->ThreadLst.Count())return this->ThreadLst[Idx].hThread; // NULL if the slot is empty
return NULL;
}
//------------------------------------------------------------------------------------
int FindThreadIdxInList(SThDesc** Res, DWORD ThreadID, HANDLE hThread=NULL) // Returns a first thread in the list if both ThreadID and hThread are NULL
{
for(UINT ctr=0,total=this->ThreadLst.Count();ctr < total;ctr++)
{
if(!this->ThreadLst[ctr].hThread)continue; // The slot is empty
if(hThread && (this->ThreadLst[ctr].hThread != hThread))continue;
if(ThreadID && (this->ThreadLst[ctr].ThreadID != ThreadID))continue;
if(Res)*Res = &this->ThreadLst[ctr];
return ctr;
}
// DBGMSG("Thread %u:%08X not found!",ThreadID,hThread);
return -1;
}
//------------------------------------------------------------------------------------
bool RemoveThreadFromList(DWORD ThreadID, HANDLE hThread=NULL) // A process can create and delete some thread very frequently so no memory moving here, just invalidate removed entries
{
int Idx = this->FindThreadIdxInList(NULL, ThreadID, hThread);
if(Idx < 0)return false;
this->RemoveThreadFromListByIdx(Idx);
return true;
}
//------------------------------------------------------------------------------------
void Clear(void)
{
this->Lock();
for(UINT ctr=0,total=this->ThreadLst.Count();ctr < total;ctr++)
{
SThDesc* ThDes = &this->ThreadLst[ctr];
if((ThDes->Flags & SThDesc::tfOpenedHnd) && ThDes->hThread)NtClose(ThDes->hThread);
}
this->ThreadLst.Clear();
this->EvtStk.Clear();
this->UnLock();
}
//------------------------------------------------------------------------------------
NTSTATUS Suspend(UINT Idx, PULONG PrevCnt=NULL, bool MarkForRemove=false, bool SuspForAll=false) // TODO: Report_DEAD_THREAD_DEBUG_EVENT if HANDLE in STATUS_THREAD_IS_TERMINATING
{
if(!this->IsThreadIndexExist(Idx))return STATUS_NOT_FOUND;
NTSTATUS Status = STATUS_UNSUCCESSFUL;
if(MarkForRemove)this->ThreadLst[Idx].Flags |= SThDesc::tfMarkedForRemove; // Will be removed after next Resume
if(HANDLE hTh = this->ThreadLst[Idx].hThread)
{
DBGMSG("Idx=%u, ThID=%u",Idx,this->ThreadLst[Idx].ThreadID);
if(IsCurrentThreadDesc(&this->ThreadLst[Idx],NtCurrentTeb()))this->UnLock(); // Unlocks if locked to suspend self
if(SuspForAll)
{
if(this->ThreadLst[Idx].Flags & SThDesc::tfSuspendedForAll){DBGMSG("Already suspended for all - skipping!"); return STATUS_SUCCESS;}
this->ThreadLst[Idx].Flags |= SThDesc::tfSuspendedForAll; // Prevent the thread from suspending again by SuspendAllThreads until ResumeAllThreads is called
}
Status = NtSuspendThread(hTh, PrevCnt);
DBGMSG("Status=%08X",Status);
if(Status == STATUS_THREAD_IS_TERMINATING)this->ReportDeadThreadDbgEvt(Idx);
}
return Status;
}
//------------------------------------------------------------------------------------
NTSTATUS Resume(UINT Idx, PULONG PrevCnt=NULL, int DbgContinue=-1) // TODO: Report_DEAD_THREAD_DEBUG_EVENT if HANDLE in STATUS_THREAD_IS_TERMINATING
{
if(!this->IsThreadIndexExist(Idx))return STATUS_NOT_FOUND;
ULONG Prev = 0;
NTSTATUS Status = STATUS_UNSUCCESSFUL;
if(DbgContinue >= 0)this->ThreadLst[Idx].SetDbgContinueState(DbgContinue); // DbgCont = DbgContinue; // ???
if(this->ThreadLst[Idx].hThread)Status = NtResumeThread(this->ThreadLst[Idx].hThread, &Prev);
if((Status || (Prev <= 1)) && (this->ThreadLst[Idx].Flags & SThDesc::tfMarkedForRemove))this->RemoveThreadFromListByIdx(Idx);
if(Status == STATUS_THREAD_IS_TERMINATING)this->ReportDeadThreadDbgEvt(Idx);
if(PrevCnt)*PrevCnt = Prev;
return Status;
}
//------------------------------------------------------------------------------------
NTSTATUS SuspendAllThreads(DWORD SingleThreadID, int SingleThreadIdx=-1, bool MarkForRemove=false, bool SkipSpecified=false) // Suspends only registered threads so ClientThread is safe
{
ULONG PrevCnt = 0;
if(!SingleThreadID && (SingleThreadIdx >= 0))
{
SThDesc* ThDesc = GetThreadDesc(SingleThreadIdx);
if(ThDesc)SingleThreadID = ThDesc->ThreadID;
}
SThDesc* CurrThDesc = NULL;
TEB* CurrTeb = NtCurrentTeb();
for(UINT ctr=0,total=this->ThreadLst.Count();ctr < total;ctr++)
{
SThDesc* ThDesc = &this->ThreadLst[ctr];
if(!ThDesc->hThread)continue; // The slot is empty
if(SkipSpecified && SingleThreadID && (ThDesc->ThreadID == SingleThreadID)){DBGMSG("Skipping: ThID=%u",ThDesc->ThreadID); continue;}
if(MarkForRemove && SingleThreadID && (ThDesc->ThreadID == SingleThreadID))ThDesc->Flags |= SThDesc::tfMarkedForRemove; // Will be removed after next Resume
if(ThDesc->Flags & SThDesc::tfSuspendedForAll)continue; // Already suspended for all
if(IsCurrentThreadDesc(ThDesc,CurrTeb)){CurrThDesc = ThDesc; continue;} // Current thread is in the list - suspend it last
NTSTATUS Status = NtSuspendThread(ThDesc->hThread, &PrevCnt);
ThDesc->Flags |= SThDesc::tfSuspendedForAll;
DBGMSG("ThID=%u, Status=%08X, SuspLst=%i",ThDesc->ThreadID, Status, PrevCnt);
if(Status == STATUS_THREAD_IS_TERMINATING)this->ReportDeadThreadDbgEvt(ctr);
}
if(CurrThDesc)
{
HANDLE hThread = CurrThDesc->hThread;
DWORD ThID = CurrThDesc->ThreadID;
DBGMSG("This Thread: ThID=%u",CurrThDesc->ThreadID);
this->UnLock(); // Release BEFORE suspending!
if(hThread) // This thread
{
NTSTATUS Status = NtSuspendThread(hThread, &PrevCnt);
DBGMSG("CURR: ThID=%u, Status=%08X, SuspLst=%i",ThID, Status, PrevCnt);
if(Status == STATUS_THREAD_IS_TERMINATING)
{
int TIdx = this->FindThreadIdxInList(NULL,ThID);
if(TIdx >= 0)this->ReportDeadThreadDbgEvt(TIdx);
}
}
}
return STATUS_SUCCESS; // Always
}
//------------------------------------------------------------------------------------
NTSTATUS ResumeAllThreads(DWORD SingleThreadID, int SingleThreadIdx=-1, int DbgContinue=-1)
{
if(!SingleThreadID && (SingleThreadIdx >= 0))
{
SThDesc* ThDesc = GetThreadDesc(SingleThreadIdx);
if(ThDesc)SingleThreadID = ThDesc->ThreadID;
}
TEB* CurrTeb = NtCurrentTeb();
for(UINT ctr=0,total=this->ThreadLst.Count();ctr < total;ctr++)
{
SThDesc* ThDesc = &this->ThreadLst[ctr];
if(!ThDesc->hThread)continue; // The slot is empty
if((ThDesc->ThreadID == SingleThreadID) && (DbgContinue >= 0))ThDesc->SetDbgContinueState(DbgContinue); // DbgCont = DbgContinue; // ???
ULONG PrevCnt = 0;
NTSTATUS Status = STATUS_UNSUCCESSFUL;
if(!IsCurrentThreadDesc(ThDesc,CurrTeb)){Status = NtResumeThread(ThDesc->hThread, &PrevCnt); ThDesc->Flags &= ~SThDesc::tfSuspendedForAll; DBGMSG("ThID=%u, Status=%08X, SuspLst=%i",ThDesc->ThreadID, Status, PrevCnt);} // Current thread is already running but suspend count > 0?
if((Status || (PrevCnt <= 1)) && (ThDesc->Flags & SThDesc::tfMarkedForRemove))this->RemoveThreadFromListByIdx(ctr); // Remove ALL marked threads whey they are resumed // Or Status is something like "TheThreadIsTerminating"
else if(Status == STATUS_THREAD_IS_TERMINATING)this->ReportDeadThreadDbgEvt(ctr);
}
return STATUS_SUCCESS;
}
//------------------------------------------------------------------------------------
NTSTATUS SetContextVal(UINT Idx, PCONTEXT Ctx)
{
if(!this->IsThreadIndexExist(Idx))return STATUS_NOT_FOUND;
if(!this->ThreadLst[Idx].pContext)return NtSetContextThread(this->ThreadLst[Idx].hThread, Ctx); // Not in exception handler
PCONTEXT ThCtx = (PCONTEXT)this->ThreadLst[Idx].pContext; // Exception handler`s Context
ThCtx->ContextFlags |= Ctx->ContextFlags; // Merge groups
#ifdef _AMD64_
ThCtx->MxCsr = Ctx->MxCsr; // ?????????????
if(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS)
{
ThCtx->Dr0 = Ctx->Dr0;
ThCtx->Dr1 = Ctx->Dr1;
ThCtx->Dr2 = Ctx->Dr2;
ThCtx->Dr3 = Ctx->Dr3;
ThCtx->Dr6 = Ctx->Dr6;
ThCtx->Dr7 = Ctx->Dr7;
}
if(Ctx->ContextFlags & CONTEXT_CONTROL)
{
ThCtx->Rbp = Ctx->Rbp;
ThCtx->Rip = Ctx->Rip;
ThCtx->SegCs = Ctx->SegCs;
ThCtx->EFlags = Ctx->EFlags;
ThCtx->Rsp = Ctx->Rsp;
ThCtx->SegSs = Ctx->SegSs;
}
if(Ctx->ContextFlags & CONTEXT_SEGMENTS)
{
ThCtx->SegGs = Ctx->SegGs;
ThCtx->SegFs = Ctx->SegFs;
ThCtx->SegEs = Ctx->SegEs;
ThCtx->SegDs = Ctx->SegDs;
}
if(Ctx->ContextFlags & CONTEXT_INTEGER)
{
ThCtx->Rdi = Ctx->Rdi;
ThCtx->Rsi = Ctx->Rsi;
ThCtx->Rbx = Ctx->Rbx;
ThCtx->Rdx = Ctx->Rdx;
ThCtx->Rcx = Ctx->Rcx;
ThCtx->Rax = Ctx->Rax;
ThCtx->R8 = Ctx->R8;
ThCtx->R9 = Ctx->R9;
ThCtx->R10 = Ctx->R10;
ThCtx->R11 = Ctx->R11;
ThCtx->R12 = Ctx->R12;
ThCtx->R13 = Ctx->R13;
ThCtx->R14 = Ctx->R14;
ThCtx->R15 = Ctx->R15;
}
if(Ctx->ContextFlags & CONTEXT_FLOATING_POINT)
{
memcpy(&ThCtx->FltSave,&Ctx->FltSave,sizeof(XMM_SAVE_AREA32));
}
if(Ctx->ContextFlags & CONTEXT_XSTATE)
{
memcpy(&ThCtx->VectorRegister,&Ctx->VectorRegister,sizeof(Ctx->VectorRegister));
ThCtx->VectorControl = Ctx->VectorControl;
}
#else
if(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS)
{
ThCtx->Dr0 = Ctx->Dr0;
ThCtx->Dr1 = Ctx->Dr1;
ThCtx->Dr2 = Ctx->Dr2;
ThCtx->Dr3 = Ctx->Dr3;
ThCtx->Dr6 = Ctx->Dr6;
ThCtx->Dr7 = Ctx->Dr7;
}
if(Ctx->ContextFlags & CONTEXT_CONTROL)
{
ThCtx->Ebp = Ctx->Ebp;
ThCtx->Eip = Ctx->Eip;
ThCtx->SegCs = Ctx->SegCs;
ThCtx->EFlags = Ctx->EFlags;
ThCtx->Esp = Ctx->Esp;
ThCtx->SegSs = Ctx->SegSs;
}
if(Ctx->ContextFlags & CONTEXT_SEGMENTS)
{
ThCtx->SegGs = Ctx->SegGs;
ThCtx->SegFs = Ctx->SegFs;
ThCtx->SegEs = Ctx->SegEs;
ThCtx->SegDs = Ctx->SegDs;
}
if(Ctx->ContextFlags & CONTEXT_INTEGER)
{
ThCtx->Edi = Ctx->Edi;
ThCtx->Esi = Ctx->Esi;
ThCtx->Ebx = Ctx->Ebx;
ThCtx->Edx = Ctx->Edx;
ThCtx->Ecx = Ctx->Ecx;
ThCtx->Eax = Ctx->Eax;
}
if(Ctx->ContextFlags & CONTEXT_FLOATING_POINT)
{
memcpy(&ThCtx->FloatSave,&Ctx->FloatSave,sizeof(FLOATING_SAVE_AREA));
}
if(Ctx->ContextFlags & CONTEXT_EXTENDED_REGISTERS)
{
memcpy(&ThCtx->ExtendedRegisters,&Ctx->ExtendedRegisters,sizeof(Ctx->ExtendedRegisters));
}
if(Ctx->ContextFlags & CONTEXT_XSTATE) // TODO:
{
}
#endif
DBGMSG("Stored locally: %u",Idx);
return STATUS_SUCCESS;
}
//------------------------------------------------------------------------------------
NTSTATUS GetContextVal(UINT Idx, PCONTEXT Ctx)
{
if(!this->IsThreadIndexExist(Idx))return STATUS_NOT_FOUND;
if(!this->ThreadLst[Idx].pContext)return NtGetContextThread(this->ThreadLst[Idx].hThread, Ctx); // Not in exception handler
PCONTEXT ThCtx = (PCONTEXT)this->ThreadLst[Idx].pContext; // Exception handler`s Context
Ctx->ContextFlags &= ThCtx->ContextFlags; // Take only present groups
#ifdef _AMD64_
Ctx->MxCsr = ThCtx->MxCsr; // ?????????????
if(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS)
{
Ctx->Dr0 = ThCtx->Dr0;
Ctx->Dr1 = ThCtx->Dr1;
Ctx->Dr2 = ThCtx->Dr2;
Ctx->Dr3 = ThCtx->Dr3;
Ctx->Dr6 = ThCtx->Dr6;
Ctx->Dr7 = ThCtx->Dr7;
}
if(Ctx->ContextFlags & CONTEXT_CONTROL)
{
Ctx->Rbp = ThCtx->Rbp;
Ctx->Rip = ThCtx->Rip;
Ctx->SegCs = ThCtx->SegCs;
Ctx->EFlags = ThCtx->EFlags;
Ctx->Rsp = ThCtx->Rsp;
Ctx->SegSs = ThCtx->SegSs;
}
if(Ctx->ContextFlags & CONTEXT_SEGMENTS)
{
Ctx->SegGs = ThCtx->SegGs;
Ctx->SegFs = ThCtx->SegFs;
Ctx->SegEs = ThCtx->SegEs;
Ctx->SegDs = ThCtx->SegDs;
}
if(Ctx->ContextFlags & CONTEXT_INTEGER)
{
Ctx->Rdi = ThCtx->Rdi;
Ctx->Rsi = ThCtx->Rsi;
Ctx->Rbx = ThCtx->Rbx;
Ctx->Rdx = ThCtx->Rdx;
Ctx->Rcx = ThCtx->Rcx;
Ctx->Rax = ThCtx->Rax;
Ctx->R8 = ThCtx->R8;
Ctx->R9 = ThCtx->R9;
Ctx->R10 = ThCtx->R10;
Ctx->R11 = ThCtx->R11;
Ctx->R12 = ThCtx->R12;
Ctx->R13 = ThCtx->R13;
Ctx->R14 = ThCtx->R14;
Ctx->R15 = ThCtx->R15;
}
if(Ctx->ContextFlags & CONTEXT_FLOATING_POINT)
{
memcpy(&Ctx->FltSave,&ThCtx->FltSave,sizeof(XMM_SAVE_AREA32));
}
if(Ctx->ContextFlags & CONTEXT_XSTATE)
{
memcpy(&Ctx->VectorRegister,&ThCtx->VectorRegister,sizeof(Ctx->VectorRegister));
Ctx->VectorControl = ThCtx->VectorControl;
}
#else
if(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS)
{
Ctx->Dr0 = ThCtx->Dr0;
Ctx->Dr1 = ThCtx->Dr1;
Ctx->Dr2 = ThCtx->Dr2;
Ctx->Dr3 = ThCtx->Dr3;
Ctx->Dr6 = ThCtx->Dr6;
Ctx->Dr7 = ThCtx->Dr7;
}
if(Ctx->ContextFlags & CONTEXT_CONTROL)
{
Ctx->Ebp = ThCtx->Ebp;
Ctx->Eip = ThCtx->Eip;
Ctx->SegCs = ThCtx->SegCs;
Ctx->EFlags = ThCtx->EFlags;
Ctx->Esp = ThCtx->Esp;
Ctx->SegSs = ThCtx->SegSs;
}
if(Ctx->ContextFlags & CONTEXT_SEGMENTS)
{
Ctx->SegGs = ThCtx->SegGs;
Ctx->SegFs = ThCtx->SegFs;
Ctx->SegEs = ThCtx->SegEs;
Ctx->SegDs = ThCtx->SegDs;
}
if(Ctx->ContextFlags & CONTEXT_INTEGER)
{
Ctx->Edi = ThCtx->Edi;
Ctx->Esi = ThCtx->Esi;
Ctx->Ebx = ThCtx->Ebx;
Ctx->Edx = ThCtx->Edx;
Ctx->Ecx = ThCtx->Ecx;
Ctx->Eax = ThCtx->Eax;
}
if(Ctx->ContextFlags & CONTEXT_FLOATING_POINT)
{
memcpy(&Ctx->FloatSave,&ThCtx->FloatSave,sizeof(FLOATING_SAVE_AREA));
}
if(Ctx->ContextFlags & CONTEXT_EXTENDED_REGISTERS)
{
memcpy(&Ctx->ExtendedRegisters,&ThCtx->ExtendedRegisters,sizeof(Ctx->ExtendedRegisters));
}
if(Ctx->ContextFlags & CONTEXT_XSTATE) // TODO:
{
}
#endif
DBGMSG("Read locally: %u",Idx);
return STATUS_SUCCESS;
}
//------------------------------------------------------------------------------------
bool IsSingleStepping(UINT Idx)
{
// if(!this->IsThreadIndexExist(Idx))return false; // Used only by HandleException anyway
return this->ThreadLst[Idx].SyncGetFlags(SThDesc::tfTraceFlg);
}
//------------------------------------------------------------------------------------
bool UpdTraceFlag(UINT Idx, PCONTEXT Ctx)
{
if(!(Ctx->ContextFlags & CONTEXT_CONTROL) || !this->IsThreadIndexExist(Idx))return false;
this->ThreadLst[Idx].SetTraceFlagState(Ctx->EFlags & SThDesc::tfTraceFlagMsk); // Trap flag mask
return true;
}
//------------------------------------------------------------------------------------
/* The value of registers DR0-DR3 is preserved across all threads
31-16 15-14 13 12-10 9-0
DR7: ???? ???? ???? ???? ?? ? ??? ??????????
LNRW LNRW LNRW LNRW G 001 GLGLGLGLGL
3333 2222 1111 0000 D EE33221100
RW: 0=Exe,1=Wr,2=IO,3=RdWr
LN: 0=1,1=2,2=8,3=4
*/
bool UpdHardwareBp(UINT Idx, PCONTEXT Ctx)
{
if(!(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS) || !this->IsThreadIndexExist(Idx))return false;
SThDesc* ThDes = &this->ThreadLst[Idx];
memset((void*)&ThDes->HwBpLst,0,sizeof(ThDes->HwBpLst));
for(UINT ctr=0;ctr < 4;ctr++) // Nothing special for x64?
{
if(!(Ctx->Dr7 & (1ULL << (ctr*2))))continue; // Skip any not enabled // Windows uses 'local' breakpoints
BYTE LCod = (Ctx->Dr7 >> (18+(ctr*4))) & 3; // Breakpoint size
if(LCod & 2)ThDes->HwBpLst[ctr].Size = (LCod & 1)?(4):(8);
else ThDes->HwBpLst[ctr].Size = LCod+1;
switch(ctr)
{
case 0:
ThDes->HwBpLst[ctr].Addr = (PBYTE)Ctx->Dr0;
break;
case 1:
ThDes->HwBpLst[ctr].Addr = (PBYTE)Ctx->Dr1;
break;
case 2:
ThDes->HwBpLst[ctr].Addr = (PBYTE)Ctx->Dr2;
break;
case 3:
ThDes->HwBpLst[ctr].Addr = (PBYTE)Ctx->Dr3;
break;
}
}
return true;
}
//------------------------------------------------------------------------------------
bool IsHardwareBpHit(UINT Idx, PVOID Addr)
{
// if(!this->IsThreadIndexExist(Idx))return false; // Used only by HandleException anyway
SThDesc* ThDes = &this->ThreadLst[Idx];
for(UINT ctr=0;ctr < 4;ctr++) // Nothing special for x64?
{
if(!ThDes->HwBpLst[ctr].Addr)continue;
if(((PBYTE)Addr >= ThDes->HwBpLst[ctr].Addr)&&((PBYTE)Addr < &ThDes->HwBpLst[ctr].Addr[ThDes->HwBpLst[ctr].Size]))return true;
}
return false;
}
//------------------------------------------------------------------------------------
bool ReadDbgContext(UINT Idx, PCONTEXT Ctx) // Remember DRx changes, made by an application
{
if(!this->IsThreadIndexExist(Idx))return false;
SThDesc* ThDes = &this->ThreadLst[Idx];
if(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS) // Only if present in Src
{
ThDes->DbgCtx.Dr0 = Ctx->Dr0;
ThDes->DbgCtx.Dr1 = Ctx->Dr1;
ThDes->DbgCtx.Dr2 = Ctx->Dr2;
ThDes->DbgCtx.Dr3 = Ctx->Dr3;
ThDes->DbgCtx.Dr6 = Ctx->Dr6;
ThDes->DbgCtx.Dr7 = Ctx->Dr7;
}
if(Ctx->ContextFlags & CONTEXT_CONTROL)ThDes->DbgCtx.TrFlg = (Ctx->EFlags & 0x0100); // ResumeFlag?
return false;
}
//------------------------------------------------------------------------------------
bool WriteDbgContext(UINT Idx, PCONTEXT Ctx) // Restore DRx state to show it to an application
{
if(!this->IsThreadIndexExist(Idx))return false;
SThDesc* ThDes = &this->ThreadLst[Idx];
if(Ctx->ContextFlags & CONTEXT_DEBUG_REGISTERS) // Only if required by dest
{
Ctx->Dr0 = ThDes->DbgCtx.Dr0;
Ctx->Dr1 = ThDes->DbgCtx.Dr1;
Ctx->Dr2 = ThDes->DbgCtx.Dr2;
Ctx->Dr3 = ThDes->DbgCtx.Dr3;
Ctx->Dr6 = ThDes->DbgCtx.Dr6;
Ctx->Dr7 = ThDes->DbgCtx.Dr7;
}
if(Ctx->ContextFlags & CONTEXT_CONTROL)Ctx->EFlags = (Ctx->EFlags & ~0x0100)|((UINT)ThDes->DbgCtx.TrFlg << 8);
return false;
}
//------------------------------------------------------------------------------------
int ReportDeadThreadDbgEvt(int ThIndex) // Requires Lock // TEB is already deallocated. Thread`s handle is in STATUS_THREAD_IS_TERMINATING state // Somehow a thread may avoid NtTerminateThread and die
{
SThDesc* Desc = this->GetThreadDesc(ThIndex);
if(Desc->Flags & SThDesc::tfMarkedForRemove)return 0; // Already removing
this->DbgEventCnt++;
DbgEvtEx* evt = this->PushDbgEvent();
evt->dwDebugEventCode = EXIT_THREAD_DEBUG_EVENT;
evt->dwProcessId = NtCurrentProcessId(); // this->CurProcID;
evt->dwThreadId = Desc->ThreadID; // Do not access its TEB in case it is already deallocated
evt->PathSize = 0;
evt->u.ExitThread.dwExitCode = 0;
Desc->Flags |= SThDesc::tfMarkedForRemove;
DBGMSG("PushDbgEvt: ThreadID=%08X(%u), ExitCode=%08X",Desc->ThreadID,Desc->ThreadID,evt->u.ExitThread.dwExitCode);
return 0;
}
//------------------------------------------------------------------------------------
};
//====================================================================================
class CSwBpList // TODO: PAGE breakpoints
{
SHM::CCritSectEx<> csec;
SHM::CGrowArr<PVOID, 32> SwBpLst;
public:
//------------------------------------------------------------------------------------
CSwBpList(void)
{
}
//------------------------------------------------------------------------------------
~CSwBpList()
{
}
//------------------------------------------------------------------------------------
int AddBP(PVOID Addr)
{
this->csec.Lock();
int BpIdx = -1;
for(UINT ctr=0,total=this->SwBpLst.Count();ctr < total;ctr++)
{
PVOID Val = this->SwBpLst[ctr];
if(Val == Addr){this->csec.Unlock(); return ctr;} // Already in list
if(!Val)BpIdx = ctr;
}
if(BpIdx < 0)
{
BpIdx = this->SwBpLst.Count();
this->SwBpLst.Add(NULL);
}
this->SwBpLst[BpIdx] = Addr;
this->csec.Unlock();
DBGMSG("Adding SwBP: %u",BpIdx);
return BpIdx;
}
//------------------------------------------------------------------------------------
int DelBP(PVOID Addr)
{
this->csec.Lock();
int BpIdx = this->GetBpIdxForAddr(Addr);
if(BpIdx < 0){this->csec.Unlock(); return -1;}
this->SwBpLst[BpIdx] = NULL;
this->csec.Unlock();
DBGMSG("Removing SwBP: %u",BpIdx);
return BpIdx;
}
//------------------------------------------------------------------------------------
int IsHitBP(PVOID Addr){return (this->GetBpIdxForAddr(Addr) >= 0);}
int GetBpIdxForAddr(PVOID Addr)
{
this->csec.Lock();
for(UINT ctr=0,total=this->SwBpLst.Count();ctr < total;ctr++)
{
PVOID Cadr = this->SwBpLst[ctr];
if(Cadr && (Cadr == Addr)){this->csec.Unlock(); return ctr;}
}
this->csec.Unlock();
return -1;
}
//------------------------------------------------------------------------------------
};
//====================================================================================
//
//
//
//====================================================================================
class CDbgClient: public SHM::CMessageIPC
{
bool BreakWrk;
bool InDbgEvent;
bool DbgAttached;
DWORD ExcludedThID;
DWORD DbgBrkThID;
DWORD ClientThID;
DWORD MainThID;
DWORD CurProcID;
PVOID hClientDll;
HANDLE hIPCThread;
UINT IPCSize;
UINT UrsOpts;
CSwBpList BpList;
CThreadList ThList;
//------------------------------------------------------------------------------------
_declspec(noinline) static void DoDbgBreak(PVOID This){__debugbreak();} // Makes it harder to track 'int 3'?
static bool IsAddrInDbgBreak(PVOID Addr){return (((PBYTE)Addr >= (PBYTE)&DoDbgBreak)&&((PBYTE)Addr < ((PBYTE)&DoDbgBreak + 64)));}
static void _fastcall DbgBreakThread(PVOID ThreadParameter)
{
CDbgClient* DbgIPC = (CDbgClient*)ThreadParameter;
DoDbgBreak(DbgIPC); // x64Dbg will continue normally from this // Any DebugBreak functions may be tracked
NtTerminateThread(NtCurrentThread, 0);
}
//------------------------------------------------------------------------------------
PTEB FindModulesAndTEBs(TEB* CurTeb, SHM::CGrowArrImpl<PBYTE>* ModArr, SHM::CGrowArrImpl<PTEB>* TebArr, int* MainThreadIndex=NULL)
{
MEMORY_BASIC_INFORMATION meminfo;
SIZE_T RetLen = 0;
SIZE_T MemoryInformationLength = sizeof(MEMORY_BASIC_INFORMATION);
PBYTE BaseAddress = NULL;
PVOID LastABase = NULL;
PTEB MainThTeb = NULL;
long MainThIdx = -1;
LARGE_INTEGER MinCrtTime;
LARGE_INTEGER CurrCrtTime;
DBGMSG("Current: PEB=%p, TEB=%p",CurTeb->ProcessEnvironmentBlock,CurTeb);
this->ThList.Lock();
MinCrtTime.QuadPart = -1i64;
for(;!NtQueryVirtualMemory(NtCurrentProcess,BaseAddress,MemoryBasicInformation,&meminfo,MemoryInformationLength,&RetLen); BaseAddress += meminfo.RegionSize)
{
// DBGMSG("BLK: Addr=%p, Base=%p, ABase=%p, Size=%08X, Type=%08X, State=%08X, Protect=%08X, AProtect=%08X",BaseAddress,meminfo.BaseAddress,meminfo.AllocationBase,meminfo.RegionSize,meminfo.Type,meminfo.State,meminfo.Protect,meminfo.AllocationProtect);
if((meminfo.Type == MEM_IMAGE) && (meminfo.State == MEM_COMMIT))
{
if(LastABase == meminfo.AllocationBase)continue;
LastABase = meminfo.AllocationBase;
if(NPEFMT::IsValidPEHeader(BaseAddress))
{
DBGMSG("Found PE image at %p",BaseAddress);
*ModArr->Add(NULL) = BaseAddress;
}
}
else if((meminfo.Type == MEM_PRIVATE) && (meminfo.State == MEM_COMMIT) && (meminfo.Protect == meminfo.AllocationProtect) && (meminfo.Protect == PAGE_READWRITE) && (meminfo.RegionSize >= 0x1000) && (meminfo.RegionSize < 0x100000)) // WinXP TEB >= 0x2000 ? // Win7 x32 TEB Blk is 0x1000 // On latest Win10 many TEBs in same big block as PEB
{
PBYTE DataPtr = (PBYTE)BaseAddress;
for(UINT Offset=0;Offset < meminfo.RegionSize;Offset+=0x1000) // Find all TEBs in the block
{
TEB* MayBeTEB = (TEB*)&DataPtr[Offset];
if((MayBeTEB->ProcessEnvironmentBlock == CurTeb->ProcessEnvironmentBlock) && (MayBeTEB->ClientId.UniqueProcess == CurTeb->ClientId.UniqueProcess)) // && (MayBeTEB->CurrentLocale == CurTeb->CurrentLocale))
{
DBGMSG("Found TEB at %p, %u",MayBeTEB, (UINT)MayBeTEB->ClientId.UniqueThread);
if((MayBeTEB != CurTeb) && ((UINT)MayBeTEB->ClientId.UniqueThread != this->ExcludedThID)) // Assuming that CurTeb belongs to Client Thread
{
int ThIdx = this->ThList.AddThreadToList(MayBeTEB, 0, NULL, &CurrCrtTime);
if(ThIdx >= 0)
{
*TebArr->Add(NULL) = MayBeTEB; // Includes ClientThread
// DBGMSG("MainThTeb=%p, CurrCrtTime=%016llX, MinCrtTime=%016llX",MainThTeb, CurrCrtTime.QuadPart, MinCrtTime.QuadPart);
if((UINT64)CurrCrtTime.QuadPart < (UINT64)MinCrtTime.QuadPart){MainThTeb = MayBeTEB; MainThIdx = ThIdx; MinCrtTime.QuadPart = CurrCrtTime.QuadPart;} // Not reliable!
}
}
else {DBGMSG("Skipping the excluded thread: %u", (UINT)MayBeTEB->ClientId.UniqueThread);}
}
}
}
}
if(MainThreadIndex)*MainThreadIndex = MainThIdx;
this->ThList.UnLock();
return MainThTeb;
}
//------------------------------------------------------------------------------------
// NOTE: Buffer is locked by this thread in message enumeration
//
int ProcessRequestDbg(SMsgHdr* Req)
{
SHM::CArgPack<2048> api; // '__chkstk' is disabled with '/Gs100000000' // -Gs9999999
SHM::CArgPack<2048> apo; // Had to put it here to save some stack space (Because variables for each scope are allocated at beginning of the function)
DBGMSG("ReqAddr=%p, MsgID=%u, MsgSeqID=%u",Req,Req->MsgID, Req->GetBlk()->MsgSeqID);
// static UINT LastMsg = 0;
// if(Req->GetBlk()->MsgSeqID <= LastMsg){ DBGMSG("Trouble!"); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// LastMsg = Req->GetBlk()->MsgSeqID;
switch(Req->MsgID)
{
case miDebugActiveProcess:
{
BOOL Reslt = TRUE;
DWORD dwProcessId = 0;
api.Assign((PBYTE)&Req->Data,Req->DataSize);
api.PopArg(dwProcessId);
if(dwProcessId != this->CurProcID){DBGMSG("Process ID mismatch: %08X:%08X",dwProcessId,this->CurProcID); return -1;} // Allow to fail here?
this->DbgAttached = true;
SHM::CGrowArr<PTEB, 128> TebArr; // NOTE: Stack arrays reserved on stack forever
SHM::CGrowArr<PBYTE, 128> ModArr; // 2048
int MainThIdx = -1;
PTEB CurTeb = NtCurrentTeb(); // ThreadID is DbgIPC->ClientThID and should not be reported to a debugger
PTEB MainThTeb = this->FindModulesAndTEBs(CurTeb, &ModArr, &TebArr, &MainThIdx);
DBGMSG("MainThTeb: %p",MainThTeb); // May happen to be NULL :)
this->MainThID = (UINT)MainThTeb->ClientId.UniqueThread; // MainThTeb should be present!!! // Report this only in CREATE_PROCESS_DEBUG_EVENT // Not guranteed to return a real main(first) thread
HANDLE hPHandle = UintToFakeHandle(this->CurProcID);
apo.PushArg(hPHandle);
HANDLE hTHandle = UintToFakeHandle(MainThIdx);
apo.PushArg(hTHandle);
apo.PushArg(MainThTeb);
apo.PushArg(this->MainThID);
apo.PushArg(Reslt);
DBGMSG("miDebugActiveProcess PutMsg: hPHandle=%08X, hTHandle=%08X, MainThId=%u, Size=%u",hPHandle,hTHandle,this->MainThID,apo.GetLen());
this->PutMsg(mtDbgRsp, miDebugActiveProcess, Req->Sequence, apo.GetPtr(), apo.GetLen());
DBGMSG("Modules=%u, Threads=%u, MainThreadID=%u, ClientThreadID=%u",ModArr.Count(),TebArr.Count(),this->MainThID,this->ClientThID);
for(int Ctr=TebArr.Count()-1;Ctr >= 0;Ctr--) // Originally all threads suspended by DebugActiveProcess before any of debug events reported but we do not have any handles yet
{
TEB* pTeb = TebArr[Ctr];
UINT ThID = (UINT)pTeb->ClientId.UniqueThread;
if((ThID == this->ClientThID)||(ThID == this->MainThID)||(ThID == this->ExcludedThID))continue; // Do not report Client, Caller thread and Main thread(again) // Man thread must be reported only in CREATE_PROCESS_DEBUG_EVENT
this->Report_CREATE_THREAD_DEBUG_EVENT(pTeb, false, true); // Open a thread`s handle, report it and suspend
}
for(int Ctr=ModArr.Count()-1;Ctr >= 0;Ctr--) // Must be AFTER reporting and supending of all threads
{
PVOID hModule = ModArr[Ctr];
if((hModule == this->hClientDll)||(hModule == CurTeb->ProcessEnvironmentBlock->ImageBaseAddress))continue; // Do not report Client DLL and main module
this->Report_LOAD_DLL_DEBUG_INFO(MainThTeb, hModule, true); // No suspending here (Only a main thread is registered anyway)
}
this->Report_CREATE_PROCESS_DEBUG_EVENT(MainThTeb); // Report process creation // Suspend Main Thread
this->DispatchDebugEvents(true); // Dispatch initial events backwards
}
break;
case miDebugActiveProcessStop:
{
DBGMSG("miDebugActiveProcessStop");
this->DbgAttached = false;
}
break;
case miContinueDebugEvent:
{
BOOL Reslt = TRUE;
DWORD dwProcessId = 0;
DWORD dwThreadId;
DWORD dwContinueStatus;
api.Assign((PBYTE)&Req->Data,Req->DataSize);
api.PopArg(dwProcessId);
api.PopArg(dwThreadId);
api.PopArg(dwContinueStatus);
if(dwProcessId != this->CurProcID){DBGMSG("Process ID mismatch: %08X:%08X",dwProcessId,this->CurProcID);}
int res = -1;
int SingleThreadIdx = -1;
bool DbgContinue = (dwContinueStatus == DBG_CONTINUE);
apo.PushArg(Reslt);
DBGMSG("miContinueDebugEvent PutMsg: ThId=%u, Size=%u",dwThreadId,apo.GetLen());
this->PutMsg(mtDbgRsp, miContinueDebugEvent, Req->Sequence, apo.GetPtr(), apo.GetLen()); // Report before resuming any threads because it may be a thread at NtTerminateProcess
this->ThList.Lock();
this->ThList.DbgEventCnt--;
DBGMSG("EventsAfter=%u, InStack=%u",this->ThList.DbgEventCnt,this->ThList.EventsInStack());
if(!this->EvtSuspAllTh) // Resumes all threads or at least the event`s thread
{
if(SingleThreadIdx < 0)SingleThreadIdx = this->ThList.FindThreadIdxInList(nullptr, dwThreadId);
if(SingleThreadIdx >= 0)res = this->ThList.Resume(SingleThreadIdx, NULL, DbgContinue);
else {DBGMSG("miContinueDebugEvent: Thread ID not found: ThId=%u",dwThreadId);}
}
else res = (this->ThList.DbgEventCnt > 0)?0:(int)this->ThList.ResumeAllThreads(dwThreadId, SingleThreadIdx, DbgContinue);
this->ThList.UnLock(); // What if this thread will be terminatred by NtTerminateProcess before UnLock?
if(res < 0){DBGMSG("miContinueDebugEvent: DoResumeThread(s) failed: ThId=%u, Err=%i",dwThreadId,res);}
this->DispatchDebugEvents(true); // Dispatch any queued debug events