-
Notifications
You must be signed in to change notification settings - Fork 3
/
DDetours.pas
2853 lines (2611 loc) · 76.1 KB
/
DDetours.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
// **************************************************************************************************
// Delphi Detours Library.
// Unit DDetours
// https://github.com/MahdiSafsafi/DDetours
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License, v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at
// https://mozilla.org/MPL/2.0/.
// **************************************************************************************************
//
// Contributors:
// - David Millington : Added TDetours<T> class.
// **************************************************************************************************
unit DDetours;
{define FIX_MADEXCEPT if you are using crash on buffer overrun/underrun feature from MadExcept }
{.$DEFINE FIX_MADEXCEPT}
{.$define DEVMODE}
{$IFDEF FPC}
{$MODE DELPHI}
{$HINTS OFF}
{$WARN 4045 OFF}
{$WARN 4055 OFF}
{$WARN 4056 OFF}
{$WARN 4082 OFF}
{$WARN 5024 OFF}
{$WARN 5028 OFF}
{$WARN 5057 OFF}
{$WARN 5058 OFF}
{$ENDIF FPC}
interface
{$I DDetoursDefs.inc}
uses
{$IFDEF RENAMED_NAMESPACE}
System.SysUtils,
System.Classes,
WinApi.Windows,
WinApi.TLHelp32,
{$IFNDEF SUPPORTS_MONITOR}
System.SyncObjs,
{$ENDIF SUPPORTS_MONITOR}
{$ELSE !RENAMED_NAMESPACE}
SysUtils,
Windows,
Classes,
{$IFNDEF SUPPORTS_MONITOR}
SyncObjs,
{$ENDIF SUPPORTS_MONITOR}
{$IFNDEF FPC}
TLHelp32,
{$ENDIF FPC}
{$ENDIF RENAMED_NAMESPACE}
{$IFDEF SUPPORTS_RTTI}
System.Generics.Collections,
System.Typinfo, System.RTTI,
{$ENDIF SUPPORTS_RTTI}
LegacyTypes,
CPUID,
InstDecode;
type
InterceptException = Exception;
TTransactionOption = (toSuspendThread);
TTransactionOptions = set of TTransactionOption;
TInterceptOption = (ioForceLoad, ioRecursive);
TInterceptOptions = set of TInterceptOption;
const
{ Maximum allowed number of hooks. }
MAX_HOOKS = 7;
DefaultInterceptOptions = [];
SErrorInvalidTType = '<T> must be a method';
{ ========================================= DDetours Interface ========================================= }
function InterceptCreate(const TargetProc, InterceptProc: Pointer; const Param: Pointer = nil; const Options: TInterceptOptions = DefaultInterceptOptions)
: Pointer; overload;
function InterceptCreate(const TargetInterface; MethodIndex: Integer; const InterceptProc: Pointer; const Param: Pointer = nil;
const Options: TInterceptOptions = DefaultInterceptOptions): Pointer; overload;
function InterceptCreate(const Module, MethodName: String; const InterceptProc: Pointer; const Param: Pointer = nil;
const Options: TInterceptOptions = DefaultInterceptOptions): Pointer; overload;
procedure InterceptCreate(const TargetProc, InterceptProc: Pointer; var TrampoLine: Pointer; const Param: Pointer = nil;
const Options: TInterceptOptions = DefaultInterceptOptions); overload;
{$IFDEF SUPPORTS_RTTI}
function InterceptCreate(const TargetInterface; const MethodName: String; const InterceptProc: Pointer; const Param: Pointer = nil;
const Options: TInterceptOptions = DefaultInterceptOptions): Pointer; overload;
{$ENDIF SUPPORTS_RTTI}
function InterceptRemove(const TrampoLine: Pointer): Integer; overload;
function GetHookCount(const TargetProc: Pointer): Integer; overload;
function GetHookCount(const TargetInterface; MethodIndex: Integer): Integer; overload;
{$IFDEF SUPPORTS_RTTI}
function GetHookCount(const TargetInterface; const MethodName: String): Integer; overload;
{$ENDIF SUPPORTS_RTTI}
function IsHooked(const TargetProc: Pointer): Boolean; overload;
function IsHooked(const TargetInterface; MethodIndex: Integer): Boolean; overload;
{$IFDEF SUPPORTS_RTTI}
function IsHooked(const TargetInterface; const MethodName: String): Boolean; overload;
{$ENDIF SUPPORTS_RTTI}
function PatchVt(const TargetInterface; MethodIndex: Integer; InterceptProc: Pointer): Pointer;
function UnPatchVt(const TrampoLine: Pointer): Boolean;
function BeginTransaction(Options: TTransactionOptions = [toSuspendThread]): THandle;
function EndTransaction(Handle: THandle): Boolean;
function EnterRecursiveSection(var TrampoLine; MaxRecursionLevel: NativeInt = 0): Boolean;
function ExitRecursiveSection(var TrampoLine): Boolean;
function GetCreatorThreadIdFromTrampoline(var TrampoLine): TThreadId;
function GetTrampolineParam(var TrampoLine): Pointer;
{$IFDEF SUPPORTS_GENERICS}
type
IIntercept<T, U> = interface(IInterface)
['{EECBF3C2-3938-4923-835A-B0A6AD27744D}']
function GetTrampoline(): T;
function GetParam(): U;
function GetCreatorThreadId(): TThreadId;
function GetInterceptOptions(): TInterceptOptions;
function EnterRecursive(MaxRecursionLevel: NativeInt = 0): Boolean;
function ExitRecursive(): Boolean;
property NextHook: T read GetTrampoline;
property TrampoLine: T read GetTrampoline; // alias to NextHook
property Param: U read GetParam;
property CreatorThreadId: TThreadId read GetCreatorThreadId;
property InterceptOptions: TInterceptOptions read GetInterceptOptions;
end;
{
Based on David Millington's original implementation TDetours<T>.
}
TIntercept<T, U> = class(TInterfacedObject, IIntercept<T, U>)
private
FNextHook: T;
FTrampolinePtr: Pointer;
FParam: U;
FCreatorThreadId: TThreadId;
FInterceptOptions: TInterceptOptions;
function TToPointer(const A): Pointer;
function PointerToT(const P): T;
function EnsureTIsMethod(): Boolean;
public
function GetTrampoline(): T;
function GetParam(): U;
function GetCreatorThreadId(): TThreadId;
function GetInterceptOptions(): TInterceptOptions;
function EnterRecursive(MaxRecursionLevel: NativeInt = 0): Boolean;
function ExitRecursive(): Boolean;
constructor Create(const TargetProc, InterceptProc: T; const AParam: U; const AInterceptOptions: TInterceptOptions = DefaultInterceptOptions); virtual;
destructor Destroy(); override;
property Param: U read FParam;
property NextHook: T read FNextHook;
property TrampoLine: T read FNextHook; // alias to NextHook
property CreatorThreadId: TThreadId read FCreatorThreadId;
property InterceptOptions: TInterceptOptions read FInterceptOptions;
end;
TIntercept<T> = class(TIntercept<T, Pointer>)
public
constructor Create(const TargetProc, InterceptProc: T; const AParam: Pointer = nil;
const AInterceptOptions: TInterceptOptions = DefaultInterceptOptions); override;
end;
{$ENDIF SUPPORTS_GENERICS}
type
DetourException = Exception;
implementation
const
{ Nops }
Nop9: array [0 .. 8] of Byte = ($66, $0F, $1F, $84, $00, $00, $00, $00, $00);
Nop8: array [0 .. 7] of Byte = ($0F, $1F, $84, $00, $00, $00, $00, $00);
Nop7: array [0 .. 6] of Byte = ($0F, $1F, $80, $00, $00, $00, $00);
Nop6: array [0 .. 5] of Byte = ($66, $0F, $1F, $44, $00, $00);
Nop5: array [0 .. 4] of Byte = ($0F, $1F, $44, $00, $00);
Nop4: array [0 .. 3] of Byte = ($0F, $1F, $40, $00);
Nop3: array [0 .. 2] of Byte = ($0F, $1F, $00);
Nop2: array [0 .. 1] of Byte = ($66, $90);
Nop1: array [0 .. 0] of Byte = ($90);
MultiNops: array [0 .. 8] of PByte = ( //
@Nop1, { Standard Nop }
@Nop2, { 2 Bytes Nop }
@Nop3, { 3 Bytes Nop }
@Nop4, { 4 Bytes Nop }
@Nop5, { 5 Bytes Nop }
@Nop6, { 6 Bytes Nop }
@Nop7, { 7 Bytes Nop }
@Nop8, { 8 Bytes Nop }
@Nop9 { 9 Bytes Nop }
);
{ Arithmetic operands }
arNone = $00;
arPlus = $08;
arMin = $10;
arAdd = arPlus or $01;
arSub = arMin or $01;
arInc = arPlus or $02;
arDec = arMin or $02;
{ Instructions OpCodes }
opJmpRelz = $E9;
opJmpRelb = $EB;
opJmpMem = $25FF;
opTestb = $85;
opPrfOpSize = $66;
opPrfAddrSize = $67;
opNop = $90;
{ thread constants }
THREAD_SUSPEND_RESUME = $0002;
{ Error messages }
SErrorSmallFunctionSize = 'Size of function is too small, risk to override others adjacent functions.';
SErrorInvalidJmp = 'Invalid JMP Type.';
SErrorInvalidJmp64 = 'Invalid JMP Type for x64.';
SErrorInvalidJmp32 = 'Invalid JMP Type for x32.';
SErrorInvalidDstSave = 'Invalid DstSave Address pointer.';
SErrorUnsupportedMultiNop = 'Multi Bytes Nop Instructions not supported by your CPU.';
SErrorRipDisp = 'Failed to correcr RIP Displacement.';
SErrorBigTrampoSize = 'Exceed maximum TrampoSize.';
SErrorMaxHook = 'Exceed maximum allowed of hooks.';
SErrorInvalidTargetProc = 'Invalid TargetProc Pointer.';
SErrorInvalidInterceptProc = 'Invalid InterceptProc Pointer.';
SErrorInvalidDescriptor = 'Invalid Descriptor.';
SErrorInvalidTrampoline = 'Invalid TrampoLine Pointer.';
SErrorBeginUnHook = 'BeginUnHooks must be called outside BeginHooks/EndHooks.';
SErrorRecursiveSectionUnsupported = 'Trampoline was not marked to use recursive section.';
SErrorTlsOutOfIndexes = 'Tls out of indexes.';
{ JMP Type }
JT_NONE = 0;
JT_REL8 = 1;
JT_REL16 = 2;
JT_REL32 = 3;
JT_MEM16 = 4;
JT_MEM32 = 5;
JT_MEM64 = 6;
JT_RIPZ = 7;
{$IFDEF CPUX64}
JT_MEMN = JT_MEM64;
{$ELSE !CPUX64}
JT_MEMN = JT_MEM32;
{$ENDIF CPUX64}
{ Jmp Type To Size }
JmpTypeToSize: array [0 .. 7] of Byte = ( //
0, { None }
2, { JT_REL8 = $EB + Rel8 }
4, { JT_REL16 = OpSizePrf + $E9 + Rel16 }
5, { JT_REL32 = $E9 + Rel32 }
7, { JT_MEM16 = OpSizePrf + $FF /4 + Disp32 }
6, { JT_MEM32 = $FF /4 + Disp32 }
6, { JT_MEM64 = $FF /4 + Disp32 }
14 { JT_RIPZ = $FF /4 + Disp32 + DQ }
);
SizeToJmpType: array [0 .. 4] of Byte = ( //
{$IFDEF CPUX86}
JT_REL8, { db }
JT_REL16, { dw }
JT_REL32, { dd }
JT_MEM32, { dd }
JT_MEM32 { dd }
{$ELSE !CPUX86}
JT_REL8, { db }
JT_REL32, { dw }
JT_REL32, { dd }
JT_MEM64, { dq }
JT_MEM64 { dq }
{$ENDIF CPUX86}
);
DscrSigSize = $08;
TmpSize = 32;
TrampolineSignature = $544C544C;
type
TArrayOfThreadId = array [0 .. HIGH(SmallInt) - 1] of DWORD;
PArrayOfThreadId = ^TArrayOfThreadId;
TTransactionStruct = record
Options: TTransactionOptions;
TID: DWORD;
PID: DWORD;
ThreadPriority: Integer;
SuspendedThreadCount: Integer;
SuspendedThreads: PArrayOfThreadId;
end;
PTransactionStruct = ^TTransactionStruct;
TOpenThread = function(dwDesiredAccess: DWORD; bInheritHandle: BOOL; dwThreadId: DWORD): THandle; stdcall;
TDscrSig = array [0 .. DscrSigSize - 1] of Byte;
TVirtualProtect = function(lpAddress: Pointer; dwSize: SIZE_T; flNewProtect: DWORD; var OldProtect: DWORD): BOOL; stdcall;
TVirtualAlloc = function(lpvAddress: Pointer; dwSize: SIZE_T; flAllocationType, flProtect: DWORD): Pointer; stdcall;
TVirtualQuery = function(lpAddress: Pointer; var lpBuffer: TMemoryBasicInformation; dwLength: SIZE_T): SIZE_T; stdcall;
TFlushInstructionCache = function(hProcess: THandle; const lpBaseAddress: Pointer; dwSize: SIZE_T): BOOL; stdcall;
TGetCurrentProcess = function: THandle; stdcall;
TVirtualFree = function(lpAddress: Pointer; dwSize: SIZE_T; dwFreeType: DWORD): BOOL; stdcall;
{ TEnumThreadCallBack for EnumProcessThreads }
TEnumThreadCallBack = function(ID: DWORD; Param: Pointer): Boolean;
TInternalFuncs = record
VirtualAlloc: TVirtualAlloc;
VirtualFree: TVirtualFree;
VirtualProtect: TVirtualProtect;
VirtualQuery: TVirtualQuery;
FlushInstructionCache: TFlushInstructionCache;
GetCurrentProcess: TGetCurrentProcess;
end;
TTrampoInfo = record
Addr: PByte; // Pointer to first trampoline instruction .
Size: Byte; // Stolen bytes size .
PData: PByte; // Original Stolen bytes.
end;
PTrampoInfo = ^TTrampoInfo;
TJmpMem = packed record
OpCode: WORD; // $0F$25
Disp32: Integer;
end;
PJmpMem = ^TJmpMem;
TDescriptor = packed record
Sig: TDscrSig; { Table signature. }
DscrAddr: PByte; { Pointer that hold jmp address (if Used)! }
nHook: Byte; { Number of hooks . }
Flags: Byte; { Reserved for future use! }
ExMem: PByte; { Reserved for jmp (if used) & for Trampoline ! }
OrgPtr: PByte; { Original Target Proc address. }
Trampo: PTrampoInfo; { Pointer to TrampoInfo struct. }
{ Array that hold jmp destination address. }
JmpAddrs: array [0 .. MAX_HOOKS] of PByte;
{
Mark the beginning of descriptor code executing .
==> Must be NOP .
}
CodeEntry: Byte;
{ Jmp Instruction for NextHook call and Trampoline call ! }
JmpMems: array [0 .. MAX_HOOKS] of TJmpMem;
end;
PDescriptor = ^TDescriptor;
TNextHook = packed record
ID: Byte; { Hook ID . }
PDscr: PDescriptor;
Signature: Cardinal;
threadid: TThreadId;
Param: Pointer;
TlsRecursionLevelIndex: DWORD;
InterceptOptions: TInterceptOptions;
end;
PNextHook = ^TNextHook;
TTrampoDataVt = record
vAddr: Pointer;
Addr: Pointer;
end;
PTrampoDataVt = ^TTrampoDataVt;
const
TrampoSize = SizeOf(TNextHook) + 64;
{ Descriptor Signature }
{$IFDEF CPUX64}
DscrSig: TDscrSig = ( //
$90, { NOP }
$40, { REX }
$40, { REX }
$40, { REX }
$0F, { ESCAPE TWO BYTE }
$1F, { HINT_NOP }
$F3, { PRF }
$F3 { PRF }
);
{$ELSE !CPUX64}
DscrSig: TDscrSig = ( //
$90, { NOP }
$40, { INC EAX }
$48, { DEC EAX }
$90, { NOP }
$0F, { ESCAPE TWO BYTE }
$1F, { HINT_NOP }
$F3, { PRF }
$F3 { PRF }
);
{$ENDIF CPUX64}
{$IFDEF FPC}
{$I 'TlHelp32.inc'}
{$ENDIF FPC}
var
OpenThread: TOpenThread = nil;
{$IFDEF FPC}
CreateToolhelp32Snapshot: TCreateToolhelp32Snapshot = nil;
Thread32First: TThread32First = nil;
Thread32Next: TThread32Next = nil;
{$ENDIF FPC}
hKernel: THandle;
OpenThreadExist: Boolean = False;
FreeKernel: Boolean = False;
SizeOfAlloc: DWORD = 0; // See initialization !
SysInfo: TSystemInfo;
InternalFuncs: TInternalFuncs;
{$IFDEF SUPPORTS_MONITOR}
FLock: TObject = nil;
{$ELSE !SUPPORTS_MONITOR}
FLock: TCriticalSection = nil;
{$ENDIF SUPPORTS_MONITOR }
{ ================================== Utils ================================== }
function GetUInt64Size(const Value: UInt64): Integer; {$IFDEF SUPPORTS_INLINE}inline; {$ENDIF SUPPORTS_INLINE}
begin
if UInt8(Value) = Value then
Result := 1
else if UInt16(Value) = Value then
Result := 2
else if UInt32(Value) = Value then
Result := 4
else
Result := 8;
end;
function GetInt64Size(const Value: Int64): Integer; {$IFDEF SUPPORTS_INLINE}inline; {$ENDIF SUPPORTS_INLINE}
begin
if Int8(Value) = Value then
Result := 1
else if Int16(Value) = Value then
Result := 2
else if Int32(Value) = Value then
Result := 4
else
Result := 8;
end;
procedure EnterLook(LockedObject: TObject); {$IFDEF SUPPORTS_INLINE}inline; {$ENDIF SUPPORTS_INLINE}
begin
{$IFDEF SUPPORTS_MONITOR}
TMonitor.Enter(LockedObject);
{$ELSE !SUPPORTS_MONITOR}
TCriticalSection(LockedObject).Enter();
{$ENDIF SUPPORTS_MONITOR}
end;
procedure LeaveLook(LockedObject: TObject); {$IFDEF SUPPORTS_INLINE}inline; {$ENDIF SUPPORTS_INLINE}
begin
{$IFDEF SUPPORTS_MONITOR}
TMonitor.Exit(LockedObject);
{$ELSE !SUPPORTS_MONITOR}
TCriticalSection(LockedObject).Leave();
{$ENDIF SUPPORTS_MONITOR}
end;
function EnumProcessThreads(PID: DWORD; CallBack: TEnumThreadCallBack; Param: Pointer): BOOL;
var
hSnap: THandle;
te: TThreadEntry32;
Next: Boolean;
begin
hSnap := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, PID);
Result := hSnap <> INVALID_HANDLE_VALUE;
if Result then
begin
te.dwSize := SizeOf(TThreadEntry32);
Next := Thread32First(hSnap, te);
while Next do
begin
if (te.th32OwnerProcessID = PID) then
begin
try
if not CallBack(te.th32ThreadID, Param) then
break;
except
end;
end;
Next := Thread32Next(hSnap, te);
end;
Result := CloseHandle(hSnap);
end;
end;
function SetMemPermission(const P: Pointer; const Size: SIZE_T; const NewProtect: DWORD): DWORD;
const
PAGE_EXECUTE_FLAGS = PAGE_EXECUTE or PAGE_EXECUTE_READ or PAGE_EXECUTE_READWRITE or PAGE_EXECUTE_WRITECOPY;
begin
Result := 0;
if Assigned(P) and (Size > 0) and (NewProtect > 0) then
begin
if InternalFuncs.VirtualProtect(P, Size, NewProtect, Result) then
if (NewProtect and PAGE_EXECUTE_FLAGS <> 0) then
{
If the protected region will be executed
=> We need to update the cpu cache !
}
InternalFuncs.FlushInstructionCache(InternalFuncs.GetCurrentProcess(), P, Size);
end;
end;
function GetDispDataSize(PInst: PInstruction): Integer;
begin
Result := 0;
if PInst^.Disp.Flags and dfUsed <> 0 then
begin
if PInst^.Archi = CPUX32 then
begin
if PInst^.Prefixes and Prf_OpSize <> 0 then
Result := ops16bits
else
Result := ops32bits;
Exit;
end
else
begin
case PInst^.OperandFlags of
opdD64:
begin
{
Defaults to O64 in PM64.
PrfOpSize results in O16.
}
if PInst^.Prefixes and Prf_OpSize <> 0 then
Result := ops16bits
else
Result := ops64bits;
end;
opdF64, opdDv64:
begin
{ The operand size is forced to a 64-bit operand size in PM64 ! }
Result := (ops64bits);
Exit;
end;
opdDf64:
begin
{
Defaults to O64 in PM64.
PrfOpSize results in O16 in AMD64.
PrfOpSize is ignored in EM64T.
}
if (CPUVendor = vAMD) and (PInst^.Prefixes and Prf_OpSize <> 0) then
Result := (ops16bits)
else
Result := (ops64bits);
Exit;
end;
else
begin
if PInst^.Rex.W then
Result := (ops64bits)
else if (PInst^.Prefixes and Prf_OpSize <> 0) then
Result := (ops16bits)
else
Result := (ops32bits);
Exit;
end;
end;
end;
end;
end;
function fDecodeInst(PInst: PInstruction): Integer;
var
IsNxtInstData: Boolean;
begin
{ Include VEX decoding if the cpu support it! }
if (VEX in CPUEncoding) then
PInst.Options := DecodeVex;
Result := DecodeInst(PInst);
{$IFDEF CPUX64}
IsNxtInstData := ((PInst^.Disp.Flags and (dfUsed or dfRip) = (dfUsed or dfRip)) and (PInst^.Disp.Value = 0));
{$ELSE !CPUX64}
IsNxtInstData := (PInst^.Disp.Value = Int64(PInst^.NextInst));
{$ENDIF CPUX64}
if IsNxtInstData then
begin
{
Check if the Next Instruction is data !
If so , That's mean it's not a valid instruction .
We must skip this data ..
otherwise , disassembling next instructions will fail !
}
Inc(Result, GetDispDataSize(PInst));
PInst^.InstSize := Result;
end;
end;
function RoundMultipleOf(const Value, MultipleOf: NativeInt): NativeInt; {$IFDEF SUPPORTS_INLINE}inline; {$ENDIF SUPPORTS_INLINE}
begin
if Value = 0 then
begin
Result := (MultipleOf);
Exit;
end;
Result := ((Value + (MultipleOf - 1)) and not(MultipleOf - 1));
end;
function AllocMemAt(const Addr: Pointer; const MemSize, flProtect: DWORD): Pointer;
var
mbi: TMemoryBasicInformation;
SysInfo: TSystemInfo;
pBase: PByte;
P: PByte;
Q: PByte;
pMax, pMin: PByte;
dwAllocGran: DWORD;
begin
{ Alloc memory on the specific nearest address from the Addr . }
Result := nil;
P := PByte(Addr);
if not Assigned(P) then
begin
Result := InternalFuncs.VirtualAlloc(nil, MemSize, MEM_RESERVE or MEM_COMMIT, flProtect);
Exit;
end;
GetSystemInfo(SysInfo);
pMin := SysInfo.lpMinimumApplicationAddress;
pMax := SysInfo.lpMaximumApplicationAddress;
dwAllocGran := SysInfo.dwAllocationGranularity;
if (NativeUInt(P) < NativeUInt(pMin)) or (NativeUInt(P) > NativeUInt(pMax)) then
Exit;
if InternalFuncs.VirtualQuery(P, mbi, SizeOf(mbi)) = 0 then
Exit;
pBase := mbi.BaseAddress;
Q := pBase;
while NativeUInt(Q) < NativeUInt(pMax) do
begin
if InternalFuncs.VirtualQuery(Q, mbi, SizeOf(mbi)) = 0 then
Exit;
if (mbi.State = MEM_FREE) and (mbi.RegionSize >= dwAllocGran) and (mbi.RegionSize >= MemSize) then
begin
{ The address (P) must be multiple of the allocation granularity (dwAllocationGranularity) . }
P := PByte(RoundMultipleOf(NativeInt(Q), dwAllocGran));
Result := InternalFuncs.VirtualAlloc(P, MemSize, MEM_RESERVE or MEM_COMMIT, flProtect);
if Assigned(Result) then
Exit;
end;
Inc(Q, mbi.RegionSize); // Next Region .
end;
{
If thre is no memory available in the range [Addr - pMax]
try to allocate at the range [pMin - Addr]
}
Q := pBase;
while NativeUInt(Q) > NativeUInt(pMin) do
begin
if InternalFuncs.VirtualQuery(Q, mbi, SizeOf(mbi)) = 0 then
Exit;
if (mbi.State = MEM_FREE) and (mbi.RegionSize >= dwAllocGran) and (mbi.RegionSize >= MemSize) then
begin
P := PByte(RoundMultipleOf(NativeInt(Q), dwAllocGran));
Result := InternalFuncs.VirtualAlloc(P, MemSize, MEM_RESERVE or MEM_COMMIT, flProtect);
if Assigned(Result) then
Exit;
end;
Dec(Q, mbi.RegionSize); // Previous Region.
end;
end;
function TryAllocMemAt(const Addr: Pointer; const MemSize, flProtect: DWORD): Pointer;
var
MEM_64: DWORD;
begin
MEM_64 := 0;
Result := AllocMemAt(Addr, MemSize, flProtect);
if not Assigned(Result) then
begin
{$IFDEF CPUX64}
{ Allocates memory at the highest possible address }
if (UInt64(Addr) and $FFFFFFFF00000000 <> 0) then
MEM_64 := MEM_TOP_DOWN;
{$ENDIF CPUX64}
Result := InternalFuncs.VirtualAlloc(nil, MemSize, MEM_RESERVE or MEM_COMMIT or MEM_64, flProtect);
end;
end;
function InsertJmp(Src, Dst: PByte; JmpType: Integer; const DstSave: PByte = nil): Integer;
var
Offset: NativeInt;
JmpSize: Integer;
begin
Result := 1;
JmpSize := JmpTypeToSize[JmpType];
Offset := NativeInt(NativeInt(Dst) - NativeInt(Src)) - JmpSize;
case JmpType of
JT_NONE:
begin
raise InterceptException.Create(SErrorInvalidJmp);
end;
JT_REL8:
begin
PByte(Src)^ := opJmpRelb;
Inc(Src);
PInt8(Src)^ := Int8(Offset);
end;
JT_REL16:
begin
{$IFDEF CPUX64}
{
JMP Rel16
==> Not supported on x64!
}
raise InterceptException.Create(SErrorInvalidJmp64);
{$ENDIF CPUX64}
PByte(Src)^ := opPrfOpSize;
Inc(Src);
PByte(Src)^ := opJmpRelz;
Inc(Src);
PInt16(Src)^ := Int16(Offset);
end;
JT_REL32:
begin
PByte(Src)^ := opJmpRelz;
Inc(Src);
PInt32(Src)^ := Offset;
end;
JT_MEM16:
begin
{$IFDEF CPUX64}
{
JMP WORD [012345]
==> Not supported on x64!
}
raise InterceptException.Create(SErrorInvalidJmp64);
{$ENDIF CPUX64}
if not Assigned(DstSave) then
raise InterceptException.Create(SErrorInvalidDstSave);
PByte(Src)^ := opPrfOpSize;
Inc(Src);
PWord(Src)^ := opJmpMem;
Inc(Src, 2);
PUInt32(Src)^ := UInt32(DstSave);
PUInt16(DstSave)^ := UInt16(Dst);
end;
JT_MEM32:
begin
{$IFDEF CPUX64}
{
JMP DWORD [012345]
==> Not supported on x64!
}
raise InterceptException.Create(SErrorInvalidJmp64);
{$ENDIF CPUX64}
if not Assigned(DstSave) then
raise InterceptException.Create(SErrorInvalidDstSave);
PWord(Src)^ := opJmpMem;
Inc(Src, 2);
PUInt32(Src)^ := UInt32(DstSave);
PUInt32(DstSave)^ := UInt32(Dst);
end;
JT_MEM64:
begin
{$IFDEF CPUX86}
{
JMP QWORD [0123456789]
==> Not supported on x32!
}
raise InterceptException.Create(SErrorInvalidJmp32);
{$ENDIF CPUX86}
if not Assigned(DstSave) then
raise InterceptException.Create(SErrorInvalidDstSave);
{ RIP Disp ! }
PUInt64(DstSave)^ := UInt64(Dst);
Offset := NativeInt(NativeInt(DstSave) - NativeInt(Src)) - JmpSize;
PWord(Src)^ := opJmpMem;
Inc(Src, 2);
PInt32(Src)^ := Offset;
end;
JT_RIPZ:
begin
{$IFDEF CPUX86}
raise InterceptException.Create(SErrorInvalidJmp32);
{$ENDIF CPUX86}
{
This is the most harder way to insert a jump !
Why ?
because we are going to mix code & data !
Thats mean when disassembling instructions after
this branch .. you will have a corrupted dissambled
structure !
The only way to detect this kind of jmp is:
to use fDecodeInst rather than DecodeInst routine .
==> We should avoid using this kind of jmp
in the original target proc .
==> It's Ok to use in others situation .
}
PWord(Src)^ := opJmpMem;
Inc(Src, 2);
PInt32(Src)^ := $00;
Inc(Src, 4);
PUInt64(Src)^ := UInt64(Dst);
end;
end;
end;
function GetJmpType(Src, Dst, DstSave: PByte): Integer;
var
Offset: NativeInt;
OffsetSize: Integer;
begin
Offset := NativeInt(NativeInt(Src) - NativeInt(Dst));
OffsetSize := GetInt64Size(Offset);
Result := SizeToJmpType[OffsetSize shr 1];
{$IFDEF CPUX64}
if Result = JT_MEM64 then
begin
if not Assigned(DstSave) then
raise InterceptException.Create(SErrorInvalidDstSave);
Offset := NativeInt(NativeInt(DstSave) - NativeInt(Src)) - 7;
if Integer(Offset) <> Offset then
begin
Result := (JT_RIPZ);
Exit;
end;
end;
{$ENDIF CPUX64}
end;
function IsMultiBytesNop(P: Pointer; Size: Integer): Boolean;
var
i: Integer;
begin
Result := False;
if Size > 0 then
begin
while (Size > 0) do
begin
for i := Length(MultiNops) downto 1 do
begin
if Size >= i then
begin
Result := CompareMem(MultiNops[i - 1], P, i);
if Result then
begin
Inc(PByte(P), i);
Dec(Size, i);
break;
end;
end;
end;
if not Result then
Exit;
end;
Result := True;
end;
end;
procedure FillMultiNop(var Buffer; Size: Integer);
var
i: Integer;
P: PByte;
begin
{ Multi Bytes Nop Instruction is fast to execute compared to
the traditional NOP instruction.
However it's not supported by all CPU !
==> Use FillNop(P,Size,True).
==> CPUID implements a routine to detect
if the CPU supports Multi Bytes Nop .
}
if not(iMultiNop in CPUInsts) then
raise InterceptException.Create(SErrorUnsupportedMultiNop);
P := PByte(@Buffer);
for i := Length(MultiNops) downto 1 do
begin
while Size >= i do
begin
Move(MultiNops[i - 1]^, P^, i);
Dec(Size, i);
Inc(P, i);
end;
if Size = 0 then
Exit;
end;
end;
function IsNop(P: PByte; Size: Integer): Boolean;
var
i: Integer;
begin
{ Return True if the first instructions are nop/multi nop. }
Result := False;
if iMultiNop in CPUInsts then
Result := IsMultiBytesNop(P, Size)
else
for i := 0 to Size - 1 do
begin
Result := (P^ = opNop);
if not Result then
Exit;
Inc(P); // Next Byte.
end;
end;
procedure FillNop(var P; Size: Integer; MultipleNop: Boolean);
begin
if MultipleNop and (iMultiNop in CPUInsts) then
FillMultiNop(P, Size)
else
FillChar(P, Size, opNop);
end;
function GetPrefixesCount(Prefixes: WORD): Byte;
var
Prf: WORD;
i: Byte;
begin
{ Get prefixes count used by the instruction. }
Result := 0;
if Prefixes = 0 then
Exit;
Prf := 0;
i := 0;
Prefixes := Prefixes and not Prf_VEX;
while Prf < $8000 do
begin
Prf := (1 shl i);
if (Prf and Prefixes = Prf) then
Inc(Result);
Inc(i);
end;
end;
function GetInstOpCodes(PInst: PInstruction; P: PByte): ShortInt;
var
nPrfs: Byte;
begin
{
Return opcodes length
Instruction OpCodes in arg P .
}
Result := 0;
FillChar(P^, MAX_INST_LENGTH_N, $90);
nPrfs := GetPrefixesCount(PInst^.Prefixes);
Inc(Result, nPrfs);
case PInst^.OpTable of
tbTwoByte:
if PInst^.Prefixes and Prf_VEX3 = 0 then
Inc(Result); // $0F
tbThreeByte:
begin
if PInst^.Prefixes and Prf_VEX3 = 0 then
Inc(Result, 2); // 0F + 38|3A !
end;
tbFPU:
Inc(Result, 2); // [$D8..$D9] + ModRm !
end;
if PInst^.Prefixes and Prf_Vex2 <> 0 then
Inc(Result); // VEX.P0
if PInst^.Prefixes and Prf_VEX3 <> 0 then
Inc(Result, 2); // VEX.P0 + VEX.P1
if PInst^.OpKind = kGrp then
Inc(Result, 2) // Group + ModRm
else
Inc(Result); // OpCode
if Assigned(P) then
Move(PInst^.Addr^, P^, Result);
end;
function GetJccOpCode(PInst: PInstruction; RelSize: Integer): DWORD;
var
OpCode: Byte;
Opcodes: array [0 .. 3] of Byte;
begin
FillChar(PByte(@Opcodes[0])^, 4, #00);
OpCode := PInst^.OpCode and $F;