-
Notifications
You must be signed in to change notification settings - Fork 51
/
Debuger.pas
2849 lines (2333 loc) · 84.4 KB
/
Debuger.pas
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
unit Debuger;
interface
uses
WinApi.Windows, System.Classes, System.SysUtils, System.SyncObjs,
ClassUtils, JclPeImage, JclDebug, DebugerTypes, DbgHookTypes,
Collections.Queues, Collections.Dictionaries, DbgMemoryProfiler,
DbgSyncObjsProfiler, DbgSamplingProfiler, DbgCodeProfiler;
type
TDebuger = class
strict private
FProcessData: TProcessData; // Ñëóæåáíàÿ èíôîðìàöèÿ îá îòëàæèâàåìîì ïðîöåññå
private
FThreadList: TDbgThreadList; // Äàííûå î âñåõ ïîòîêàõ îòëàæèâàåìîãî ïðîöåññà
FThreadAdvInfoList: TThreadAdvInfoList; // Äîïîëíèòåëüíàÿ èíôîðìàöèÿ î ïîòîêàõ
FActiveThreadList: TDbgActiveThreadList; // Ñïèñîê àêòèâíûõ ïîòîêîâ
FSetEntryPointBreakPoint: LongBool; // Ôëàã óêàçûâàþùèé îòëàä÷èêó, íåîáõîäèìî ëè ñòàâèòü ÂÐ íà ÅÐ
FBreakpointList: TBreakpointList; // Ñïèñîê ÂÐ è ÌÂÐ
FRestoreBPIndex: Integer; // Èíäåêñ äëÿ âîññòàíîâëåíèÿ ÂÐ
FRestoreMBPIndex: Integer; // Èíäåêñ äëÿ âîññòàíîâëåíèÿ ÌÂÐ
FRestoredHWBPIndex: Integer; // Èíäåêñû äëÿ âîññòàíîâëåíèÿ ÍÂÐ
FRestoredThread: TThreadId;
FCloseDebugProcess: LongBool; // Ôëàã óêàçûâàþùèé íóæíî ëè çàêðûâàòü îòëàæèâàåìûé ïðîöåññ ïðè çàâåðøåíèè îòëàäêè
FContinueStatus: DWORD; // Ñòàòóñ ñ êîòîðûì âûçûâàåòñÿ ContinueDebugEvent
FResumeAction: TResumeAction; // Ôëàã ïîâåäåíèÿ îòëàä÷èêà ïîñëå îáðàáîòêè î÷åðåäíîãî ñîáûòèÿ
FRemoveCurrentBreakpoint: LongBool; // Ôëàã óäàëåíèÿ òåêóùåãî ÂÐ
FCurThreadId: TThreadId;
FCurThreadData: PThreadData;
FDbgState: TDbgState;
FDbgTraceState: TDbgTraceState;
FTraceEvent: TEvent;
FTraceCounter: Cardinal;
// Debug options
FPerfomanceMode: LongBool;
FExceptionCheckMode: LongBool;
FExceptionCallStack: LongBool;
FCodeTracking: LongBool;
FTrackSystemUnits: LongBool;
FSamplingMethod: LongBool;
// ---
FMemoryBPCheckMode: LongBool;
FPerfomanceCheckPtr: Pointer;
// âíåøíèå ñîáûòèÿ
FMainLoopFailed: TNotifyEvent;
FCreateThread: TCreateThreadEvent;
FCreateProcess: TCreateProcessEvent;
FExitThread: TExitThreadEvent;
FExitProcess: TExitProcessEvent;
FLoadDll: TLoadDllEvent;
FUnLoadDll: TUnLoadDllEvent;
FDebugString: TDebugStringEvent;
FRip: TRipEvent;
FEndDebug: TNotifyEvent;
FChangeDebugState: TNotifyEvent;
FDbgLog: TDbgLogEvent;
FDbgLogMode: LongBool; // Äåáàæíûé ðåæèì
FExceptionEvents: TExceptionEvents;
FBreakPoint: TBreakPointEvent;
FHardwareBreakpoint: THardwareBreakpointEvent;
FDbgMemoryProfiler: TDbgMemoryProfiler;
FDbgSyncObjsProfiler: TDbgSyncObjsProfiler;
FDbgSamplingProfiler: TDbgSamplingProfiler;
FDbgCodeProfiler: TDbgCodeProfiler;
function GetExceptionEvent(const Index: TExceptionCode): TDefaultExceptionEvent;
procedure SetExceptionEvent(const Index: TExceptionCode; const Value: TDefaultExceptionEvent);
procedure SetCloseDebugProcess(const Value: LongBool);
procedure SetPerfomanceMode(const Value: LongBool);
procedure SetCodeTracking(const Value: LongBool);
procedure SetTrackSystemUnits(const Value: LongBool);
procedure SetExceptionCallStack(const Value: LongBool);
procedure SetExceptionCheckMode(const Value: LongBool);
procedure DoSetBreakpoint(const Address: Pointer; var SaveByte: Byte);
procedure DoSetBreakpointF(const Address: Pointer; var SaveByte: Byte);
//procedure DoRemoveBreakpoint(const Address: Pointer; const SaveByte: Byte);
procedure DoRemoveBreakpointF(const Address: Pointer; const SaveByte: Byte);
//procedure DoRestoreBreakpoint(const Address: Pointer);
procedure DoRestoreBreakpointF(const Address: Pointer);
procedure SetDbgTraceState(const Value: TDbgTraceState);
procedure SetDbgState(const Value: TDbgState);
procedure SetSamplingMethod(const Value: LongBool);
function GetActive: LongBool; inline;
protected
// ðàáîòà ñ äàííûìè î íèòÿõ îòëàæèâàåìîãî ïðèëîæåíèÿ
function AddThread(const ThreadID: TThreadId; ThreadHandle: THandle): PThreadData;
procedure RemoveThread(const ThreadID: TThreadId);
function GetThreadIndex(const ThreadID: TThreadId; const UseFinished: LongBool = False): Integer;
function GetThreadInfoIndex(const ThreadId: TThreadId): Integer;
function AddThreadInfo(const ThreadId: TThreadId): PThreadAdvInfo;
function GetThreadInfo(const ThreadId: TThreadId): PThreadAdvInfo;
function SetThreadInfo(const ThreadId: TThreadId): PThreadAdvInfo;
// îáðàáîò÷èêè îòëàäî÷íûõ ñîáûòèé ïåðâîé î÷åðåäè
procedure DoCreateProcess(DebugEvent: PDebugEvent);
procedure DoExitProcess(DebugEvent: PDebugEvent);
procedure DoCreateThread(DebugEvent: PDebugEvent);
procedure DoExitThread(DebugEvent: PDebugEvent);
procedure DoLoadDll(DebugEvent: PDebugEvent);
procedure DoUnLoadDll(DebugEvent: PDebugEvent);
procedure DoDebugString(DebugEvent: PDebugEvent);
procedure DoRip(DebugEvent: PDebugEvent);
procedure DoEndDebug;
procedure DoDebugerFailed;
procedure DoResumeAction(const ThreadID: TThreadId);
procedure DoDbgLog(const ThreadId: TThreadId; const LogData: String);
// îáðàáîò÷èêè îòëàäî÷íûõ ñîáûòèé âòîðîé î÷åðåäè
procedure CallUnhandledExceptionEvents(const Code: TExceptionCode; DebugEvent: PDebugEvent);
procedure CallUnhandledBreakPointEvents(const Code: TExceptionCode; DebugEvent: PDebugEvent);
procedure ProcessExceptionBreakPoint(DebugEvent: PDebugEvent);
function ProcessUserBreakPoint(DebugEvent: PDebugEvent): LongBool;
function ProcessTraceBreakPoint(DebugEvent: PDebugEvent): LongBool;
procedure ProcessExceptionSingleStep(DebugEvent: PDebugEvent);
procedure ProcessExceptionGuardPage(DebugEvent: PDebugEvent);
procedure SetThreadName(DebugEvent: PDebugEvent);
procedure ProcessDbgException(DebugEvent: PDebugEvent);
procedure ProcessDbgThreadInfo(DebugEvent: PDebugEvent);
procedure ProcessDbgMemoryInfo(DebugEvent: PDebugEvent);
procedure ProcessDbgPerfomance(DebugEvent: PDebugEvent);
procedure ProcessDbgSyncObjsInfo(DebugEvent: PDebugEvent);
procedure ProcessDbgTraceInfo(DebugEvent: PDebugEvent);
procedure ProcessDbgSamplingInfo(DebugEvent: PDebugEvent);
function ProcessHardwareBreakpoint(DebugEvent: PDebugEvent): LongBool;
// ðàáîòà ñ òî÷êàìè îñòàíîâêè
function AddNewBreakPoint(var Value: TBreakpoint): LongBool;
procedure CheckBreakpointIndex(Value: Integer);
function CheckIsAddrInRealMemoryBPRegion(BreakPointIndex: Integer; AAddr: Pointer): LongBool;
function GetBPIndex(BreakPointAddr: Pointer; const ThreadID: TThreadId = 0): Integer;
function GetMBPIndex(BreakPointAddr: Pointer; FromIndex: Integer = 0): Integer;
function IsBreakpointPresent(const Value: TBreakpoint): LongBool;
procedure ToggleInt3Breakpoint(Index: Integer; Active: LongBool);
procedure ToggleMemoryBreakpoint(Index: Integer; Active: LongBool);
procedure UpdateHardwareBreakpoints(const ThreadID: TThreadId);
function PerfomancePauseDebug: LongBool;
function AddThreadPointInfo(ThreadData: PThreadData; const PointType: TDbgPointType; DebugEvent: PDebugEvent = nil): LongBool;
function AddProcessPointInfo(const PointType: TDbgPointType): LongBool;
public
constructor Create;
destructor Destroy; override;
procedure ClearDbgInfo;
procedure Log(const Msg: String);
// çàïóñê/îñòàíîâêà îòëàäêè
function AttachToProcess(const ProcessID: TProcessId; SentEntryPointBreakPoint: LongBool): LongBool;
function DebugNewProcess(const AppPath: string; var ErrInfo: String; const RunParams: String = ''; const WorkingDirectory: String = ''): LongBool;
function StopDebug: LongBool;
function PauseDebug: LongBool;
function ContinueDebug: LongBool;
function TraceDebug(const TraceType: TDbgTraceState): LongBool;
// Îñíîâíîé öèêë îáðàáîòêè äåáàæíûõ ñîáûòèé
procedure ProcessDebugEvents;
// ÷òåíèå çàïèñü äàííûõ
Function ProcAllocMem(const Size: Cardinal): Pointer;
Procedure ProcFreeMem(Data : Pointer; const Size: NativeUInt = 0);
procedure InjectThread(hProcess: THandle; Func: Pointer; FuncSize: Cardinal; aParams: Pointer;
aParamsSize: Cardinal; WaitAndFree: LongBool = True);
function InjectFunc(Func: Pointer; const CodeSize: Cardinal): Pointer;
procedure InjectPerfThread;
procedure InjectPerfFunc;
function ReadData(const AddrPrt, ResultPtr: Pointer; const DataSize: Integer): LongBool;
function ReadStringA(AddrPrt: Pointer; Len: Integer = 0): AnsiString;
function ReadStringW(AddrPrt: Pointer; Len: Integer = 0): WideString;
function ReadStringP(AddrPrt: Pointer; Len: Byte = 0): ShortString;
function WriteData(AddrPrt, DataPtr: Pointer; const DataSize: Cardinal): LongBool;
procedure SetFlag(const ThreadID: TThreadId; Flag: DWORD; Value: LongBool);
function GetFlag(const ThreadID: TThreadId; Flag: DWORD): LongBool;
function UpdateThreadContext(const ThreadID: TThreadId; const ContextFlags: Cardinal = CONTEXT_FULL): PThreadData; overload;
function UpdateThreadContext(ThreadData: PThreadData; const ContextFlags: Cardinal = CONTEXT_FULL): LongBool; overload;
function UpdateCurThreadContext(const ContextFlags: Cardinal = CONTEXT_FULL): LongBool;
function GetRegisters(const ThreadID: TThreadId): TContext;
procedure SetRegisters(const ThreadID: TThreadId; var Context: TContext);
procedure SetSingleStepMode(const ThreadID: TThreadId; const RestoreEIPAfterBP: LongBool); overload;
procedure SetSingleStepMode(ThData: PThreadData; const RestoreEIPAfterBP: LongBool); overload;
Function IsValidAddr(Const Addr: Pointer): LongBool;
Function IsValidCodeAddr(Const Addr: Pointer): LongBool;
Function IsValidProcessCodeAddr(Const Addr: Pointer): LongBool;
procedure GetCallStack(ThData: PThreadData; var Stack: TDbgInfoStack);
procedure GetCallStackEx(ThData: PThreadData; var Stack: TDbgInfoStack);
function GetThreadData(const ThreadID: TThreadId; const UseFinished: LongBool = False): PThreadData;
function CurThreadId: TThreadId;
function CurThreadData: PThreadData;
function GetThreadCount: Integer;
function GetThreadDataByIdx(const Idx: Integer): PThreadData;
procedure GetActiveThreads(var Res: TDbgActiveThreads);
// âûïîëíåíèå êîäà
Procedure ExecuteCode(AddrPtr: Pointer; const TimeOut: Cardinal);
function GetDllName(lpImageName, lpBaseOfDll: Pointer; var Unicode: LongBool): AnsiString;
// ðàáîòà ñ òî÷êàìè îñòàíîâêè
function SetUserBreakpoint(Address: Pointer; const ThreadId: TThreadId = 0; const Description: string = ''): LongBool;
function SetMemoryBreakpoint(Address: Pointer; Size: Cardinal; BreakOnWrite: LongBool; const Description: string): LongBool;
procedure RemoveBreakpoint(const Address: Pointer; const SaveByte: Byte); overload; inline;
procedure SetBreakpoint(const Address: Pointer; var SaveByte: Byte); inline;
procedure RestoreBreakpoint(const Address: Pointer); inline;
procedure RemoveBreakpoint(Index: Integer); overload;
procedure ToggleBreakpoint(Index: Integer; Active: LongBool);
function BreakpointCount: Integer;
function BreakpointItem(Index: Integer): TBreakpoint;
procedure RemoveCurrentBreakpoint;
// ðàáîòà ñ àïïàðàòíûìè òî÷êàìè îñòàíîâêè
procedure SetHardwareBreakpoint(const ThreadId: TThreadID; Address: Pointer; Size: THWBPSize; Mode: THWBPMode; HWIndex: THWBPIndex; const Description: string);
procedure ToggleHardwareBreakpoint(const ThreadId: TThreadID; Index: THWBPIndex; Active: LongBool);
procedure DropHardwareBreakpoint(const ThreadId: TThreadID; Index: THWBPIndex);
procedure DropAllHardwareBreakpoint(const ThreadId: TThreadID);
// âíóòðåííèå ñîáûòèÿ îòëàä÷èêà
property OnMainLoopFailed: TNotifyEvent read FMainLoopFailed write FMainLoopFailed;
property OnEndDebug: TNotifyEvent read FEndDebug write FEndDebug;
property OnChangeDebugState: TNotifyEvent read FChangeDebugState write FChangeDebugState;
// îáðàáîò÷èêè îòëàäî÷íûõ ñîáûòèé
property OnCreateThread: TCreateThreadEvent read FCreateThread write FCreateThread;
property OnCreateProcess: TCreateProcessEvent read FCreateProcess write FCreateProcess;
property OnExitThread: TExitThreadEvent read FExitThread write FExitThread;
property OnExitProcess: TExitProcessEvent read FExitProcess write FExitProcess;
property OnLoadDll: TLoadDllEvent read FLoadDll write FLoadDll;
property OnUnloadDll: TUnLoadDllEvent read FUnLoadDll write FUnLoadDll;
property OnDebugString: TDebugStringEvent read FDebugString write FDebugString;
property OnRip: TRipEvent read FRip write FRip;
property OnDbgLog: TDbgLogEvent read FDbgLog write FDbgLog;
property DbgLogMode: LongBool read FDbgLogMode write FDbgLogMode;
// îáðàáîò÷èêè èñêëþ÷åíèé
property OnBreakPoint: TBreakPointEvent read FBreakPoint write FBreakPoint;
property OnHardwareBreakpoint: THardwareBreakpointEvent read FHardwareBreakpoint write FHardwareBreakpoint;
property OnUnknownException: TDefaultExceptionEvent index ecUnknown read GetExceptionEvent write SetExceptionEvent;
property OnUnknownBreakPoint: TDefaultExceptionEvent index ecBreakpoint read GetExceptionEvent write SetExceptionEvent;
property OnSingleStep: TDefaultExceptionEvent index ecSingleStep read GetExceptionEvent write SetExceptionEvent;
property OnCtrlC: TDefaultExceptionEvent index ecCtrlC read GetExceptionEvent write SetExceptionEvent;
property OnNonContinuable: TDefaultExceptionEvent index ecNonContinuable read GetExceptionEvent write SetExceptionEvent;
property OnPageGuard: TDefaultExceptionEvent index ecGuard read GetExceptionEvent write SetExceptionEvent;
// ðàñøèðåííûå ñâîéñòâà îòëàä÷èêà
property ContinueStatus: DWORD read FContinueStatus write FContinueStatus;
property CloseDebugProcessOnFree: LongBool read FCloseDebugProcess write SetCloseDebugProcess;
property ProcessData: TProcessData read FProcessData;
property ResumeAction: TResumeAction read FResumeAction write FResumeAction;
property DbgState: TDbgState read FDbgState write SetDbgState;
property DbgTraceState: TDbgTraceState read FDbgTraceState write SetDbgTraceState;
property Active: LongBool read GetActive;
// Îïöèè ïðîôàéëåðà
property PerfomanceMode: LongBool read FPerfomanceMode write SetPerfomanceMode;
property ExceptionCheckMode: LongBool read FExceptionCheckMode write SetExceptionCheckMode;
property ExceptionCallStack: LongBool read FExceptionCallStack write SetExceptionCallStack;
property CodeTracking: LongBool read FCodeTracking write SetCodeTracking;
property TrackSystemUnits: LongBool read FTrackSystemUnits write SetTrackSystemUnits;
property SamplingMethod: LongBool read FSamplingMethod write SetSamplingMethod;
property MemoryBPCheckMode: LongBool read FMemoryBPCheckMode write FMemoryBPCheckMode;
property DbgMemoryProfiler: TDbgMemoryProfiler read FDbgMemoryProfiler;
property DbgSysncObjsProfiler: TDbgSyncObjsProfiler read FDbgSyncObjsProfiler;
property DbgSamplingProfiler: TDbgSamplingProfiler read FDbgSamplingProfiler;
property DbgCodeProfiler: TDbgCodeProfiler read FDbgCodeProfiler;
end;
var
gvDebuger: TDebuger = nil;
implementation
uses
RTLConsts, Math, DebugHook, DebugInfo, WinAPIUtils, Winapi.TlHelp32, Winapi.ImageHlp,
System.Contnrs, System.AnsiStrings, CollectList, Collections.Base,
DbgWorkerThread;
function _DbgPerfomanceHook(pvParam: Pointer): DWORD; stdcall;
begin
Result := DWORD(@_DbgPerfomanceHook);
end;
function CodeDataToExceptionCode(const Value: DWORD): TExceptionCode;
const
EXCEPTION_UNKNOWN = 0;
ExceptionCodeData: array [TExceptionCode] of DWORD = (
EXCEPTION_UNKNOWN,
EXCEPTION_BREAKPOINT,
EXCEPTION_SINGLE_STEP,
DBG_CONTROL_C,
EXCEPTION_NONCONTINUABLE_EXCEPTION,
EXCEPTION_GUARD_PAGE,
EXCEPTION_SET_THREAD_NAME
);
begin
for Result := Low(TExceptionCode) to High(TExceptionCode) do
if Value = ExceptionCodeData[Result] then
Break;
Result := ecUnknown;
end;
{ TDebuger }
function TDebuger.AddNewBreakPoint(var Value: TBreakpoint): LongBool;
var
Len: Integer;
begin
Result := not IsBreakpointPresent(Value);
if Result then
begin
Value.Active := True;
Len := BreakpointCount;
SetLength(FBreakpointList, Len + 1);
FBreakpointList[Len] := Value;
end;
end;
function TDebuger.AddThreadPointInfo(ThreadData: PThreadData; const PointType: TDbgPointType; DebugEvent: PDebugEvent = nil): LongBool;
var
Cur: UInt64;
//Prev: UInt64;
PrevTime: UInt64;
Delta: UInt64;
ThPoint: PThreadPoint;
begin
Result := False;
if ThreadData = Nil then Exit;
//Delta := 0;
//Prev := 0;
//Cur := 0;
case PointType of
ptStart:
Result := True;
ptStop:
Result := True;
ptException:
Result := True;
ptPerfomance:
begin
// Îòíîñèòåëüíîå âðåìÿ âûïîëíåíèÿ
ThreadData^.Elapsed := FProcessData.Elapsed - ThreadData^.Started;
// Ñîõðàíÿåì âðåìÿ CPU
PrevTime := ThreadData^.CPUTime;
ThreadData^.CPUTime := GetThreadCPUTime(ThreadData^.ThreadHandle);
Delta := ThreadData^.CPUTime - PrevTime;
// Ñ÷åò÷èê òàéìåðà CPU
Cur := _QueryThreadCycleTime(ThreadData^.ThreadHandle);
//Prev := ThreadData^.CPUElapsed;
ThreadData^.CPUElapsed := Cur;
// Äîáàâëÿåì èíôó, êîãäà ïîòîê àêòèâåí
Result := (Delta > (_QueryPerformanceFrequency div 10000)); // 0.1 msec èç 10 msec
end;
ptSyncObjsInfo:
Result := True;
ptTraceInfo:
Result := True;
end;
if Result then
begin
//ThreadData^.DbgPoints.BeginRead;
try
ThPoint := PThreadPoint(ThreadData^.DbgPoints.Add);
ThPoint^.PerfIdx := FProcessData.CurDbgPointIdx;
ThPoint^.PointType := PointType;
case PointType of
ptStart:
begin
ThreadData^.Started :=
FProcessData.Started + FProcessData.DbgPointByIdx(ThPoint^.PerfIdx)^.FromStart;
end;
ptStop:
begin
ThreadData^.Elapsed :=
(FProcessData.Started + FProcessData.DbgPointByIdx(ThPoint^.PerfIdx)^.FromStart) - ThreadData^.Started;
ThreadData^.CPUTime := GetThreadCPUTime(ThreadData^.ThreadHandle);
ThreadData^.CPUElapsed := _QueryThreadCycleTime(ThreadData^.ThreadHandle);
end;
ptException:
begin
ThPoint^.ExceptInfo := TExceptInfo.Create(DebugEvent);
ThreadData^.DbgExceptions.Add(ThPoint^.ExceptInfo);
FProcessData.DbgExceptions.Add(ThPoint^.ExceptInfo);
end;
ptPerfomance:
begin
ThPoint^.PerfInfo := Nil;
(* TODO:
ThPoint^.PerfInfo := TPerfInfo.Create;
ThPoint^.PerfInfo.DeltaTickCPU := Cur - Prev;
ThPoint^.PerfInfo.DeltaTime := Delta;
*)
end;
ptSyncObjsInfo:
begin
ThPoint^.SyncObjsInfo := TSyncObjsInfo.Create(DebugEvent, ThreadData, ThPoint^.PerfIdx);
end;
ptTraceInfo:
begin
if FDbgTraceState = dtsPause then
begin
ThPoint^.ExceptInfo := TExceptInfo.Create(ThreadData);
ThPoint^.ExceptInfo.ExceptionName := Format('### DBG_TRACE #%d', [FTraceCounter]);
ThreadData^.DbgExceptions.Add(ThPoint^.ExceptInfo);
FProcessData.DbgExceptions.Add(ThPoint^.ExceptInfo);
end;
end;
end;
finally
ThreadData^.DbgPoints.Commit;
//ThreadData^.DbgPoints.EndRead;
end;
end;
end;
function TDebuger.AddProcessPointInfo(const PointType: TDbgPointType): LongBool;
var
ProcPoint: PProcessPoint;
Cur: UInt64;
PCur: Int64;
PrevTime: UInt64;
CurTime: UInt64;
Delta: UInt64;
begin
Result := False;
PCur := _QueryPerformanceCounter;
CurTime := GetProcessCPUTime(FProcessData.AttachedProcessHandle);
Delta := 0;
case PointType of
ptStart, ptException, ptThreadInfo, ptTraceInfo {, ptMemoryInfo}:
begin
Result := True;
end;
ptStop:
begin
FProcessData.Elapsed := PCur;
FProcessData.CPUElapsed := _QueryProcessCycleTime(FProcessData.AttachedProcessHandle);
FProcessData.CPUTime := CurTime;
Result := True;
end;
ptPerfomance:
begin
// äåëüòà àáñîëþòíîãî âðåìåíè
FProcessData.Elapsed := PCur;
// äåëüòà ñ÷åò÷èêà òàéìåðà CPU
Cur := _QueryProcessCycleTime(FProcessData.AttachedProcessHandle);
FProcessData.CPUElapsed := Cur;
// Âðåìÿ CPU ïðîöåññà
PrevTime := FProcessData.CPUTime;
FProcessData.CPUTime := CurTime;
Delta := CurTime - PrevTime;
// Äîáàâëÿåì òîëüêî åñëè ïðîöåññ àêòèâåí
Result := (Delta > (_QueryPerformanceFrequency div 10000)); // 0.1 msec èç 10 msec
end;
end;
if Result then
begin
ProcPoint := FProcessData.DbgPoints.Add;
ProcPoint^.FromStart := PCur - FProcessData.Started;
ProcPoint^.CPUTime := CurTime;
ProcPoint^.PointType := PointType;
case PointType of
ptPerfomance:
begin
ProcPoint^.DeltaTime := Delta;
end;
end;
FProcessData.DbgPoints.Commit;
end;
end;
function TDebuger.AddThread(const ThreadID: TThreadId; ThreadHandle: THandle): PThreadData;
begin
Result := FThreadList.Add;
Result^.Init;
Result^.ThreadID := ThreadID;
Result^.State := tsActive;
Result^.ThreadHandle := ThreadHandle;
FActiveThreadList.AddOrSetValue(ThreadId, Result);
Result^.ThreadAdvInfo := SetThreadInfo(ThreadId);
Result^.ThreadAdvInfo^.ThreadData := Result;
FThreadList.Commit;
if AddProcessPointInfo(ptThreadInfo) then
AddThreadPointInfo(Result, ptStart);
end;
function TDebuger.AddThreadInfo(const ThreadId: TThreadId): PThreadAdvInfo;
begin
Result := FThreadAdvInfoList.Add;
Result^.ThreadId := ThreadId;
Result^.ThreadData := Nil;
FThreadAdvInfoList.Commit;
end;
function TDebuger.ProcAllocMem(const Size: Cardinal): Pointer;
begin
// TODO: Ïðîâåðèòü âûäåëåíèå ïàìÿòè äëÿ ìàëåíüêèõ Size
Result := VirtualAllocEx(FProcessData.AttachedProcessHandle, Nil, Size, MEM_COMMIT Or MEM_RESERVE, PAGE_EXECUTE_READWRITE);
If Result = nil Then
RaiseLastOsError;
end;
function TDebuger.AttachToProcess(const ProcessID: TProcessId; SentEntryPointBreakPoint: LongBool): LongBool;
begin
LoadLibrary('DbgHook32.dll'); // Äëÿ áûñòðîé çàãðóçêè â ïðîöåññå
Result := False;
if FProcessData.State = psActive then
Exit;
FSetEntryPointBreakPoint := SentEntryPointBreakPoint;
FProcessData.ProcessID := ProcessID;
Result := DebugActiveProcess(Cardinal(ProcessID));
end;
function TDebuger.BreakpointCount: Integer;
begin
Result := Length(FBreakpointList);
end;
function TDebuger.BreakpointItem(Index: Integer): TBreakpoint;
begin
CheckBreakpointIndex(Index);
Result := FBreakpointList[Index];
end;
procedure TDebuger.CallUnhandledBreakPointEvents(const Code: TExceptionCode; DebugEvent: PDebugEvent);
begin
//ContinueStatus := DBG_EXCEPTION_NOT_HANDLED;
if Assigned(FExceptionEvents[Code]) then
FExceptionEvents[Code](Self, DebugEvent^.dwThreadId, @DebugEvent^.Exception.ExceptionRecord);
end;
procedure TDebuger.CallUnhandledExceptionEvents(const Code: TExceptionCode; DebugEvent: PDebugEvent);
var
IsTraceException: LongBool;
begin
if gvDebugInfo.CheckDebugException(@DebugEvent^.Exception.ExceptionRecord, IsTraceException) then
begin
if IsTraceException then
begin
// TODO:
end;
ContinueStatus := DBG_CONTINUE;
end
else
begin
if DebugEvent^.Exception.dwFirstChance = 1 then
begin
ContinueStatus := DBG_EXCEPTION_NOT_HANDLED;
if AddProcessPointInfo(ptException) then
AddThreadPointInfo(CurThreadData, ptException, DebugEvent);
if Assigned(FExceptionEvents[Code]) then
FExceptionEvents[Code](Self, DebugEvent^.dwThreadId, @DebugEvent^.Exception.ExceptionRecord);
end
else
ContinueStatus := DBG_CONTINUE;
end;
end;
procedure TDebuger.CheckBreakpointIndex(Value: Integer);
begin
if (Value < 0) or (Value >= BreakpointCount) then
raise EDebugCoreException.CreateFmt(SListIndexError, [Value]);
end;
function TDebuger.CheckIsAddrInRealMemoryBPRegion(BreakPointIndex: Integer; AAddr: Pointer): LongBool;
begin
CheckBreakpointIndex(BreakPointIndex);
Result := Cardinal(AAddr) >= Cardinal(FBreakpointList[BreakPointIndex].Memory.Address);
if Result then
Result := Cardinal(AAddr) < Cardinal(FBreakpointList[BreakPointIndex].Memory.Address) + FBreakpointList[BreakPointIndex].Memory.Size;
end;
procedure TDebuger.ClearDbgInfo;
var
I: Integer;
ThData: PThreadData;
begin
DbgState := dsNone;
FDbgMemoryProfiler.Clear;
FDbgSyncObjsProfiler.Clear;
FDbgSamplingProfiler.Clear;
FDbgCodeProfiler.Clear;
FProcessData.Clear;
try
FActiveThreadList.Clear;
FThreadList.BeginWrite;
try
for I := 0 to FThreadList.Count - 1 do
begin
ThData := FThreadList[I];
ThData.Clear;
end;
finally
FThreadList.Clear;
FThreadList.EndWrite;
end;
finally
FThreadAdvInfoList.Clear;
FTraceCounter := 0;
end;
end;
function TDebuger.ContinueDebug: LongBool;
begin
Result := False;
if DbgTraceState = dtsPause then
begin
DbgTraceState := dtsContinue;
FTraceEvent.SetEvent;
Result := True;
end;
end;
constructor TDebuger.Create();
function SetDebugPriv: LongBool;
var
Token: THandle;
tkp: TTokenPrivileges;
begin
Result := False;
if OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, Token) then
begin
if LookupPrivilegeValue(nil, PChar('SeDebugPrivilege'), tkp.Privileges[0].Luid) then
begin
tkp.PrivilegeCount := 1;
tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
Result := AdjustTokenPrivileges(Token, False, tkp, 0, PTokenPrivileges(nil)^, PCardinal(nil)^);
end;
end;
end;
begin
inherited Create;
if not SetDebugPriv then
RaiseLastOSError;
FDbgState := dsNone;
FDbgTraceState := dtsContinue;
FTraceEvent := TEvent.Create(nil, True, False, '');
FRestoreBPIndex := -1;
FRestoreMBPIndex := -1;
FRestoredHWBPIndex := -1;
FRestoredThread := 0;
FCloseDebugProcess := True;
FSetEntryPointBreakPoint := False;
FDbgLogMode := False;
FMemoryBPCheckMode := False;
FThreadList := TCollectList<TThreadData>.Create;
FThreadAdvInfoList := TCollectList<TThreadAdvInfo>.Create;
FActiveThreadList := TDbgActiveThreadList.Create(512, True);
FProcessData := TProcessData.Create;
FPerfomanceMode := False;
FPerfomanceCheckPtr := Nil; //Pointer($76FED315);
FDbgSamplingProfiler := TDbgSamplingProfiler.Create;
FDbgMemoryProfiler := TDbgMemoryProfiler.Create;
FDbgSyncObjsProfiler := TDbgSyncObjsProfiler.Create;
FDbgCodeProfiler := TDbgCodeProfiler.Create;
end;
function TDebuger.CurThreadData: PThreadData;
begin
if FCurThreadData = Nil then
UpdateCurThreadContext;
Result := FCurThreadData;
end;
function TDebuger.CurThreadId: TThreadId;
begin
Result := FCurThreadId;
end;
function TDebuger.DebugNewProcess(const AppPath: string; var ErrInfo: String; const RunParams: String = ''; const WorkingDirectory: String = ''): LongBool;
var
PI: PProcessInformation;
SI: PStartupInfo;
CmdLine: String;
PCmdLine: PChar;
PAppName: PChar;
PWorkDir: PChar;
begin
LoadLibrary('DbgHook32.dll'); // Äëÿ áûñòðîé çàãðóçêè â ïðîöåññå
Result := False;
if FProcessData.State = psActive then
Exit;
//FSetEntryPointBreakPoint := SentEntryPointBreakPoint;
FSetEntryPointBreakPoint := False;
PI := AllocMem(SizeOf(TProcessInformation));
SI := AllocMem(SizeOf(TStartupInfo));
try
SI.cb := SizeOf(TStartupInfo);
SI.dwFlags := STARTF_USESHOWWINDOW;
SI.wShowWindow := SW_SHOWNORMAL;
PAppName := nil;
PCmdLine := nil;
PWorkDir := nil;
if RunParams <> '' then
begin
CmdLine := Format('"%s" %s', [AppPath, RunParams]);
PCmdLine := PChar(CmdLine);
end
else
PAppName := PChar(AppPath);
if (WorkingDirectory <> '') and (DirectoryExists(WorkingDirectory)) then
PWorkDir := PChar(WorkingDirectory);
Result := CreateProcess(PAppName, PCmdLine, nil, nil, False, DEBUG_PROCESS or DEBUG_ONLY_THIS_PROCESS, nil,
PWorkDir, SI^, PI^);
if Result then
begin
FProcessData.ProcessID := TProcessId(PI.dwProcessId);
FProcessData.CreatedProcessHandle := PI.hProcess;
FProcessData.CreatedThreadHandle := PI.hThread;
end
else
ErrInfo := SysErrorMessage(GetLastError);
finally
FreeMemory(PI);
FreeMemory(SI);
end;
end;
destructor TDebuger.Destroy;
begin
StopDebug;
ClearDbgInfo;
FreeAndNil(FActiveThreadList);
FreeAndNil(FThreadList);
FreeAndNil(FThreadAdvInfoList);
FreeAndNil(FProcessData);
FreeAndNil(FTraceEvent);
FreeAndNil(FDbgMemoryProfiler);
FreeAndNil(FDbgSyncObjsProfiler);
FreeAndNil(FDbgSamplingProfiler);
FreeAndNil(FDbgCodeProfiler);
inherited;
end;
procedure TDebuger.DoCreateProcess(DebugEvent: PDebugEvent);
var
CreateThreadInfo: PCreateThreadDebugInfo;
begin
DbgState := dsStarted;
FProcessData.State := psActive;
// Ñîõðàíÿåì äàííûå î ïðîöåññå
FProcessData.AttachedFileHandle := DebugEvent^.CreateProcessInfo.hFile;
FProcessData.AttachedProcessHandle := DebugEvent^.CreateProcessInfo.hProcess;
FProcessData.AttachedThreadHandle := DebugEvent^.CreateProcessInfo.hThread;
FProcessData.StartAddress := DebugEvent^.CreateProcessInfo.lpStartAddress;
FProcessData.BaseOfImage := DebugEvent^.CreateProcessInfo.lpBaseOfImage;
FProcessData.MainThreadID := DebugEvent^.dwThreadId;
FProcessData.Started := _QueryPerformanceCounter;
FProcessData.DbgPoints := TCollectList<TProcessPoint>.Create;
FProcessData.DbgGetMemInfo := TGetMemInfoList.Create(1024, True);
FProcessData.DbgGetMemInfo.OwnsValues := True;
FProcessData.ProcessGetMemCount := 0;
FProcessData.ProcessGetMemSize := 0;
FProcessData.DbgExceptions.Clear;
FProcessData.DbgTrackEventCount := 0;
FProcessData.DbgTrackUnitList := TCodeTrackUnitInfoList.Create(4096);
FProcessData.DbgTrackUnitList.OwnsValues := True;
FProcessData.DbgTrackFuncList := TCodeTrackFuncInfoList.Create(4096);
FProcessData.DbgTrackFuncList.OwnsValues := True;
FProcessData.DbgTrackUsedUnitList := TTrackUnitInfoList.Create(64);
FProcessData.DbgTrackUsedUnitList.OwnsKeys := False;
FProcessData.DbgTrackUsedUnitList.OwnsValues := False;
//DbgTrackBreakpoints := nil;
//DbgTrackRETBreakpoints := nil;
// Ìåòêà ñòàðòà ïðîöåññà
AddProcessPointInfo(ptStart);
// Èíèöèàëèçàöèÿ õóêîâ
//LoadLibrary('DbgHook32.dll'); // ??? Áëîêèðîâêà îò ïðåæäåâðåìåííîé âûãðóçêè
if Assigned(gvDebugInfo) then
gvDebugInfo.InitDebugHook;
// Óñòàíàâëèâàåì BreakPoint íà òî÷êó âõîäà ïðîöåññà
if FSetEntryPointBreakPoint then
SetUserBreakpoint(FProcessData.StartAddress, 0, 'Process Entry Point Breakpoint');
if Assigned(FCreateProcess) then
FCreateProcess(Self, DebugEvent^.dwProcessId, @DebugEvent^.CreateProcessInfo);
AddThread(DebugEvent^.dwThreadId, FProcessData.AttachedThreadHandle);
with SetThreadInfo(DebugEvent^.dwThreadId)^ do
begin
ThreadName := 'Main thread';
ThreadAdvType := tatNormal;
end;
if Assigned(FCreateThread) then
begin
CreateThreadInfo := AllocMem(SizeOf(TCreateThreadDebugInfo));
try
CreateThreadInfo.hThread := FProcessData.AttachedThreadHandle;
FCreateThread(Self, DebugEvent^.dwThreadId, CreateThreadInfo);
finally
FreeMemory(CreateThreadInfo);
end;
end;
// Çàïóñê ïîòîêà ïî îáðàáîòêå ñòåêîâ
if CodeTracking and SamplingMethod then
DbgSamplingProfiler.InitSamplingTimer;
TDbgWorkerThread.Init;
DoResumeAction(DebugEvent^.dwThreadId);
end;
procedure TDebuger.DoCreateThread(DebugEvent: PDebugEvent);
begin
AddThread(DebugEvent^.dwThreadId, DebugEvent^.CreateThread.hThread);
if Assigned(FCreateThread) then
FCreateThread(Self, DebugEvent^.dwThreadId, @DebugEvent^.CreateThread);
end;
procedure TDebuger.DoDebugString(DebugEvent: PDebugEvent);
begin
if Assigned(FDebugString) then
FDebugString(Self, DebugEvent.dwThreadId, @DebugEvent^.DebugString);
end;
procedure TDebuger.DoExitProcess(DebugEvent: PDebugEvent);
begin
DbgSamplingProfiler.ResetSamplingTimer;
TDbgWorkerThread.Reset;
DbgState := dsStoping;
FProcessData.State := psFinished;
// Ìåòêà çàâåðøåíèÿ ïðîöåññà
AddProcessPointInfo(ptStop);
// Óäàëÿåì ãëàâíûé ïîòîê
if Assigned(FExitThread) then
FExitThread(Self, FProcessData.MainThreadID, nil);
RemoveThread(FProcessData.MainThreadID);
if Assigned(FExitProcess) then
FExitProcess(Self, FProcessData.ProcessID, @DebugEvent^.ExitProcess);
if FProcessData.AttachedFileHandle <> 0 then
begin
CloseHandle(FProcessData.AttachedFileHandle);
FProcessData.AttachedFileHandle := 0;
end;
//FreeLibrary('DbgHook32.dll');
end;
procedure TDebuger.DoExitThread(DebugEvent: PDebugEvent);
begin
if FPerfomanceMode and (DebugEvent^.ExitThread.dwExitCode = Cardinal(@_DbgPerfomanceHook)) then
Exit;
if Assigned(FExitThread) then
FExitThread(Self, DebugEvent^.dwThreadId, @DebugEvent^.ExitThread);
RemoveThread(DebugEvent^.dwThreadId);