-
Notifications
You must be signed in to change notification settings - Fork 7
/
madTools.pas
1116 lines (1026 loc) · 42.2 KB
/
madTools.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
// ***************************************************************
// madTools.pas version: 1.2t · date: 2006-11-28
// -------------------------------------------------------------
// several basic tool functions
// -------------------------------------------------------------
// Copyright (C) 1999 - 2006 www.madshi.net, All Rights Reserved
// ***************************************************************
// 2006-11-28 1.2t (1) limited support for 64bit modules added
// (2) "OS" detects Vista, Media Center, x64, etc
// 2005-06-11 1.2s "ResToStr" returns a resource as binary data in a string
// 2005-02-05 1.2r GetImageNtHeaders avoids inconvenient debugger exceptions
// 2004-03-12 1.2q AMD64 NX: New -> VirtualAlloc (in MethodToProcedure)
// 2003-10-05 1.2p (1) support for Windows 2003 added
// (2) OS.enum renamed to OS.Enum -> BCB support
// 2003-06-09 1.2o (1) GetImageProcAddress now handles forwarded APIs correctly
// (2) minor bug in GetImageNtHeaders fixed
// (3) some other minor bug fixes / improvements
// 2002-12-27 1.2m FindModule + GetImageProcName added
// 2002-11-20 1.2l make OS.description work even after madTools.finalization
// 2002-10-25 1.2k some low level module image parsing functions added
// 2002-09-05 1.2j GetFreeSystemResources now simply returns 0 in NT family
// 2002-06-04 1.2i little NT4 bug workaround, see MsgHandlerWindow
// 2002-04-24 1.2h mutex and window class name now process+module dependent
// 2002-02-24 1.2g MsgHandler is now using mutex instead of critical section
// 2002-02-16 1.2f MsgHandler stuff rewritten, thread safe etc.
// 2001-07-23 1.2e Add/DelMsgHandler now can also work with other threads
// 2001-07-22 1.2d fix for wrong OS information ("setup.exe" on ME)
// 2001-07-15 1.2c new functions added (1) GetFreeSystemResources
// (2) GetFileVersion / FileVersionToStr
// 2001-05-19 1.2b osWinXP added
// 2001-04-10 1.2a TOS.description added
// 2000-11-22 1.2 MsgHandlerWindow (and related) functionality added
// 2000-07-25 1.1a minor changes in order to get rid of SysUtils
unit madTools;
{$I mad.inc}
interface
uses Windows, madTypes;
// ***************************************************************
type
// types for the "OS" function
TOsEnum = (osNone, osWin95, osWin95osr2, osWin98, osWin98se, osWinME, osWin9xNew,
osWinNtOld, osWinNt4, osWin2k, osWinXP, osWin2003, osWinVista, osWinNtNew);
TOS = record
major : cardinal;
minor : cardinal;
build : cardinal;
spStr : string;
win9x : boolean;
win9xEnum : TOsEnum;//osNone..osWin9xNew; BCB doesn't like this
winNt : boolean;
winNtEnum : TOsEnum;
Enum : TOsEnum;
x64 : boolean;
spNo : cardinal;
description : string;
end;
const
// operating system strings
COsDescr : array [TOsEnum] of pchar =
('None', 'Windows 95', 'Windows 95 OSR-2', 'Windows 98', 'Windows 98 SE',
'Windows ME', 'Windows 9x New',
'Windows NT 3', 'Windows NT 4', 'Windows 2000', 'Windows XP',
'Windows 2003', 'Windows Vista', 'Windows NT New');
// Tests which system is running...
function OS : TOS;
// ***************************************************************
// returns the 9x resource usage; 0: System; 1: GDI; 2: User
function GetFreeSystemResources (resource: word) : word;
// ***************************************************************
// returns the short respectively the long variant of the filename
function GetShortFileName (fileName: string) : string;
function GetLongFileName (fileName: string) : string;
// ***************************************************************
// returns the version number of a file, can be used on e.g. system dlls
function GetFileVersion (file_ : string) : int64;
function FileVersionToStr (version : int64 ) : string;
// ***************************************************************
// converts a procedure/function to a method
function ProcedureToMethod (self : TObject;
procAddr : pointer) : TMethod;
// converts a method to a procedure/function
// CAUTION: this works only for stdcall methods!!
// you should free the procedure pointer (FreeMem), when you don't need it anymore
function MethodToProcedure (self : TObject;
methodAddr : pointer) : pointer; overload;
function MethodToProcedure (method : TMethod) : pointer; overload;
// ***************************************************************
type
// types for AddMsgHandler/DelMsgHandler
TMsgHandler = procedure (window, msg: cardinal; wParam, lParam: integer; var result: integer);
TMsgHandlerOO = procedure (window, msg: cardinal; wParam, lParam: integer; var result: integer) of object;
// returns the message handler window handle of the specified thread
// if no such window exists yet (and if threadID = 0) then the window is created
function MsgHandlerWindow (threadID: cardinal = 0) : cardinal;
// add/delete a message handler for the message handler window of the specified thread
function AddMsgHandler (handler: TMsgHandler; msg: cardinal = 0; threadID: cardinal = 0) : cardinal; overload;
function AddMsgHandler (handler: TMsgHandlerOO; msg: cardinal = 0; threadID: cardinal = 0) : cardinal; overload;
function DelMsgHandler (handler: TMsgHandler; msg: cardinal = 0; threadID: cardinal = 0) : boolean; overload;
function DelMsgHandler (handler: TMsgHandlerOO; msg: cardinal = 0; threadID: cardinal = 0) : boolean; overload;
// ***************************************************************
const
// PE header constants
CENEWHDR = $003C; // offset of new EXE header
CEMAGIC = $5A4D; // old EXE magic id: 'MZ'
CPEMAGIC = $4550; // NT portable executable
{$externalsym IMAGE_NT_OPTIONAL_HDR32_MAGIC}
{$externalsym IMAGE_NT_OPTIONAL_HDR64_MAGIC}
IMAGE_NT_OPTIONAL_HDR32_MAGIC = $10b; // 32bit PE file
IMAGE_NT_OPTIONAL_HDR64_MAGIC = $20b; // 64bit PE file
type
// PE header types
TImageImportDirectory = packed record
HintNameArray : dword;
TimeDateStamp : dword;
ForwarderChain : dword;
Name_ : dword;
ThunkArray : dword;
end;
PImageImportDirectory = ^TImageImportDirectory;
TImageExportDirectory = packed record
Characteristics : dword;
TimeDateStamp : dword;
MajorVersion : word;
MinorVersion : word;
Name_ : dword;
Base : dword;
NumberOfFunctions : integer;
NumberOfNames : integer;
AddressOfFunctions : dword;
AddressOfNames : dword;
AddressOfNameOrdinals : dword;
end;
PImageExportDirectory = ^TImageExportDirectory;
TImageOptionalHeader64 = packed record
Magic : WORD;
MajorLinkerVersion : BYTE;
MinorLinkerVersion : BYTE;
SizeOfCode : DWORD;
SizeOfInitializedData : DWORD;
SizeOfUninitializedData : DWORD;
AddressOfEntryPoint : DWORD;
BaseOfCode : DWORD;
ImageBase : int64;
SectionAlignment : DWORD;
FileAlignment : DWORD;
MajorOperatingSystemVersion : WORD;
MinorOperatingSystemVersion : WORD;
MajorImageVersion : WORD;
MinorImageVersion : WORD;
MajorSubsystemVersion : WORD;
MinorSubsystemVersion : WORD;
Win32VersionValue : DWORD;
SizeOfImage : DWORD;
SizeOfHeaders : DWORD;
CheckSum : DWORD;
Subsystem : WORD;
DllCharacteristics : WORD;
SizeOfStackReserve : int64;
SizeOfStackCommit : int64;
SizeOfHeapReserve : int64;
SizeOfHeapCommit : int64;
LoaderFlags : DWORD;
NumberOfRvaAndSizes : DWORD;
DataDirectory : array [0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES - 1] of IMAGE_DATA_DIRECTORY;
end;
PImageOptionalHeader64 = ^TImageOptionalHeader64;
// find into which module the specified address belongs (if any)
function FindModule (addr : pointer;
var moduleHandle : dword;
var moduleName : string) : boolean;
// some low level module image parsing functions
function GetImageNtHeaders (module: dword) : PImageNtHeaders;
function GetImageImportDirectory (module: dword) : PImageImportDirectory;
function GetImageExportDirectory (module: dword) : PImageExportDirectory;
// most of the time GetImageProcAddress is equal to GetProcAddress, except:
// (1) IAT hooking often hooks GetProcAddress, too, and fakes the result
// (2) in win9x GetProcAddress refuses to work for ordinal kernel32 APIs
function GetImageProcAddress (module: dword; const name : string; doubleCheck: boolean = false) : pointer; overload;
function GetImageProcAddress (module: dword; index : integer ) : pointer; overload;
// this is the opposite of Get(Image)ProcAddress
function GetImageProcName (module: dword; proc: pointer; unmangle: boolean) : string;
// returns a resource as binary data in a string
function ResToStr (module: dword; resType, resName: pchar) : string;
// ***************************************************************
// try..except/finally works only if you have SysUtils in your uses clause
// call this function and it works without SysUtils, too
procedure InitTryExceptFinally;
// ***************************************************************
// internal functions, please ignore
function NeedModuleFileMap(module: dword) : pointer;
function Unmangle(var publicName, unitName: string) : boolean;
function VirtualToRaw(nh: PImageNtHeaders; addr: dword) : dword;
function GetSizeOfImage(nh: PImageNtHeaders) : dword;
function TickDif(tick: dword) : dword;
var CheckProcAddress : function (var addr: pointer) : boolean = nil;
NeedModuleFileMapEx : function (module: dword) : pointer = nil;
implementation
uses Messages, madStrings;
// ***************************************************************
var os_ : TOS;
osReady : boolean = false;
function OS : TOS;
const PROCESSOR_ARCHITECTURE_AMD64 = 9;
VER_NT_WORKSTATION = 1;
SM_TABLEPC = 86;
SM_MEDIACENTER = 87;
SM_STARTER = 88;
SM_SERVERR2 = 89;
type TOsVersionInfoExW = packed record
dwOSVersionInfoSize : dword;
dwMajorVersion : dword;
dwMinorVersion : dword;
dwBuildNumber : dword;
dwPlatformId : dword;
szCSDVersion : array[0..127] of WideChar;
wServicePackMajor : word;
wServicePackMinor : word;
wSuiteMask : word;
wProductType : byte;
wReserved : byte;
end;
var vi : TOsVersionInfoA;
viW : TOsVersionInfoExW;
i1 : integer;
gnsi : procedure (var si: TSystemInfo) stdcall;
si : TSystemInfo;
begin
if (not osReady) or (os_.description = '') then begin
osReady := true;
if GetVersion and $80000000 = 0 then begin
ZeroMemory(@viW, sizeOf(viW));
viW.dwOSVersionInfoSize := sizeOf(TOsVersionInfoExW);
if not GetVersionExW(POsVersionInfo(@viW)^) then begin
viW.dwOSVersionInfoSize := sizeOf(TOsVersionInfoW);
GetVersionExW(POsVersionInfo(@viW)^);
end;
Move(viW, vi, sizeOf(vi));
for i1 := low(vi.szCSDVersion) to high(vi.szCSDVersion) do
vi.szCSDVersion[i1] := char(viW.szCSDVersion[i1]);
end else begin
ZeroMemory(@vi, sizeOf(vi));
vi.dwOSVersionInfoSize := sizeOf(vi);
GetVersionExA(vi);
end;
with os_ do begin
major := vi.dwMajorVersion;
minor := vi.dwMinorVersion;
spStr := vi.szCSDVersion;
win9x := vi.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;
winNt := vi.dwPlatformId = VER_PLATFORM_WIN32_NT;
if win9x then build := word(vi.dwBuildNumber)
else build := vi.dwBuildNumber;
enum := osNone;
spNo := 0;
if win9x then begin
case major of
0..3 : ;
4 : case minor of
00..09 : if build > 1000 then enum := osWin95osr2
else enum := osWin95;
10 : if build > 2700 then enum := osWinME
else if build > 2000 then enum := osWin98se
else enum := osWin98;
11..90 : enum := osWinME;
else enum := osWin9xNew;
end;
else enum := osWin9xNew;
end;
win9xEnum := enum;
winNtEnum := osNone;
end else if winNt then begin
case major of
0..3 : enum := osWinNtOld;
4 : enum := osWinNt4;
5 : case minor of
0 : enum := osWin2k;
1 : enum := osWinXP;
else begin
if viW.wProductType = VER_NT_WORKSTATION then
enum := osWinXP
else enum := osWin2003;
end;
end;
6 : case minor of
0 : enum := osWinVista;
else enum := osWinNtNew;
end;
else enum := osWinNtNew;
end;
win9xEnum := osNone;
winNtEnum := enum;
if viW.dwOSVersionInfoSize >= sizeOf(TOsVersionInfoExW) then
spNo := viW.wServicePackMajor
else
if Length(spStr) >= 14 then
spNo := StrToIntEx(false, @spStr[14], Length(spStr) - 13);
gnsi := GetProcAddress(GetModuleHandle(kernel32), 'GetNativeSystemInfo');
if @gnsi <> nil then begin
ZeroMemory(@si, sizeOf(si));
gnsi(si);
x64 := si.wProcessorArchitecture = PROCESSOR_ARCHITECTURE_AMD64;
end;
end;
description := COsDescr[enum];
if winNt then begin
if GetSystemMetrics(SM_SERVERR2) <> 0 then
description := description + ' R2';
if GetSystemMetrics(SM_TABLEPC) <> 0 then
description := description + ' Tablet PC';
if GetSystemMetrics(SM_STARTER) <> 0 then
description := description + ' Starter';
if (enum < osWinVista) and (GetSystemMetrics(SM_MEDIACENTER) <> 0) then
description := description + ' Media Center';
if x64 then
description := description + ' x64';
if spStr <> '' then
description := description + ' ' + spStr;
end;
end;
end;
result := os_;
end;
// ***************************************************************
//this was nice, but unfortunately doesn't work in BCB:
//function LoadLibrary16 (libraryName : pchar ) : dword; stdcall; external kernel32 index 35;
//function FreeLibrary16 (hInstance : dword ) : integer; stdcall; external kernel32 index 36;
//function GetProcAddress16 (hinstance : dword; procName: pchar) : pointer; stdcall; external kernel32 index 37;
// so we have to do it the hard way:
var LoadLibrary16 : function (libraryName : pchar ) : dword stdcall = nil;
FreeLibrary16 : function (hInstance : dword ) : integer stdcall = nil;
GetProcAddress16 : function (hinstance : dword; procName: pchar) : pointer stdcall = nil;
function GetFreeSystemResources(resource: word) : word;
var thunkTrash : string[$3C];
user16 : dword;
gfsr : pointer;
qtt : pointer;
dll : dword;
begin
result := 0;
if GetVersion and $80000000 <> 0 then begin
if @LoadLibrary16 = nil then begin
dll := GetModuleHandle(kernel32);
LoadLibrary16 := GetImageProcAddress(dll, 35);
FreeLibrary16 := GetImageProcAddress(dll, 36);
GetProcAddress16 := GetImageProcAddress(dll, 37);
end;
if @LoadLibrary16 <> nil then begin
user16 := LoadLibrary16('user.exe');
if user16 <> 0 then begin
thunkTrash := '';
gfsr := GetProcAddress16(user16, 'GetFreeSystemResources');
qtt := GetProcAddress(GetModuleHandle(kernel32), 'QT_Thunk');
if (gfsr <> nil) and (qtt <> nil) then
asm
push resource
mov edx, gfsr
call qtt
mov result, ax
end;
FreeLibrary16(user16);
end;
end;
end;
end;
// ***************************************************************
function ExtractFileDrive(const fileName: string) : string;
var i1 : integer;
begin
result := '';
if Length(fileName) >= 2 then
if (fileName[1] = '\') and (fileName[2] = '\') then begin
i1 := PosStr('\', fileName, 3);
if (i1 > 0) and (i1 < Length(fileName)) then begin
i1 := PosStr('\', fileName, i1 + 1);
if i1 > 0 then result := Copy(fileName, 1, i1)
else result := fileName;
end;
end else
if fileName[2] = ':' then
result := Copy(fileName, 1, 3);
end;
function GetShortFileName(fileName: string) : string;
var c1, c2, c3 : cardinal;
wfd : TWin32FindData;
begin
result := '';
if (fileName <> '') and (fileName[Length(fileName)] = '\') then
Delete(fileName, Length(fileName), 1);
c3 := Length(ExtractFileDrive(fileName));
repeat
c1 := PosStr('\', fileName, maxInt, 1);
if (c3 = 0) or (c1 < c3) then begin
result := fileName + '\' + result;
break;
end;
if (PosStr('*', fileName, c1 + 1) = 0) and (PosStr('?', fileName, c1 + 1) = 0) then begin
c2 := FindFirstFile(pchar(fileName), wfd);
if c2 <> INVALID_HANDLE_VALUE then begin
windows.FindClose(c2);
if wfd.cAlternateFileName[0] <> #0 then
result := string(wfd.cAlternateFileName) + '\' + result
else result := string(wfd.cFileName ) + '\' + result;
end else result := Copy(fileName, c1 + 1, maxInt) + '\' + result;
end else result := Copy(fileName, c1 + 1, maxInt) + '\' + result;
Delete(fileName, c1, maxInt);
until (c1 = 0) or (fileName = '');
if (result <> '') and (result[Length(result)] = '\') then
Delete(result, Length(result), 1);
end;
function GetLongFileName(fileName: string) : string;
var c1, c2, c3 : cardinal;
wfd : TWin32FindData;
begin
result := '';
if (fileName <> '') and (fileName[Length(fileName)] = '\') then
Delete(fileName, Length(fileName), 1);
c3 := Length(ExtractFileDrive(fileName));
repeat
c1 := PosStr('\', fileName, maxInt, 1);
if (c3 = 0) or (c1 < c3) then begin
result := fileName + '\' + result;
break;
end;
if (PosStr('~', fileName, c1 + 1) > 0) and (PosStr('*', fileName, c1 + 1) = 0) and
(PosStr('?', fileName, c1 + 1) = 0) then begin
c2 := FindFirstFile(pchar(fileName), wfd);
if c2 <> INVALID_HANDLE_VALUE then begin
windows.FindClose(c2);
result := string(wfd.cfileName) + '\' + result;
end else result := Copy(fileName, c1 + 1, maxInt) + '\' + result;
end else result := Copy(fileName, c1 + 1, maxInt) + '\' + result;
Delete(fileName, c1, maxInt);
until (c1 = 0) or (fileName = '');
if (result <> '') and (result[Length(result)] = '\') then
Delete(result, Length(result), 1);
end;
// ***************************************************************
function GetFileVersion(file_: string) : int64;
var len, hnd : dword;
buf : string;
pfi : PVsFixedFileInfo;
begin
result := 0;
len := GetFileVersionInfoSize(pchar(file_), hnd);
if len <> 0 then begin
SetLength(buf, len);
if GetFileVersionInfo(pchar(file_), hnd, len, pointer(buf)) and
VerQueryValue(pointer(buf), '\', pointer(pfi), len) then
result := int64(pfi^.dwFileVersionMS) shl 32 + int64(pfi^.dwFileVersionLS);
end;
end;
function FileVersionToStr(version: int64) : string;
begin
result := IntToStrEx( version shr 48 ) + '.' +
IntToStrEx((version shr 32) and $FFFF) + '.' +
IntToStrEx((version shr 16) and $FFFF) + '.' +
IntToStrEx( version and $FFFF);
end;
// ***************************************************************
function MethodToProcedure(self: TObject; methodAddr: pointer) : pointer;
type
TMethodToProc = packed record
popEax : byte; // $58 pop EAX
pushSelf : record // push self
opcode : byte; // $B8
self : pointer; // self
end;
pushEax : byte; // $50 push EAX
jump : record // jmp [target]
opcode : byte; // $FF
modRm : byte; // $25
pTarget : ^pointer; // @target
target : pointer; // @MethodAddr
end;
end;
var mtp : ^TMethodToProc absolute result;
begin
mtp := VirtualAlloc(nil, sizeOf(mtp^), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
with mtp^ do begin
popEax := $58;
pushSelf.opcode := $68;
pushSelf.self := self;
pushEax := $50;
jump.opcode := $FF;
jump.modRm := $25;
jump.pTarget := @jump.target;
jump.target := methodAddr;
end;
end;
function MethodToProcedure(method: TMethod) : pointer;
begin
result := MethodToProcedure(TObject(method.data), method.code);
end;
function ProcedureToMethod(self: TObject; procAddr: pointer) : TMethod;
begin
result.Data := self;
result.Code := procAddr;
end;
// ***************************************************************
type
TMsgHandlers = array of record
message : cardinal;
handler : TMsgHandler;
handlerOO : TMsgHandlerOO;
end;
var
MsgHandlerMutex : dword = 0;
MsgHandlerWindows : array of record
threadID : cardinal;
window : cardinal;
handlers : TMsgHandlers;
end;
function MsgHandlerWindowProc(window, msg: cardinal; wParam, lParam: integer) : integer; stdcall;
var i1 : integer;
mh : TMsgHandlers;
begin
mh := nil;
result := DefWindowProc(window, msg, wParam, lParam);
if (msg in [WM_QUERYENDSESSION, WM_QUIT, WM_SYSCOLORCHANGE, WM_ENDSESSION, WM_SYSTEMERROR,
WM_WININICHANGE, WM_DEVMODECHANGE, WM_ACTIVATEAPP, WM_FONTCHANGE, WM_TIMECHANGE,
WM_SPOOLERSTATUS, WM_COMPACTING, WM_POWER, WM_INPUTLANGCHANGEREQUEST, WM_INPUTLANGCHANGE,
WM_USERCHANGED, WM_DISPLAYCHANGE]) or (msg >= WM_POWERBROADCAST) then begin
WaitForSingleObject(MsgHandlerMutex, INFINITE);
try
for i1 := 0 to high(MsgHandlerWindows) do
if MsgHandlerWindows[i1].window = window then begin
mh := Copy(MsgHandlerWindows[i1].handlers);
break;
end;
finally ReleaseMutex(MsgHandlerMutex) end;
for i1 := 0 to high(mh) do
if mh[i1].message = msg then
if @mh[i1].handler <> nil then
mh[i1].handler (window, msg, wParam, lParam, result)
else mh[i1].handlerOO(window, msg, wParam, lParam, result);
end;
end;
function MsgHandlerWindow(threadID: cardinal = 0) : cardinal;
const CMadToolsMsgHandlerWindow = 'madToolsMsgHandlerWindow';
var wndClass : TWndClass;
mutex : dword;
i1 : integer;
s1 : string;
begin
result := 0;
if threadID = 0 then threadID := GetCurrentThreadID;
s1 := IntToHexEx(GetCurrentThreadID) + IntToHexEx(dword(@MsgHandlerWindow));
if MsgHandlerMutex = 0 then begin
mutex := CreateMutex(nil, false, pchar('madToolsMsgHandlerMutex' + s1));
if mutex <> 0 then begin
WaitForSingleObject(mutex, INFINITE);
if MsgHandlerMutex = 0 then
MsgHandlerMutex := mutex
else CloseHandle(mutex);
end;
end else
WaitForSingleObject(MsgHandlerMutex, INFINITE);
try
for i1 := 0 to high(MsgHandlerWindows) do
if MsgHandlerWindows[i1].threadID = threadID then begin
result := MsgHandlerWindows[i1].window;
break;
end;
finally ReleaseMutex(MsgHandlerMutex) end;
if (result = 0) and (threadID = GetCurrentThreadID) then begin
ZeroMemory(@wndClass, sizeOf(wndClass));
wndClass.lpfnWndProc := @MsgHandlerWindowProc;
wndClass.hInstance := GetModuleHandle(nil);
wndClass.lpszClassName := pchar(CMadToolsMsgHandlerWindow + s1);
windows.RegisterClass(wndClass);
// in NT4 you sometimes have to give exactly the same *pointer*
// which you used in RegisterClass, the same *string* sometimes fails
result := CreateWindowEx(WS_EX_TOOLWINDOW, wndClass.lpszClassName, '', WS_POPUP,
0, 0, 0, 0, 0, 0, wndClass.hInstance, nil);
if result <> 0 then begin
WaitForSingleObject(MsgHandlerMutex, INFINITE);
try
i1 := Length(MsgHandlerWindows);
SetLength(MsgHandlerWindows, i1 + 1);
MsgHandlerWindows[i1].threadID := threadID;
MsgHandlerWindows[i1].window := result;
finally ReleaseMutex(MsgHandlerMutex) end;
end;
end;
end;
function AddMsgHandler_(handler: TMsgHandler; handlerOO: TMsgHandlerOO; msg, threadID: cardinal) : cardinal;
var i1, i2 : integer;
b1 : boolean;
window : cardinal;
begin
result := 0;
window := MsgHandlerWindow(threadID);
if window <> 0 then begin
WaitForSingleObject(MsgHandlerMutex, INFINITE);
try
for i1 := 0 to high(MsgHandlerWindows) do
if MsgHandlerWindows[i1].window = window then
with MsgHandlerWindows[i1] do begin
if msg = 0 then begin
msg := WM_USER;
repeat
b1 := true;
for i2 := 0 to high(handlers) do
if handlers[i2].message = msg then begin
b1 := false;
inc(msg);
break;
end;
until b1;
end else
for i2 := 0 to high(handlers) do
if (handlers[i2].message = msg) and
( @handlers[i2].handler = @handler ) and
(int64(TMethod(handlers[i2].handlerOO)) = int64(TMethod(handlerOO))) then
exit;
i2 := Length(handlers);
SetLength(handlers, i2 + 1);
handlers[i2].message := msg;
handlers[i2].handler := handler;
handlers[i2].handlerOO := handlerOO;
result := msg;
break;
end;
finally ReleaseMutex(MsgHandlerMutex) end;
end;
end;
function AddMsgHandler(handler: TMsgHandler; msg: cardinal = 0; threadID: cardinal = 0) : cardinal;
begin
result := AddMsgHandler_(handler, nil, msg, threadID);
end;
function AddMsgHandler(handler: TMsgHandlerOO; msg: cardinal = 0; threadID: cardinal = 0) : cardinal;
begin
result := AddMsgHandler_(nil, handler, msg, threadID);
end;
function DelMsgHandler_(handler: TMsgHandler; handlerOO: TMsgHandlerOO; msg, threadID: cardinal) : boolean;
var i1, i2 : integer;
c1 : cardinal;
begin
result := false;
if MsgHandlerMutex <> 0 then begin
if threadID = 0 then threadID := GetCurrentThreadID;
WaitForSingleObject(MsgHandlerMutex, INFINITE);
try
c1 := 0;
for i1 := 0 to high(MsgHandlerWindows) do
if MsgHandlerWindows[i1].threadID = threadID then
with MsgHandlerWindows[i1] do begin
for i2 := high(handlers) downto 0 do
if ( (msg = 0) or (handlers[i2].message = msg) ) and
( @handlers[i2].handler = @handler ) and
(int64(TMethod(handlers[i2].handlerOO)) = int64(TMethod(handlerOO))) then begin
handlers[i2] := handlers[high(handlers)];
SetLength(handlers, high(handlers));
end;
if (handlers = nil) and IsWindow(window) then begin
c1 := window;
MsgHandlerWindows[i1] := MsgHandlerWindows[high(MsgHandlerWindows)];
SetLength(MsgHandlerWindows, high(MsgHandlerWindows));
end;
break;
end;
finally ReleaseMutex(MsgHandlerMutex) end;
if c1 <> 0 then
if threadID = GetCurrentThreadID then
DestroyWindow(c1)
else PostMessage(c1, WM_CLOSE, 0, 0);
end;
end;
function DelMsgHandler(handler: TMsgHandler; msg: cardinal = 0; threadID: cardinal = 0) : boolean;
begin
result := DelMsgHandler_(handler, nil, msg, threadID);
end;
function DelMsgHandler(handler: TMsgHandlerOO; msg: cardinal = 0; threadID: cardinal = 0) : boolean;
begin
result := DelMsgHandler_(nil, handler, msg, threadID);
end;
procedure FinalMsgHandler;
var mutex : dword;
begin
mutex := MsgHandlerMutex;
MsgHandlerMutex := 0;
if mutex <> 0 then
CloseHandle(mutex);
end;
// ***************************************************************
function FindModule(addr: pointer; var moduleHandle: dword; var moduleName: string) : boolean;
var mbi : TMemoryBasicInformation;
arrChA : array [0..MAX_PATH] of char;
arrChW : array [0..MAX_PATH] of widechar;
i1 : integer;
ch1 : char;
begin
result := (VirtualQuery(addr, mbi, sizeOf(mbi)) = sizeOf(mbi)) and
(mbi.State = MEM_COMMIT) and (mbi.AllocationBase <> nil);
if result then begin
if GetVersion and $80000000 <> 0 then
result := GetModuleFileNameA(dword(mbi.AllocationBase), arrChA, MAX_PATH) <> 0
else result := GetModuleFileNameW(dword(mbi.AllocationBase), arrChW, MAX_PATH) <> 0;
if result then begin
moduleHandle := dword(mbi.AllocationBase);
if GetVersion and $80000000 = 0 then
for i1 := 0 to MAX_PATH - 1 do begin
ch1 := char(arrChW[i1]);
arrChA[i1] := ch1;
if ch1 = #0 then
break;
end;
moduleName := arrChA;
end;
end;
end;
function GetImageNtHeaders(module: dword) : PImageNtHeaders;
begin
result := nil;
try
if (not IsBadReadPtr(pointer(module), 2)) and (TPWord(module)^ = CEMAGIC) then begin
result := pointer(module + dword(pointer(module + CENEWHDR)^));
if result^.signature <> CPEMAGIC then
result := nil;
end;
except result := nil end;
end;
function GetImageDataDirectory(module, directory: dword) : pointer;
var nh : PImageNtHeaders;
begin
nh := GetImageNtHeaders(module);
if nh <> nil then begin
if nh^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
dword(result) := module + PImageOptionalHeader64(@nh^.OptionalHeader).DataDirectory[directory].VirtualAddress
else dword(result) := module + nh^.OptionalHeader .DataDirectory[directory].VirtualAddress;
end else
result := nil;
end;
function GetImageImportDirectory(module: dword) : PImageImportDirectory;
begin
result := GetImageDataDirectory(module, IMAGE_DIRECTORY_ENTRY_IMPORT);
end;
function GetImageExportDirectory(module: dword) : PImageExportDirectory;
begin
result := GetImageDataDirectory(module, IMAGE_DIRECTORY_ENTRY_EXPORT);
end;
function ExportToFunc(module, addr: dword) : pointer;
var nh : PImageNtHeaders;
ed : TImageDataDirectory;
s1 : string;
pc1, pc2 : pchar;
begin
nh := GetImageNtHeaders(module);
if nh^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
ed := PImageOptionalHeader64(@nh^.OptionalHeader).DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
else ed := nh^.OptionalHeader .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (addr >= ed.VirtualAddress) and (addr < ed.VirtualAddress + ed.Size) then begin
s1 := pchar(module + addr);
pc1 := pchar(s1);
pc2 := pc1;
repeat inc(pc2) until pc2^ = '.';
pc2^ := #0;
inc(pc2);
result := GetImageProcAddress(GetModuleHandle(pc1), pc2);
end else
result := pointer(module + addr);
end;
function VirtualToRaw(nh: PImageNtHeaders; addr: dword) : dword;
type TAImageSectionHeader = packed array [0..maxInt shr 6] of TImageSectionHeader;
var i1 : integer;
sh : ^TAImageSectionHeader;
begin
result := addr;
if nh^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
dword(sh) := dword(@nh^.OptionalHeader) + sizeOf(TImageOptionalHeader64)
else dword(sh) := dword(@nh^.OptionalHeader) + sizeOf(TImageOptionalHeader );
for i1 := 0 to nh^.FileHeader.NumberOfSections - 1 do
if (addr >= sh[i1].VirtualAddress) and
((i1 = nh^.FileHeader.NumberOfSections - 1) or (addr < sh[i1 + 1].VirtualAddress)) then begin
result := addr - sh[i1].VirtualAddress + sh[i1].PointerToRawData;
break;
end;
end;
function GetSizeOfImage(nh: PImageNtHeaders) : dword;
begin
if nh^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
result := PImageOptionalHeader64(@nh.OptionalHeader).SizeOfImage
else result := nh.OptionalHeader .SizeOfImage;
end;
function NeedModuleFileMap(module: dword) : pointer;
var arrCh : pointer;
fh : dword;
map : dword;
begin
result := nil;
if GetVersion and $80000000 = 0 then begin
arrCh := pointer(LocalAlloc(LPTR, MAX_PATH * 2 + 2));
GetModuleFileNameW(module, arrCh, MAX_PATH);
fh := CreateFileW(arrCh, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
end else begin
arrCh := pointer(LocalAlloc(LPTR, MAX_PATH + 1));
GetModuleFileNameA(module, arrCh, MAX_PATH);
fh := CreateFileA(arrCh, GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
end;
LocalFree(dword(arrCh));
if fh <> INVALID_HANDLE_VALUE then begin
if GetVersion and $80000000 = 0 then
map := CreateFileMappingW(fh, nil, PAGE_READONLY, 0, 0, nil)
else map := CreateFileMappingA(fh, nil, PAGE_READONLY, 0, 0, nil);
if map <> 0 then begin
result := MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
CloseHandle(map);
end;
CloseHandle(fh);
end;
end;
function GetImageProcAddress(module: dword; const name: string; doubleCheck: boolean = false) : pointer;
var ed : PImageExportDirectory;
nh : PImageNtHeaders;
i1 : integer;
c1, c2, c3 : dword;
w1 : word;
va : dword;
buf : pointer;
p1 : pointer;
freeBuf : boolean;
soi : dword;
begin
result := nil;
if module <> 0 then begin
nh := GetImageNtHeaders(module);
if nh <> nil then begin
soi := GetSizeOfImage(nh);
if nh^.OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC then
va := PImageOptionalHeader64(@nh^.OptionalHeader).DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
else va := nh^.OptionalHeader .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
dword(ed) := module + va;
if ed <> nil then
for i1 := 0 to ed^.NumberOfNames - 1 do
if lstrcmpA(pointer(module + TPACardinal(module + ed^.AddressOfNames)^[i1]), pointer(name)) = 0 then begin
w1 := TPAWord(module + ed^.AddressOfNameOrdinals)^[i1];
c1 := TPACardinal(module + ed^.AddressOfFunctions)^[w1];
if doubleCheck or (c1 > soi) then begin
dword(p1) := module + c1;
if (@CheckProcAddress <> nil) and CheckProcAddress(p1) then begin
result := p1;
break;
end;
if @NeedModuleFileMapEx <> nil then
buf := NeedModuleFileMapEx(module)
else
buf := nil;
freeBuf := buf = nil;
if buf = nil then
buf := NeedModuleFileMap(module);
if buf <> nil then begin
try
c2 := ed^.AddressOfNames;
c3 := ed^.AddressOfFunctions;
dword(ed) := dword(buf) + VirtualToRaw(nh, va);
if (c2 = ed^.AddressOfNames) and (c3 = ed^.AddressOfFunctions) then
c1 := TPACardinal(dword(buf) + VirtualToRaw(nh, ed^.AddressOfFunctions))^[w1];
except end;
if freeBuf then
UnmapViewOfFile(buf);
end;
end;
result := ExportToFunc(module, c1);
break;
end;
end;
if result = nil then begin
nh := GetImageNtHeaders(module);
if (nh <> nil) and (nh^.OptionalHeader.Magic <> IMAGE_NT_OPTIONAL_HDR64_MAGIC) then
result := GetProcAddress(module, pointer(name));
end;
end;
end;
function GetImageProcAddress(module: dword; index: integer) : pointer; overload;
var oi : integer;
nh : PImageNtHeaders;
ed : PImageExportDirectory;
c1 : dword;
begin
result := nil;
oi := index;
ed := GetImageExportDirectory(module);
if ed <> nil then
with ed^ do begin
dec(index, Base);
if (index >= 0) and (index < NumberOfFunctions) then begin
c1 := TPACardinal(module + AddressOfFunctions)^[index];
if c1 > 0 then
result := ExportToFunc(module, c1);
end;
end;
if result = nil then begin
nh := GetImageNtHeaders(module);
if (nh <> nil) and (nh^.OptionalHeader.Magic <> IMAGE_NT_OPTIONAL_HDR64_MAGIC) then
result := GetProcAddress(module, pchar(oi));
end;
end;
function GetImageProcName(module: dword; proc: pointer; unmangle: boolean) : string;
var ed : PImageExportDirectory;
i1, i2 : integer;
s1 : string;
begin
result := '';
ed := GetImageExportDirectory(module);
if ed <> nil then
with ed^ do
for i1 := 0 to NumberOfFunctions - 1 do
if module + TPACardinal(module + AddressOfFunctions)^[i1] = dword(proc) then begin
for i2 := 0 to NumberOfNames - 1 do
if TPAWord(module + AddressOfNameOrdinals)^[i2] = i1 then begin
result := pchar(module + TPACardinal(module + AddressOfNames)^[i2]);
break;
end;
if result = '' then
result := '#' + IntToStrEx(Base + dword(i1));
break;
end;
if unmangle and madTools.Unmangle(result, s1) then
result := s1 + '.' + result;