forked from speller/peviewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PEUtils.pas
1683 lines (1435 loc) · 43.9 KB
/
PEUtils.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 PEUtils;
interface
uses
Winapi.Windows, Classes, SysUtils, PETypes, CommonUtilities, System.Win.Registry, PEHdrUtils,
System.Generics.Collections, Winapi.ShlObj, WinApiWorks;
type
TPeImportKind = (ikImport, ikDelayImport{, ikBoundImport});
TValidState = (vsUnknown, vsValid, vsPartialValid, vsInvalid);
TMachineType = (mtUnknown, mt32, mt64);
EImageNotSupported = class(Exception);
TFileMapper = class
private
FFileHandle : THandle;
FMapHandle: THandle;
FFileSize: UInt64;
FMap: Pointer;
FFileName: string;
public
constructor Create(const AFileName: string);
destructor Destroy; override;
property Map: Pointer read fMap;
property FileSize: UInt64 read FFileSize;
property FileName: string read fFileName;
procedure LoadFile(const AFileName: string);
procedure UnloadFile;
end;
TBasePEItem = class(TCollectionItem)
private
FName: string;
FTag: Integer;
public
constructor Create(const AName: string; ACollection: TCollection); reintroduce; virtual;
property Name: string read FName write FName;
property Tag: Integer read FTag write FTag;
end;
TBasePECollection = class(TCollection)
private
FOwner: TPersistent;
function GetItemByName(const AName: string): TBasePEItem;
protected
function GetOwner: TPersistent; override;
public
property ItemByName[const AName: string]: TBasePEItem read GetItemByName; default;
procedure AddItems(ACollection: TCollection);
function IndexOfName(const AName: string): Integer;
end;
TExportItem = class(TBasePEItem)
private
FHint: SysUInt;
FAddr: SysUInt;
FOrdinal: SysUInt;
FRawOffset: SysUInt;
public
property Ordinal: SysUInt read FOrdinal write FOrdinal;
property Hint: SysUInt read FHint write FHint;
property Address: SysUInt read FAddr write FAddr;
property RawOffset: SysUInt read FRawOffset write FRawOffset;
end;
TImportLib = class;
TImportItem = class(TBasePEItem)
private
FHint: SysUInt;
FModule: string;
FLib: TImportLib;
FValid: TValidState;
FOrdinal: SysUInt;
FDisplayName: string;
public
// constructor Create(const AName: string; ACollection: TCollection); override;
property Module: string read FModule write FModule;
property Hint: SysUInt read FHint write FHint;
property Ordinal: SysUInt read FOrdinal write FOrdinal;
property Lib: TImportLib read FLib write FLib;
property ValidationState: TValidState read FValid write FValid;
property DisplayName: string read FDisplayName write FDisplayName;
procedure Assign(Source: TPersistent); override;
end;
TPEImage = class;
TImportLib = class(TBasePEItem)
private
FThunk: Pointer;
FImage: TPEImage;
FSec: PImageSectionHeader;
FImportKind: TPEImportKind;
FValid: TValidState;
FImportDescriptor: Pointer;
FFunctions: TBasePECollection;
procedure LoadData;
public
constructor Create(const AName: string; ACollection: TCollection); override;
destructor Destroy; override;
property ImportDescriptor: Pointer read FImportDescriptor write FImportDescriptor;
property ImportKind: TPEImportKind read FImportKind write FImportKind;
property Functions: TBasePECollection read FFunctions write FFunctions;
property ValidationState: TValidState read FValid write FValid;
property Image: TPEImage read FImage write FImage;
end;
TSectionItem = class(TBasePEItem)
private
FHasEP: Boolean;
FRawSize: SysUInt;
FVirtualSize: SysUInt;
FVirtualAddress: SysUInt;
FRawOffset: SysUInt;
FFlags: SysUInt;
public
property VirtualAddress: SysUInt read FVirtualAddress write FVirtualAddress;
property RawOffset: SysUInt read FRawOffset write FRawOffset;
property VirtualSize: SysUInt read FVirtualSize write FVirtualSize;
property RawSize: SysUInt read FRawSize write FRawSize;
property Flags: SysUInt read FFlags write FFlags;
property HasEP: Boolean read FHasEP write FHasEP;
end;
TResNode = class(TBasePEItem)
private
FSubDirs: TBasePECollection;
FIsRoot: Boolean;
FIsDirectory: Boolean;
FDataRaw: SysUInt;
FDataType: SysUInt;
FID: Word;
FDataSize: SysUInt;
FLang: SysUInt;
FParent: TResNode;
FImgColorDepth: Byte;
FImgY: Integer;
FImgX: Integer;
FDisplayName: string;
fCodePage: SysUInt;
FCorrupted: Boolean;
FCorruptedReason: string;
function GetChildren(Index: Integer): TResNode;
function GetChildrenCount: Integer;
public
constructor Create(const AName: string; AParent: TResNode); reintroduce;
destructor Destroy; override;
public
property Parent: TResNode read fParent write fParent;
property IsRoot: Boolean read fIsRoot;
property IsDirectory: Boolean read fIsDirectory write fIsDirectory;
property SubDirs: TBasePECollection read FSubDirs;
property DataRaw: SysUInt read FDataRaw write FDataRaw;
property DataSize: SysUInt read FDataSize write FDataSize;
property DataType: SysUInt read FDataType write FDataType;
property DisplayName: string read FDisplayName write FDisplayName;
property Lang: SysUInt read FLang write Flang;
property CodePage: SysUInt read FCodePage write fCodePage;
property ID: Word read FID write FID;
property ImgX: Integer read FImgX write FImgX;
property ImgY: Integer read FImgY write FImgY;
property ImgColorDepth: Byte read FImgColorDepth write FImgColorDepth;
property Children[Index: Integer]: TResNode read GetChildren;
property ChildrenCount: Integer read GetChildrenCount;
property Corrupted: Boolean read FCorrupted write FCorrupted;
property CorruptedReason: string read FCorruptedReason write FCorruptedReason;
end;
TPEImageHeaderDirectoryList = packed array[0..IMAGE_NUMBEROF_DIRECTORY_ENTRIES-1] of TImageDataDirectory;
PPEImageHeaderDirectoryList = ^TPEImageHeaderDirectoryList;
TPEImage = class
private
FMapper: TFileMapper;
FImList: TBasePECollection; // import libraries
FExList: TBasePECollection;
FRawSections: TList<UInt64>; // raw section headers
FSimpleExportList: TStringList; // simple list of exports for validity check
FCorrupted: Boolean;
FSections: TBasePECollection;
FImageLoadCount: Integer;
FEPExists: Boolean;
FResourceTree: TResNode;
FVersionResource: TResNode;
FImageType: Integer;
FMachineType: TMachineType;
function GetSect(Idx: Integer): PImageSectionHeader;
function GetImageTypeText: string;
function GetImageTypeSupported: Boolean;
function GetRawSectionCount: Integer;
function GetImageType: Integer;
function GetMachineType: TMachineType;
protected
function GetImageNTHeader: Pointer; virtual; abstract;
procedure SetImageNTHeader(AHeader: Pointer); virtual; abstract;
function GetSizeOfNTHeader: Integer; virtual; abstract;
function GetNTOptionalHeaderDataDirectory: PPEImageHeaderDirectoryList; virtual; abstract;
function GetNTFileHeaderNumberOfSections: UInt; virtual; abstract;
function GetNTOptionalHeaderAddressOfEntryPoint: UInt64; virtual; abstract;
procedure CheckImageType;
procedure SafeClearSimpleExportList;
public
class function CreateImage(const AFileName: string): TPEImage;
constructor Create(const AFileName: string); reintroduce;
destructor Destroy; override;
property ExportList: TBasePECollection read fExList;
property ImportList: TBasePECollection read fImList;
property SectionList: TBasePECollection read FSections;
property ResourceTree: TResNode read fResourceTree;
property VersionResource: TResNode read FVersionResource;
property SimpleExportList: TStringList read FSimpleExportList;
property ImageLoadCount: Integer read fImageLoadCount;
property Mapper: TFileMapper read fMapper;
property RawSections[Idx: Integer]: PImageSectionHeader read GetSect;
property RawSectionCount: Integer read GetRawSectionCount;
property ImageTypeText: string read GetImageTypeText;
property ImageTypeSupported: Boolean read GetImageTypeSupported;
property ImageType: Integer read GetImageType;
property MachineType: TMachineType read GetMachineType;
property Corrupted: Boolean read fCorrupted;
property ImageNTHeader: Pointer read GetImageNTHeader write SetImageNTHeader;
procedure LoadImExData;
procedure LoadSectionData;
procedure LoadSimpleExportInfo;
procedure LoadResourceTree;
procedure LoadVersionInfoResource;
function GetEntryPointRAW(var SecIdx: Integer): UInt64; virtual; abstract;
property EntryPointExists: Boolean read fEPExists;
procedure LoadImage; virtual;
procedure UnloadImage; virtual;
function VA2Raw(VirtualAddress: UInt64; ASecList: TList<UInt64>; var SecIdx: Integer): UInt64;
function RVA2Raw(VirtualAddress: UInt64; SecHdr: PImageSectionHeader ): UInt64;
procedure LoadCommonData;
function FormatHex(AValue: UInt64): string; virtual; abstract;
function RVA2RawEx(VirtualAddress: UInt64; SecHdr: PImageSectionHeader): UInt64; virtual; abstract;
end;
TPEImage32 = class(TPEImage)
private
FImageNTHeader: PImageNTHeaders32;
protected
function GetImageNTHeader: Pointer; override;
procedure SetImageNTHeader(AHeader: Pointer); override;
function GetSizeOfNTHeader: Integer; override;
function GetNTOptionalHeaderAddressOfEntryPoint: UInt64; override;
function GetNTOptionalHeaderDataDirectory: PPEImageHeaderDirectoryList; override;
function GetNTFileHeaderNumberOfSections: UInt; override;
public
property ImageNTHeader: PImageNTHeaders32 read FImageNTHeader;
function RVA2RawEx(VirtualAddress: UInt64; SecHdr: PImageSectionHeader): UInt64; override;
function GetEntryPointRAW(var SecIdx: Integer): UInt64; override;
function FormatHex(AValue: UInt64): string; override;
end;
TPEImage64 = class(TPEImage)
private
FImageNTHeader: PImageNTHeaders64;
{$IFNDEF WIN64}
FWow64Temp: SysUInt;
{$ENDIF}
protected
function GetImageNTHeader: Pointer; override;
procedure SetImageNTHeader(AHeader: Pointer); override;
function GetSizeOfNTHeader: Integer; override;
function GetNTOptionalHeaderDataDirectory: PPEImageHeaderDirectoryList; override;
function GetNTFileHeaderNumberOfSections: UInt; override;
function GetNTOptionalHeaderAddressOfEntryPoint: UInt64; override;
public
property ImageNTHeader: PImageNTHeaders64 read FImageNTHeader;
procedure LoadImage; override;
procedure UnloadImage; override;
function RVA2RawEx(VirtualAddress: UInt64; SecHdr: PImageSectionHeader): UInt64; override;
function GetEntryPointRAW(var SecIdx: Integer): UInt64; override;
function FormatHex(AValue: UInt64): string; override;
end;
TDWORDArray = array[ 0..8191 ] of DWORD;
PDWORDArray = ^TDWORDArray;
TWORDArray = array[ 0..15883 ] of WORD;
PWORDArray = ^TWORDArray;
TByteArray = array[ 0..15883 ] of Byte;
PByteArray = ^TByteArray;
function PEImageLoadLibrary(const AFileName: string; AIs64: Boolean): TPEImage;
function GetFileType(Base: Pointer; FileSize: UInt64): UInt64;
function GetNTHeaders( Base: Pointer ): PImageNtHeaders32;
function ImageType2String(IT: SysUInt): string;
procedure FreeResTree(Root: TResNode);
implementation
function GetFileSizeEx(hFile: THandle; var lpFileSize: UInt64): BOOL; stdcall; external kernel32;
const
EXE_TYPE_DOS16 = $100;
ENV_BUFFER_SIZE = 10000;
NATIVE64 = {$IFDEF WIN64}True{$ELSE}False{$ENDIF};
function GetFileType(Base: Pointer; FileSize: UInt64): UInt64;
var
NTSigPtr: ^SysUInt;
DosHdr: PImageDosHeader;
begin
Result := 0;
DosHdr := Base;
if PWORD( Base )^ <> $5A4D then Exit;
if {(DosHdr._lfanew <= $40) or}
(SysUInt(DosHdr._lfanew) > FileSize - 2) then
begin
Result := EXE_TYPE_DOS16;
Exit;
end;
NTSigPtr := Pointer(Integer(Base) + DosHdr._lfanew);
case (NTSigPtr^ and $0000FFFF) of
IMAGE_DOS_SIGNATURE: Result := IMAGE_DOS_SIGNATURE;
IMAGE_OS2_SIGNATURE: Result := IMAGE_OS2_SIGNATURE;
IMAGE_OS2_SIGNATURE_LE: Result := IMAGE_OS2_SIGNATURE_LE;
IMAGE_NT_SIGNATURE: Result := IMAGE_NT_SIGNATURE;
end;
end;
function GetNTHeaders(Base: Pointer): PImageNtHeaders32;
begin
Inc(PByte(Base), PImageDosHeader(Base)._lfanew);
Result := Base;
end;
function ImageType2String( IT: SysUInt ): string;
begin
case IT of
IMAGE_DOS_SIGNATURE: Result := 'MZ';
IMAGE_OS2_SIGNATURE: Result := 'NE';
IMAGE_OS2_SIGNATURE_LE: Result := 'LE';
IMAGE_NT_SIGNATURE: Result := 'PE';
EXE_TYPE_DOS16: Result := '16-bit DOS';
else
Result := 'UNKNOWN';
end;
end;
procedure FreeResTree( Root: TResNode );
var
I: Integer;
begin
if Root <> nil then
begin
if Root.SubDirs.Count = 0 then
Root.Free
else
for I := 0 to Root.SubDirs.Count - 1 do
TResNode(Root.SubDirs.Items[ I ]).Free;
end;
end;
{$WARNINGS OFF}
function Wow64DisableWow64FsRedirection(out OldValue: SysUInt): BOOL; stdcall; external 'kernel32.dll' delayed;
function Wow64RevertWow64FsRedirection(const OldValue: SysUInt): BOOL; stdcall; external 'kernel32.dll' delayed;
{$WARNINGS ON}
// Load specified library and search the location of it
// like windows does (LoadLibrary), but we do not need entry point
// calls and other preparations.
// Warning: NT only 16-bit system directory is not included.
function PEImageLoadLibrary(const AFileName: string; AIs64: Boolean): TPEImage;
const
imgTypes: array[Boolean] of TMachineType = (mt32, mt64);
function getSystemDir: string;
begin
Result := '';
{if (NATIVE64 and AIs64) or (not NATIVE64 and not AIs64) then
begin
SetLength(Result, MAX_PATH);
SetLength(Result, GetCurrentDirectory(MAX_PATH, @Result[1]));
end
else if (not NATIVE64 and AIs64) then
begin
SetLength(Result, MAX_PATH);
SetLength(Result, GetCurrentDirectory(MAX_PATH, @Result[1]));
end
else} if (NATIVE64 and not AIs64) then
begin
SetLength(Result, MAX_PATH);
if (SHGetSpecialFolderPath(0, @Result[1], $29, False)) then
SetLength(Result, StrLen(PWideChar(@Result[1])))
else
Result := '';
end;
if (Result = '') then
begin
SetLength(Result, MAX_PATH);
SetLength(Result, GetSystemDirectory(@Result[1], MAX_PATH));
end;
end;
function checkImage(const AFN: string; var AResult: TPEImage): Boolean;
var
img: TPEImage;
{$IFNDEF WIN64}
tmp: SysUInt;
{$ENDIF}
begin
Result := False;
{$IFNDEF WIN64}
try
if AIs64 and IsOnWow then
Wow64DisableWow64FsRedirection(tmp);
{$ENDIF}
if FileExists(AFN) then
begin
try
img := TPEImage.CreateImage(AFN);
try
img.LoadImage;
try
if (img.MachineType = imgTypes[AIs64]) then
AResult := img;
finally
img.UnloadImage;
end;
finally
if (AResult = nil) then
img.Free;
end;
Result := (AResult <> nil);
except
end;
end;
{$IFNDEF WIN64}
finally
if AIs64 and IsOnWow then
Wow64RevertWow64FsRedirection(tmp);
end;
{$ENDIF}
end;
var
s, winDir, curDir, envDir, envDirs, curLib: string;
len, i: Integer;
vl: TStringList;
r: TRegistry;
begin
Result := nil;
{$IFNDEF WIN64}
// åñëè ñìîòðèì 64-áèòíûé áèíàðíèê, íî ïðîöåññ 32 áèòà è ðàáîòàåò íà 32-áèòíîé ñèñòåìå, òî íè÷åãî íå çàãðóæàåì
if AIs64 and not IsOnWow then
Exit;
{$ENDIF}
// 1-st step
if checkImage(AFileName, Result) then
Exit;
if Pos( '\', AFileName ) > 0 then // FileName contains a path - stop searching
begin
Result := nil;
Exit;
end;
// 2-nd step
SetLength(curDir, MAX_PATH);
SetLength(curDir, GetCurrentDirectory(MAX_PATH, @curDir[1]));
if checkImage(GluePath([curDir, AFileName]), Result) then
Exit;
// 3-rd step
if checkImage(GluePath([getSystemDir, AFileName]), Result) then
Exit;
// 4-th step
// 16-bit system directory not included
// 5-th step
SetLength( WinDir, MAX_PATH + 1 );
Len := GetWindowsDirectory( @WinDir[ 1 ], MAX_PATH + 1 );
SetLength( WinDir, Len );
WinDir := IncludeTrailingPathDelimiter( WinDir );
S := WinDir + AFileName;
if checkImage(s, Result) then
Exit;
// 6-th step
SetLength(envDirs, ENV_BUFFER_SIZE);
SetLength(envDirs, GetEnvironmentVariable('PATH', @EnvDirs[1], ENV_BUFFER_SIZE));
envDir := Parse(envDirs, ';');
while (envDirs <> '') do
begin
s := GluePath([envDir, AFileName]);
if checkImage(s, Result) then
Exit;
envDir := Parse(envDirs, ';');
end;
// Loader checks this registry entry too. "7" step
r := TRegistry.Create;
try
r.RootKey := HKEY_LOCAL_MACHINE;
if (r.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs')) then
begin
VL := TStringList.Create;
r.GetValueNames(VL);
for I := 0 to VL.Count - 1 do
begin
CurLib := VL[ I ];
S := ExtractFileName( CurLib );
if AnsiSameText(s, AFileName) then
begin
if checkImage(curLib, Result) then
Exit;
end;
end;
VL.Free;
end;
finally
r.Free;
end;
Result := nil;
end;
{ TFileMapper }
constructor TFileMapper.Create(const AFileName: string);
begin
FFileName := AFileName;
end;
destructor TFileMapper.Destroy;
begin
UnloadFile;
inherited;
end;
procedure TFileMapper.LoadFile(const AFileName: string);
begin
if (FMap = nil) then
begin
FFileHandle := CreateFile(
PChar(AFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
if (FFileHandle = INVALID_HANDLE_VALUE) then
RaiseLastOSError;
try
GetFileSizeEx(FFileHandle, FFileSize);
FMapHandle := CreateFileMapping(FFileHandle, nil, PAGE_READONLY, 0, 0, nil);
if (FMapHandle = 0) then
RaiseLastOSError;
try
FMap := MapViewOfFile(FMapHandle, FILE_MAP_READ, 0, 0, 0);
if (FMap = nil) then
RaiseLastOSError;
FFileName := AFileName;
except
CloseHandle(FMapHandle);
FMapHandle := 0;
raise;
end;
except
CloseHandle(FFileHandle);
FFileHandle := 0;
raise;
end;
end;
end;
procedure TFileMapper.UnloadFile;
begin
if (FMap <> nil) then
begin
UnmapViewOfFile(FMap);
CloseHandle(FMapHandle);
CloseHandle(FFileHandle);
FMap := nil;
FFileHandle := 0;
FMapHandle := 0;
end;
end;
{ TPEImage }
function TPEImage.GetImageTypeText: string;
var
hdr: PImageNtHeaders32;
ft: Word;
begin
if (Mapper.Map <> nil) then
begin
ft := GetFileType(Mapper.Map, Mapper.FileSize);
Result := ImageType2String(ft);
if (ft = IMAGE_NT_SIGNATURE) then
begin
hdr := ImageNTHeader;
Result := Result + ', ' + GetImageMachineType(hdr.FileHeader.Machine);
end;
end
else
Result := '';
end;
function TPEImage.GetMachineType: TMachineType;
var
it: Integer;
begin
if (FMachineType = mtUnknown) then
begin
Result := mtUnknown;
it := GetImageType;
if (it = IMAGE_FILE_MACHINE_I386) then
Result := mt32
else if (it = IMAGE_FILE_MACHINE_AMD64) then
Result := mt64;
FMachineType := Result;
end
else
Result := FMachineType;
end;
function TPEImage.VA2Raw(VirtualAddress: UInt64; ASecList: TList<UInt64>; var SecIdx: Integer): UInt64;
var
I: Integer;
Pos: SysUInt;
CurSect: PImageSectionHeader;
begin
Result := 0;
SecIdx := -1;
for I := 0 to ASecList.Count - 1 do
begin
CurSect := Pointer(ASecList.Items[I]);
if
(CurSect.VirtualAddress <= VirtualAddress) and
// (VirtualAddress < CurSect.VirtualAddress + CurSect.SizeOfRawData)
(VirtualAddress < CurSect.VirtualAddress + CurSect.Misc.VirtualSize)
then
begin
Pos := VirtualAddress - CurSect.VirtualAddress;
Result := CurSect.PointerToRawData + Pos;
SecIdx := I;
Break;
end;
end;
end;
function TPEImage.RVA2Raw(VirtualAddress: UInt64; SecHdr: PImageSectionHeader ): UInt64;
begin
Result := VirtualAddress - SecHdr.VirtualAddress + SecHdr.PointerToRawData;
end;
procedure TPEImage.SafeClearSimpleExportList;
var
i: Integer;
begin
if (SimpleExportList <> nil) then
begin
for i := 0 to SimpleExportList.Count - 1 do
SimpleExportList.Objects[i] := nil;
SimpleExportList.Clear;
end;
end;
function TPEImage.GetImageType: Integer;
var
hdr: PImageNtHeaders32;
begin
if (FMapper.Map <> nil) then
begin
Result := -1;
if (GetFileType(Mapper.Map, Mapper.FileSize) = IMAGE_NT_SIGNATURE) then
begin
hdr := ImageNTHeader;
Result := hdr.FileHeader.Machine;
FImageType := Result;
end;
end
else
Result := FImageType;
end;
function TPEImage.GetImageTypeSupported: Boolean;
var
hdr: PImageNtHeaders32;
begin
if (FMapper.Map <> nil) then
begin
Result := (GetFileType(Mapper.Map, Mapper.FileSize) = IMAGE_NT_SIGNATURE);
if (Result) then
begin
hdr := ImageNTHeader;
Result :=
(hdr.FileHeader.Machine = IMAGE_FILE_MACHINE_I386) or
(hdr.FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64);
end;
end
else
Result := False;
end;
function TPEImage.GetRawSectionCount: Integer;
begin
Result := FRawSections.Count;
end;
function TPEImage.GetSect(Idx: Integer): PImageSectionHeader;
begin
Result := Pointer(FRawSections.Items[Idx]);
end;
procedure TPEImage.LoadCommonData;
var
i: Integer;
hdr: Pointer;
begin
hdr := ImageNTHeader;
if (FRawSections = nil) then
FRawSections := TList<UInt64>.Create
else
FRawSections.Clear;
for I := 0 to GetNTFileHeaderNumberOfSections - 1 do
begin
FRawSections.Add(UInt64(hdr) + GetSizeOfNTHeader + I * SizeOf(TImageSectionHeader));
end;
FEPExists := (GetNTOptionalHeaderAddressOfEntryPoint > 0);
end;
procedure TPEImage.CheckImageType;
begin
if (not ImageTypeSupported) then
raise EImageNotSupported.Create(ImageTypeText + ': unsupported');
end;
constructor TPEImage.Create(const AFileName: string);
begin
inherited Create;
FMapper := TFileMapper.Create(AFileName);
FImageType := -1;
end;
class function TPEImage.CreateImage(const AFileName: string): TPEImage;
var
stm: TFileStream;
buffer: Pointer;
sz: Integer;
hdr: PImageNtHeaders32;
begin
Result := nil;
// Preload image to determine its type and create object of approriate class
stm := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
sz := SizeOf(TImageDosHeader) + SizeOf(TImageNtHeaders64) + 2048;
GetMem(buffer, sz);
try
stm.Read(buffer^, sz);
if (GetFileType(buffer, sz) <> IMAGE_NT_SIGNATURE) then
raise Exception.Create('Image is not PE image');
hdr := GetNTHeaders(buffer);
if (hdr.FileHeader.Machine = IMAGE_FILE_MACHINE_AMD64) then
Result := TPEImage64.Create(AFileName)
else
Result := TPEImage32.Create(AFileName);
finally
FreeMem(buffer);
end;
finally
stm.Free;
end;
if (Result = nil) then
raise Exception.Create('WTF???');
end;
destructor TPEImage.Destroy;
begin
FImList.Free;
FExList.Free;
FSections.Free;
SafeClearSimpleExportList;
SimpleExportList.Free;
FRawSections.Free;
FMapper.Free;
FResourceTree.Free;
FVersionResource.Free;
inherited;
end;
procedure TPEImage.LoadImage;
begin
Mapper.LoadFile(Mapper.FileName);
Inc(FImageLoadCount);
ImageNTHeader := GetNTHeaders(Mapper.Map);
GetMachineType;
GetImageType;
end;
procedure TPEImage.LoadImExData;
var
i: Integer;
dataDir: TImageDataDirectory;
expDir: PImageExportDirectory;
imgBase: SysUInt;
j: SysUInt;
sec: PImageSectionHeader;
names: PDWORDArray;
addresses: PDWORDArray;
ordinals: PWORDArray;
rawPtr: SysUInt;
secIdx: Integer;
importDesc: PImageImportDescriptor;
delayImportDesc: PImgDelayDescr;
nam: PAnsiChar;
libItem: TImportLib;
libI, libJ: TImportLib;
exportItem: TExportItem;
funcVA, funcRaw: Integer;
is64: Boolean;
begin
CheckImageType;
LoadCommonData;
ImgBase := SysUInt(Mapper.Map);
fCorrupted := False;
if fExList = nil then
fExList := TBasePECollection.Create(TExportItem);
if fImList = nil then
fImList := TBasePECollection.Create(TImportLib);
is64 := Self is TPEImage64;
// ---- Export ----
ExportList.Clear;
try
DataDir := GetNTOptionalHeaderDataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if DataDir.VirtualAddress <> 0 then
begin
RawPtr := VA2Raw( DataDir.VirtualAddress, FRawSections, SecIdx );
if RawPtr <> 0 then
begin
Sec := Pointer(FRawSections.Items[SecIdx]);
ExpDir := Pointer( ImgBase + RawPtr );
Names := Pointer( RVA2Raw( ExpDir.AddressOfNames, Sec ) +
ImgBase );
Addresses := Pointer( RVA2Raw( ExpDir.AddressOfFunctions, Sec ) +
ImgBase );
Ordinals := Pointer( RVA2Raw( ExpDir.AddressOfNameOrdinals, Sec ) +
ImgBase );
for I := 0 to ExpDir.NumberOfNames - 1 do
begin
nam := PAnsiChar(RVA2Raw(Names[I], Sec ) + ImgBase);
FuncVA := Addresses[ Ordinals[ I ] ];
FuncRaw := RVA2Raw( FuncVA, Sec );
// FuncRaw := VA2Raw( FuncVA, fSList, SecIdx );
exportItem := TExportItem(FExList.Add);
exportItem.Name := string(nam);
exportItem.Ordinal := Ordinals[ I ] + ExpDir.Base;
exportItem.Hint := I;
exportItem.Address := FuncVA;
exportItem.RawOffset := FuncRaw;
end;
end;
end;
except
fCorrupted := True;
end;
// ---- Import ----
ImportList.Clear;
try
DataDir := GetNTOptionalHeaderDataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if DataDir.VirtualAddress <> 0 then
begin
RawPtr := VA2Raw( DataDir.VirtualAddress, FRawSections, SecIdx );
if RawPtr <> 0 then
begin
Sec := Pointer(FRawSections.Items[SecIdx]);
ImportDesc := Pointer( ImgBase + RawPtr );
while ImportDesc.Name <> 0 do
begin
nam := PAnsiChar( RVA2Raw( ImportDesc.Name, Sec ) + ImgBase );
libItem := TImportLib.Create(string(nam), FImList);
libItem.ImportKind := ikImport;
libItem.ImportDescriptor := ImportDesc;
libItem.Image := Self;
if (importDesc.Characteristics = 0) then
LibItem.FThunk := Pointer(RVA2Raw(importDesc.FirstThunk, Sec) + ImgBase)
else
LibItem.FThunk := Pointer(RVA2Raw(importDesc.Characteristics, Sec) + ImgBase);
LibItem.FSec := Sec;
LibItem.LoadData;
Inc(importDesc);
end;
end;
end;
except
FCorrupted := True;
end;
try
dataDir := GetNTOptionalHeaderDataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT];
if dataDir.VirtualAddress <> 0 then
begin
rawPtr := VA2Raw(dataDir.VirtualAddress, FRawSections, secIdx);
if (rawPtr <> 0) then
begin
sec := Pointer(FRawSections.Items[SecIdx]);
delayImportDesc := Pointer(ImgBase + RawPtr);
while delayImportDesc.szName <> 0 do
begin
nam := PAnsiChar(RVA2Raw(delayImportDesc.szName, Sec) + ImgBase);
LibItem := TImportLib.Create(string(nam), FImList);
libItem.ImportKind := ikDelayImport;
libItem.ImportDescriptor := delayImportDesc;
libItem.Image := Self;
if (is64) then
LibItem.FThunk := Pointer(RVA2Raw(delayImportDesc^.pINT, Sec) + ImgBase)
else
LibItem.FThunk := Pointer(VA2Raw(delayImportDesc^.pINT, FRawSections, secIdx) + ImgBase);
LibItem.fSec := Sec;
LibItem.LoadData;
Inc(delayImportDesc);
end;
end;