-
Notifications
You must be signed in to change notification settings - Fork 35
/
NtUtils.ImageHlp.pas
1272 lines (1049 loc) · 34.6 KB
/
NtUtils.ImageHlp.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 NtUtils.ImageHlp;
{
This module include various parsing routines for Portable Executable format.
}
interface
uses
Ntapi.WinNt, Ntapi.ImageHlp, NtUtils, DelphiApi.Reflection;
type
TImageBitness = (ib32Bit, ib64Bit);
TExportEntry = record
Name: AnsiString;
Ordinal: Word;
[Hex] VirtualAddress: Cardinal;
Forwards: Boolean;
ForwardsTo: AnsiString;
end;
PExportEntry = ^TExportEntry;
TImportType = (
itNormal,
itDelayed
);
TImportTypeSet = set of TImportType;
TImportEntry = record
ImportByName: Boolean;
DelayedImport: Boolean;
Name: AnsiString;
Ordinal: Word;
end;
TImportDllEntry = record
DllName: AnsiString;
[Hex] IAT: Cardinal; // Import Address Table RVA
Functions: TArray<TImportEntry>;
end;
TRtlxImageDebugInfo = record
Timestamp: TUnixTime;
PdbGuid: TGuid;
PdbAge: Cardinal;
FileName: AnsiString;
end;
// Get an NT header of an image
function RtlxGetImageNtHeader(
out NtHeader: PImageNtHeaders;
const Image: TMemory;
RangeChecks: Boolean = True
): TNtxStatus;
// Get the image bitness
function RtlxGetImageBitness(
out Bitness: TImageBitness;
const Image: TMemory;
[in, opt] NtHeaders: PImageNtHeaders = nil;
RangeChecks: Boolean = True
): TNtxStatus;
// Get the preferred image base address (potentially, after dynamic relocation)
function RtlxGetImageBase(
out Base: UInt64;
const Image: TMemory;
[in, opt] NtHeaders: PImageNtHeaders = nil;
RangeChecks: Boolean = True
): TNtxStatus;
// Get the RVA of the entrypoint
function RtlxGetImageEntrypointRva(
out EntryPointRva: Cardinal;
const Image: TMemory;
[in, opt] NtHeaders: PImageNtHeaders = nil;
RangeChecks: Boolean = True
): TNtxStatus;
// Get a section that contains a virtual address
function RtlxSectionTableFromVirtualAddress(
out Section: PImageSectionHeader;
const Image: TMemory;
MappedAsImage: Boolean;
VirtualAddress: Cardinal;
AddressRange: Cardinal;
[in, opt] NtHeaders: PImageNtHeaders = nil;
RangeChecks: Boolean = True
): TNtxStatus;
// Get a pointer to a virtual address in an image
function RtlxExpandVirtualAddress(
out Address: Pointer;
const Image: TMemory;
MappedAsImage: Boolean;
VirtualAddress: Cardinal;
AddressRange: Cardinal;
[in, opt] NtHeaders: PImageNtHeaders = nil;
RangeChecks: Boolean = True;
[out, opt] pSectionEndAddress: PPointer = nil
): TNtxStatus;
// Get a data directory in an image
function RtlxGetDirectoryEntryImage(
[MayReturnNil] out Directory: PImageDataDirectory;
const Image: TMemory;
MappedAsImage: Boolean;
Entry: TImageDirectoryEntry;
RangeChecks: Boolean = True
): TNtxStatus;
// Enumerate exported functions in an image
function RtlxEnumerateExportImage(
out Entries: TArray<TExportEntry>;
const Image: TMemory;
MappedAsImage: Boolean;
RangeChecks: Boolean = True
): TNtxStatus;
// Find an export entry by name
function RtlxFindExportedNameIndex(
const Entries: TArray<TExportEntry>;
const Name: AnsiString
): Integer;
// Enumerate imported or delayed import of an image
function RtlxEnumerateImportImage(
out Entries: TArray<TImportDllEntry>;
const Image: TMemory;
MappedAsImage: Boolean;
ImportTypes: TImportTypeSet = [itNormal, itDelayed];
RangeChecks: Boolean = True
): TNtxStatus;
// Relocate an image to a new base address
function RtlxRelocateImage(
const Image: TMemory;
NewImageBase: NativeUInt;
MappedAsImage: Boolean;
RangeChecks: Boolean = True
): TNtxStatus;
// Retrieve PDB information for an image
function RtlxGetImageDebugInfo(
out Info: TRtlxImageDebugInfo;
const Image: TMemory;
MappedAsImage: Boolean;
[in, opt] NtHeaders: PImageNtHeaders = nil;
RangeChecks: Boolean = True
): TNtxStatus;
implementation
uses
Ntapi.ntrtl, Ntapi.ntmmapi, ntapi.ntstatus, NtUtils.SysUtils, NtUtils.Memory,
DelphiUtils.Arrays, NtUtils.Processes, DelphiUtils.RangeChecks;
{$RANGECHECKS OFF}
{$OVERFLOWCHECKS OFF}
{$BOOLEVAL OFF}
{$IFOPT R+}{$DEFINE R+}{$ENDIF}
{$IFOPT Q+}{$DEFINE Q+}{$ENDIF}
function RtlxGetImageNtHeader;
const
Flags: array [Boolean] of Cardinal = (
RTL_IMAGE_NT_HEADER_EX_FLAG_NO_RANGE_CHECK, 0
);
begin
try
// Let ntdll parse the DOS header and locate the NT header.
// Note that the range checks here don't cover data past FileHeader.
Result.Location := 'RtlImageNtHeaderEx';
Result.Status := RtlImageNtHeaderEx(Flags[RangeChecks <> False],
Image.Address, Image.Size, NtHeader);
except
Result.Location := 'RtlxGetImageNtHeader';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxGetImageBitness;
begin
// Locate the NT headers
if not Assigned(NtHeaders) then
begin
Result := RtlxGetImageNtHeader(NtHeaders, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
end;
Result.Location := 'RtlxGetImageBitness';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
try
// Validate the optional header magic offset
if RangeChecks and not CheckStruct(Image,
@NtHeaders.OptionalHeader.Magic, SizeOf(Word)) then
Exit;
// Check the magic
case NtHeaders.OptionalHeader.Magic of
IMAGE_NT_OPTIONAL_HDR32_MAGIC: Bitness := ib32Bit;
IMAGE_NT_OPTIONAL_HDR64_MAGIC: Bitness := ib64Bit;
else
Exit;
end;
Result.Status := STATUS_SUCCESS;
except
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxGetImageBase;
var
Bitness: TImageBitness;
begin
// Locate the NT headers
if not Assigned(NtHeaders) then
begin
Result := RtlxGetImageNtHeader(NtHeaders, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
end;
// Determine the bitness of the header
Result := RtlxGetImageBitness(Bitness, Image);
if not Result.IsSuccess then
Exit;
Result.Location := 'RtlxGetImageBase';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
try
case Bitness of
ib32Bit:
begin
// Check the 32-bit image base field
if RangeChecks and not CheckStruct(Image, @NtHeaders.OptionalHeader32
.ImageBase, SizeOf(Cardinal)) then
Exit;
Base := NtHeaders.OptionalHeader32.ImageBase;
end;
ib64Bit:
begin
// Check the 64-bit image base field
if RangeChecks and not CheckStruct(Image, @NtHeaders.OptionalHeader64
.ImageBase, SizeOf(UInt64)) then
Exit;
Base := NtHeaders.OptionalHeader64.ImageBase;
end;
else
Exit;
end;
Result.Status := STATUS_SUCCESS;
except
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxGetImageEntrypointRva;
begin
// Locate the NT headers
if not Assigned(NtHeaders) then
begin
Result := RtlxGetImageNtHeader(NtHeaders, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
end;
Result.Location := 'RtlxGetEntrypointRvaImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
try
// Check the field offset which is the same for 32- and 64-bit images
if RangeChecks and not CheckStruct(Image, @NtHeaders.OptionalHeader
.AddressOfEntryPoint, SizeOf(Cardinal)) then
Exit;
EntryPointRva := NtHeaders.OptionalHeader.AddressOfEntryPoint;
Result.Status := STATUS_SUCCESS;
except
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxSectionTableFromVirtualAddress;
var
SectionRegion: TMemory;
i: Integer;
begin
try
// Reproduce RtlSectionTableFromVirtualAddress with more range checks
if not Assigned(NtHeaders) then
begin
Result := RtlxGetImageNtHeader(NtHeaders, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
end;
// Fail with this status if something goes wrong with range checks
Result.Location := 'RtlxSectionTableFromVirtualAddress';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
if RangeChecks and not CheckStruct(Image,
@NtHeaders.FileHeader, SizeOf(TImageFileHeader)) then
Exit;
Pointer(Section) := PByte(@NtHeaders.OptionalHeader) +
NtHeaders.FileHeader.SizeOfOptionalHeader;
if RangeChecks and not CheckArray(Image, Section,
SizeOf(TImageSectionHeader), NtHeaders.FileHeader.NumberOfSections) then
Exit;
for i := 0 to Integer(NtHeaders.FileHeader.NumberOfSections) - 1 do
begin
UIntPtr(SectionRegion.Address) := Section.VirtualAddress;
if MappedAsImage then
SectionRegion.Size := Section.VirtualSize
else
SectionRegion.Size := Section.SizeOfRawData;
// If range checks are disabled, test the starting virtual address only
if not RangeChecks then
AddressRange := 0;
// Does this virtual address (range) belong to this section?
if CheckStruct(SectionRegion, Pointer(VirtualAddress), AddressRange) then
begin
// Found it
Result.Status := STATUS_SUCCESS;
Exit;
end;
// Go to the next section
Inc(Section);
end;
// The virtual address is not found within image sections
Result.Status := STATUS_NOT_FOUND;
except
Result.Location := 'RtlxSectionTableFromVirtualAddress';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxExpandVirtualAddress;
var
Section: PImageSectionHeader;
RawAddress64: UInt64;
begin
try
// Reproduce and extend RtlImageRvaToVa with more access checks
if MappedAsImage and not RangeChecks then
begin
// Virtual addresses in an image without range checks are just offsets
Address := Image.Offset(VirtualAddress);
// No range checks mean no end address
if Assigned(pSectionEndAddress) then
pSectionEndAddress^ := Pointer(UInt64(-1));
Exit(NtxSuccess);
end;
// Find a section containing the virtual address range
Result := RtlxSectionTableFromVirtualAddress(Section, Image, MappedAsImage,
VirtualAddress, AddressRange, NtHeaders, RangeChecks);
if not Result.IsSuccess then
Exit;
Result.Location := 'RtlxExpandVirtualAddress';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
if MappedAsImage then
begin
// Validate the virtual address range
if RangeChecks and not CheckOffsetStruct(Image, VirtualAddress,
AddressRange) then
Exit;
Address := Image.Offset(VirtualAddress);
if Assigned(pSectionEndAddress) then
begin
// Validate section up to its end
if RangeChecks and not CheckOffsetStruct(Image, Section.VirtualAddress,
Section.VirtualSize) then
Exit;
pSectionEndAddress^ := Image.Offset(Section.VirtualAddress +
Section.VirtualSize);
end;
end
else
begin
// Compute the address without a possibility to overflow
RawAddress64 := UInt64(Section.PointerToRawData) + VirtualAddress -
Section.VirtualAddress;
// Validate raw data range
if RangeChecks and not CheckOffsetStruct(Image, RawAddress64,
AddressRange) then
Exit;
// Convert the address from VA to raw
Address := Image.Offset(RawAddress64);
if Assigned(pSectionEndAddress) then
begin
// Validate section up to the end
if RangeChecks and not CheckOffsetStruct(Image,
Section.PointerToRawData, Section.SizeOfRawData) then
Exit;
if RangeChecks then
pSectionEndAddress^ := Image.Offset(Section.PointerToRawData +
Section.SizeOfRawData)
else
pSectionEndAddress^ := Pointer(UInt64(-1)); // No end expected
end;
end;
Result.Status := STATUS_SUCCESS;
except
Result.Location := 'RtlxExpandVirtualAddress';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxGetDirectoryEntryImage;
var
Header: PImageNtHeaders;
Bitness: TImageBitness;
NumberOfRvaAndSizes: Cardinal;
begin
// Reproduce RtlImageDirectoryEntryToData with more range checks
Result := RtlxGetImageNtHeader(Header, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
Result := RtlxGetImageBitness(Bitness, Image, Header, RangeChecks);
if not Result.IsSuccess then
Exit;
try
// Save the maximum directory index
if Bitness = ib64Bit then
NumberOfRvaAndSizes := Header.OptionalHeader64.NumberOfRvaAndSizes
else
NumberOfRvaAndSizes := Header.OptionalHeader32.NumberOfRvaAndSizes;
except
Result.Location := 'RtlxGetDirectoryEntryImage';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
Exit;
end;
if Cardinal(Entry) >= NumberOfRvaAndSizes then
begin
// Index is out of range
Directory := nil;
Exit;
end;
// Locate the directory
if Bitness = ib64Bit then
Directory := @Header.OptionalHeader64.DataDirectory[Entry]
else
Directory := @Header.OptionalHeader32.DataDirectory[Entry];
// Verify it
if RangeChecks and not CheckStruct(Image, Directory,
SizeOf(TImageDataDirectory)) then
begin
Result.Location := 'RtlxGetDirectoryEntryImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
end;
end;
function CaptureAnsiString(
const Image: TMemory;
[in] Start: PAnsiChar;
RangeChecks: Boolean = True
): AnsiString;
var
Finish, Boundary: PAnsiChar;
begin
Finish := Start;
if RangeChecks then
Boundary := Image.Offset(Image.Size)
else
Boundary := Pointer(UIntPtr(-1));
while (Finish < Boundary) and (Finish^ <> #0) do
Inc(Finish);
SetString(Result, Start, UIntPtr(Finish) - UIntPtr(Start));
end;
{ Export }
function RtlxEnumerateExportImage;
var
Header: PImageNtHeaders;
ExportData: PImageDataDirectory;
ExportDirectory: PImageExportDirectory;
Names, Functions: ^TAnysizeArray<Cardinal>;
Ordinals: ^TAnysizeArray<Word>;
i: Integer;
Name: PAnsiChar;
begin
try
Result := RtlxGetImageNtHeader(Header, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
// Find export directory data
Result := RtlxGetDirectoryEntryImage(ExportData, Image,
MappedAsImage, IMAGE_DIRECTORY_ENTRY_EXPORT, RangeChecks);
if not Result.IsSuccess then
Exit;
// Check if the image has any exports
if not Assigned(ExportData) or (ExportData.VirtualAddress = 0) then
begin
// Nothing to parse, exit
Entries := nil;
Exit;
end;
// Make sure export directory has appropriate size
if RangeChecks and (ExportData.Size < SizeOf(TImageExportDirectory)) then
begin
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
Exit;
end;
// Obtain a pointer to the export directory
Result := RtlxExpandVirtualAddress(Pointer(ExportDirectory), Image,
MappedAsImage, ExportData.VirtualAddress, ExportData.Size,
Header, RangeChecks);
if not Result.IsSuccess then
Exit;
// Verify names and ordinals array size
if RangeChecks and (ExportDirectory.NumberOfNames >
Cardinal(-1) div SizeOf(Cardinal)) then
begin
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INTEGER_OVERFLOW;
Exit;
end;
// Get the address of names
Result := RtlxExpandVirtualAddress(Pointer(Names), Image, MappedAsImage,
ExportDirectory.AddressOfNames, ExportDirectory.NumberOfNames *
SizeOf(Cardinal), Header, RangeChecks);
if not Result.IsSuccess then
Exit;
// Get an address of name ordinals
Result := RtlxExpandVirtualAddress(Pointer(Ordinals), Image, MappedAsImage,
ExportDirectory.AddressOfNameOrdinals, ExportDirectory.NumberOfNames *
SizeOf(Word), Header, RangeChecks);
if not Result.IsSuccess then
Exit;
// Ordinals can reference only up to 65k exported functions
if RangeChecks and (ExportDirectory.NumberOfFunctions > High(Word)) then
begin
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INTEGER_OVERFLOW;
Exit;
end;
// Get an address of functions
Result := RtlxExpandVirtualAddress(Pointer(Functions), Image, MappedAsImage,
ExportDirectory.AddressOfFunctions, ExportDirectory.NumberOfFunctions *
SizeOf(Cardinal), Header, RangeChecks);
if not Result.IsSuccess then
Exit;
// Fail with this status if something goes wrong
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
SetLength(Entries, ExportDirectory.NumberOfNames);
for i := 0 to High(Entries) do
begin
Entries[i].Ordinal := Ordinals{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF};
// Get a pointer to a name
Result := RtlxExpandVirtualAddress(Pointer(Name), Image, MappedAsImage,
Names{$R-}[i]{$IFDEF R+}{$R+}{$ENDIF}, 0, Header,
RangeChecks);
if not Result.IsSuccess then
Exit;
Entries[i].Name := CaptureAnsiString(Image, Name, RangeChecks);
// Each ordinal is an index inside an array of functions
if RangeChecks and (Entries[i].Ordinal >=
ExportDirectory.NumberOfFunctions) then
begin
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INTEGER_OVERFLOW;
Exit;
end;
Entries[i].VirtualAddress :=
Functions{$R-}[Ordinals[i]]{$IFDEF R+}{$R+}{$ENDIF};
// Forwarded functions have the virtual address in the same section as
// the export directory
Entries[i].Forwards := (Entries[i].VirtualAddress >=
ExportData.VirtualAddress) and (Entries[i].VirtualAddress <
UInt64(ExportData.VirtualAddress) + ExportData.Size);
if Entries[i].Forwards then
begin
// In case of forwarding the address actually points to the target name
Result := RtlxExpandVirtualAddress(Pointer(Name), Image, MappedAsImage,
Entries[i].VirtualAddress, 0, Header, RangeChecks);
if not Result.IsSuccess then
Exit;
Entries[i].ForwardsTo := CaptureAnsiString(Image, Name, RangeChecks);
end;
end;
except
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxFindExportedNameIndex;
begin
// Export entries are sorted, use fast case-sensitive binary search
Result := TArray.BinarySearchEx<TExportEntry>(Entries,
function (const Entry: TExportEntry): Integer
begin
Result := RtlxCompareAnsiStrings(Entry.Name, Name, True);
end
);
end;
{ Import }
const
IMAGE_DIRECTORY: array [TImportType] of TImageDirectoryEntry = (
IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT
);
DESCRIPTOR_SIZE: array [TImportType] of Cardinal = (
SizeOf(TImageImportDescriptor), SizeOf(TImageDelayLoadDescriptor)
);
IAT_ENTRY_SIZE: array [TImageBitness] of Cardinal = (
SizeOf(Cardinal), SizeOf(UInt64)
);
function RtlxpDumpImportTableFunctions(
out Functions: TArray<TImportEntry>;
const Image: TMemory;
MappedAsImage: Boolean;
TableRVA: Cardinal;
[in] Header: PImageNtHeaders;
ImportType: TImportType;
Bitness: TImageBitness;
RangeChecks: Boolean
): TNtxStatus;
var
UnboundIAT, UnboundIATStart, SectionEnd: Pointer;
ByName: PImageImportByName;
Count: Cardinal;
i: Integer;
begin
try
// Locate import name table
Result := RtlxExpandVirtualAddress(Pointer(UnboundIATStart),
Image, MappedAsImage, TableRVA, IAT_ENTRY_SIZE[Bitness], Header,
RangeChecks, @SectionEnd);
if not Result.IsSuccess then
Exit;
Count := 0;
UnboundIAT := UnboundIATStart;
Dec(PByte(SectionEnd), IAT_ENTRY_SIZE[Bitness]);
// Count number of functions
while ((Bitness = ib64Bit) and (UInt64(UnboundIAT^) <> 0)) or
((Bitness = ib32Bit) and (Cardinal(UnboundIAT^) <> 0)) do
begin
Inc(Count);
Inc(PByte(UnboundIAT), IAT_ENTRY_SIZE[Bitness]);
// Make sure the next element belongs to the same section
if RangeChecks and (UIntPtr(UnboundIAT) > UIntPtr(SectionEnd)) then
begin
Result.Location := 'RtlxpDumpImportTableFunctions';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
Exit;
end;
end;
UnboundIAT := UnboundIATStart;
SetLength(Functions, Count);
for i := 0 to High(Functions) do
with Functions[i] do
begin
DelayedImport := (ImportType = itDelayed);
if Bitness = ib64Bit then
ImportByName := UInt64(UnboundIAT^) and (UInt64(1) shl 63) = 0
else
ImportByName := Cardinal(UnboundIAT^) and (1 shl 31) = 0;
if ImportByName then
begin
// Locate function name
Result := RtlxExpandVirtualAddress(Pointer(ByName), Image,
MappedAsImage, Cardinal(UnboundIAT^), SizeOf(TImageImportByName),
Header, RangeChecks);
if not Result.IsSuccess then
Exit;
Name := CaptureAnsiString(Image, @ByName.Name[0], RangeChecks);
end
else
Ordinal := Word(UnboundIAT^); // Import by ordinal
Inc(PByte(UnboundIAT), IAT_ENTRY_SIZE[Bitness]);
end;
except
Result.Location := 'RtlxpDumpImportTableFunctions';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxpDumpImportTable(
out Entries: TArray<TImportDllEntry>;
const Image: TMemory;
MappedAsImage: Boolean;
[in] ImportData: PImageDataDirectory;
[in] Header: PImageNtHeaders;
ImportType: TImportType;
Bitness: TImageBitness;
RangeChecks: Boolean
): TNtxStatus;
var
ImportDescriptor: PImageImportDescriptor;
DelayImportDescriptor: PImageDelayLoadDescriptor absolute ImportDescriptor;
DescriptorsStart, DescriptorsEnd: Pointer;
Count: Cardinal;
i: Integer;
DllNameRVA, TableRVA: Cardinal;
pDllName: PAnsiChar;
begin
try
// Make sure import directory has appropriate size
if ImportData.Size < DESCRIPTOR_SIZE[ImportType] then
begin
Result.Location := 'RtlxpDumpImportTable';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
Exit;
end;
// Obtain a pointer to the import directory
Result := RtlxExpandVirtualAddress(Pointer(DescriptorsStart), Image,
MappedAsImage, ImportData.VirtualAddress, DESCRIPTOR_SIZE[ImportType],
Header, RangeChecks, @DescriptorsEnd);
if not Result.IsSuccess then
Exit;
Count := 0;
ImportDescriptor := DescriptorsStart;
Dec(PByte(DescriptorsEnd), DESCRIPTOR_SIZE[ImportType]);
// Count the number of descriptors
while ((ImportType = itNormal) and (ImportDescriptor.Name <> 0)) or
((ImportType = itDelayed) and (DelayImportDescriptor.DllNameRVA <> 0)) do
begin
Inc(Count);
// Move to the next DLL
if ImportType = itNormal then
Inc(ImportDescriptor)
else
Inc(DelayImportDescriptor);
// Make sure it is still within the image
if UIntPtr(ImportDescriptor) > UIntPtr(DescriptorsEnd) then
begin
Result.Location := 'RtlxpDumpImportTable';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
Exit;
end;
end;
ImportDescriptor := DescriptorsStart;
SetLength(Entries, Count);
for i := 0 to High(Entries) do
with Entries[i] do
begin
if ImportType = itNormal then
DllNameRVA := ImportDescriptor.Name
else
DllNameRVA := DelayImportDescriptor.DllNameRVA;
// Locate the DLL name string
Result := RtlxExpandVirtualAddress(Pointer(pDllName), Image,
MappedAsImage, DllNameRVA, SizeOf(AnsiChar), Header, RangeChecks);
if not Result.IsSuccess then
Exit;
// Save DLL name and IAT RVA
DllName := CaptureAnsiString(Image, pDllName, RangeChecks);
if ImportType = itNormal then
begin
IAT := ImportDescriptor.FirstThunk;
TableRVA := ImportDescriptor.OriginalFirstThunk;
end
else
begin
IAT := DelayImportDescriptor.ImportAddressTableRVA;
TableRVA := DelayImportDescriptor.ImportNameTableRVA;
end;
// Save all functions from the descriptor
Result := RtlxpDumpImportTableFunctions(Functions, Image, MappedAsImage,
TableRVA, Header, ImportType, Bitness, RangeChecks);
if not Result.IsSuccess then
Exit;
// Move to the next DLL
if ImportType = itNormal then
Inc(ImportDescriptor)
else
Inc(DelayImportDescriptor);
end;
except
Result.Location := 'RtlxpDumpImportTable';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
// A worker function for enumerating image import
function RtlxpEnumerateImportImage(
out Entries: TArray<TImportDllEntry>;
const Image: TMemory;
MappedAsImage: Boolean;
ImportType: TImportType;
RangeChecks: Boolean
): TNtxStatus;
var
Header: PImageNtHeaders;
ImportData: PImageDataDirectory;
Bitness: TImageBitness;
begin
try
Result := RtlxGetImageNtHeader(Header, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
// Find import directory data
Result := RtlxGetDirectoryEntryImage(ImportData, Image, MappedAsImage,
IMAGE_DIRECTORY[ImportType], RangeChecks);
if not Result.IsSuccess then
Exit;
// Check if the image has any imports
if not Assigned(ImportData) or (ImportData.VirtualAddress = 0) then
begin
// Nothing to parse, exit
Entries := nil;
Exit;
end;
// The structure of import depends on image bitness
Result := RtlxGetImageBitness(Bitness, Image, Header, RangeChecks);
if not Result.IsSuccess then
Exit;
Result := RtlxpDumpImportTable(Entries, Image, MappedAsImage, ImportData,
Header, ImportType, Bitness, RangeChecks);
except
Result.Location := 'RtlxEnumerateImportImage';
Result.Status := STATUS_UNHANDLED_EXCEPTION;
end;
end;
function RtlxEnumerateImportImage;
var
PerTypeEntries: TArray<TImportDllEntry>;
ImportType: TImportType;
begin
if ImportTypes - [itNormal, itDelayed] <> [] then
begin
Result.Location := 'RtlxEnumerateImportImage';
Result.Status := STATUS_INVALID_PARAMETER;
Exit;
end;
Entries := nil;
for ImportType in ImportTypes do
begin
Result := RtlxpEnumerateImportImage(PerTypeEntries, Image, MappedAsImage,
ImportType, RangeChecks);
if not Result.IsSuccess then
begin
Entries := nil;
Exit;
end;
Entries := Entries + PerTypeEntries;
end;
end;
{ Relocations }
function RtlxRelocateImage;
var
NtHeaders: PImageNtHeaders;
Bitness: TImageBitness;
RelocationDelta: UInt64;
RelocDirectory: PImageDataDirectory;
Entry: PImageBaseRelocation;
DirectoryEnd, TargetPage, Target, TargetBoundary: Pointer;
TargetSize: Cardinal;
TypeOffset: PImageRelocationTypeOffset;
ProtectionReverter, NextPageProtectionReverter: IAutoReleasable;
begin
try
Result := RtlxGetImageNtHeader(NtHeaders, Image, RangeChecks);
if not Result.IsSuccess then
Exit;
Result := RtlxGetImageBitness(Bitness, Image, NtHeaders, RangeChecks);
if not Result.IsSuccess then
Exit;
Result.Location := 'RtlxRelocateImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
if RangeChecks then
case Bitness of
ib32Bit:
if not CheckStruct(Image, @NtHeaders.OptionalHeader32.ImageBase,
SizeOf(Cardinal)) then
Exit;
ib64Bit:
if not CheckStruct(Image, @NtHeaders.OptionalHeader64.ImageBase,