-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathldrapi.c
1667 lines (1459 loc) · 47.6 KB
/
ldrapi.c
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
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS NT User Mode Library
* FILE: dll/ntdll/ldr/ldrapi.c
* PURPOSE: PE Loader Public APIs
* PROGRAMMERS: Alex Ionescu ([email protected])
* Aleksey Bragin ([email protected])
*/
/* INCLUDES *****************************************************************/
#include <ntdll.h>
#define NDEBUG
#include <debug.h>
/* GLOBALS *******************************************************************/
LIST_ENTRY LdrpUnloadHead;
LONG LdrpLoaderLockAcquisitionCount;
BOOLEAN LdrpShowRecursiveLoads, LdrpBreakOnRecursiveDllLoads;
UNICODE_STRING LdrApiDefaultExtension = RTL_CONSTANT_STRING(L".DLL");
ULONG AlternateResourceModuleCount;
extern PLDR_MANIFEST_PROBER_ROUTINE LdrpManifestProberRoutine;
/* FUNCTIONS *****************************************************************/
NTSTATUS
NTAPI
LdrFindCreateProcessManifest(IN ULONG Flags,
IN PVOID Image,
IN PVOID IdPath,
IN ULONG IdPathLength,
IN PVOID OutDataEntry)
{
UNIMPLEMENTED;
return STATUS_NOT_IMPLEMENTED;
}
NTSTATUS
NTAPI
LdrDestroyOutOfProcessImage(IN PVOID Image)
{
UNIMPLEMENTED;
return STATUS_NOT_IMPLEMENTED;
}
NTSTATUS
NTAPI
LdrCreateOutOfProcessImage(IN ULONG Flags,
IN HANDLE ProcessHandle,
IN HANDLE DllHandle,
IN PVOID Unknown3)
{
UNIMPLEMENTED;
return STATUS_NOT_IMPLEMENTED;
}
NTSTATUS
NTAPI
LdrAccessOutOfProcessResource(IN PVOID Unknown,
IN PVOID Image,
IN PVOID Unknown1,
IN PVOID Unknown2,
IN PVOID Unknown3)
{
UNIMPLEMENTED;
return STATUS_NOT_IMPLEMENTED;
}
VOID
NTAPI
LdrSetDllManifestProber(
_In_ PLDR_MANIFEST_PROBER_ROUTINE Routine)
{
LdrpManifestProberRoutine = Routine;
}
BOOLEAN
NTAPI
LdrAlternateResourcesEnabled(VOID)
{
/* ReactOS does not support this */
return FALSE;
}
FORCEINLINE
ULONG_PTR
LdrpMakeCookie(VOID)
{
/* Generate a cookie */
return (((ULONG_PTR)NtCurrentTeb()->RealClientId.UniqueThread & 0xFFF) << 16) |
(_InterlockedIncrement(&LdrpLoaderLockAcquisitionCount) & 0xFFFF);
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrUnlockLoaderLock(
_In_ ULONG Flags,
_In_opt_ ULONG_PTR Cookie)
{
NTSTATUS Status = STATUS_SUCCESS;
DPRINT("LdrUnlockLoaderLock(%x %Ix)\n", Flags, Cookie);
/* Check for valid flags */
if (Flags & ~LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* Flags are invalid, check how to fail */
if (Flags & LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* The caller wants us to raise status */
RtlRaiseStatus(STATUS_INVALID_PARAMETER_1);
}
/* A normal failure */
return STATUS_INVALID_PARAMETER_1;
}
/* If we don't have a cookie, just return */
if (!Cookie) return STATUS_SUCCESS;
/* Validate the cookie */
if ((Cookie & 0xF0000000) ||
((Cookie >> 16) ^ (HandleToUlong(NtCurrentTeb()->RealClientId.UniqueThread) & 0xFFF)))
{
DPRINT1("LdrUnlockLoaderLock() called with an invalid cookie!\n");
/* Invalid cookie, check how to fail */
if (Flags & LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* The caller wants us to raise status */
RtlRaiseStatus(STATUS_INVALID_PARAMETER_2);
}
/* A normal failure */
return STATUS_INVALID_PARAMETER_2;
}
/* Ready to release the lock */
if (Flags & LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* Do a direct leave */
RtlLeaveCriticalSection(&LdrpLoaderLock);
}
else
{
/* Wrap this in SEH, since we're not supposed to raise */
_SEH2_TRY
{
/* Leave the lock */
RtlLeaveCriticalSection(&LdrpLoaderLock);
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
/* We should use the LDR Filter instead */
Status = _SEH2_GetExceptionCode();
}
_SEH2_END;
}
/* All done */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrLockLoaderLock(
_In_ ULONG Flags,
_Out_opt_ PULONG Disposition,
_Out_opt_ PULONG_PTR Cookie)
{
NTSTATUS Status = STATUS_SUCCESS;
BOOLEAN InInit = LdrpInLdrInit;
DPRINT("LdrLockLoaderLock(%x %p %p)\n", Flags, Disposition, Cookie);
/* Zero out the outputs */
if (Disposition) *Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_INVALID;
if (Cookie) *Cookie = 0;
/* Validate the flags */
if (Flags & ~(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS |
LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY))
{
/* Flags are invalid, check how to fail */
if (Flags & LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* The caller wants us to raise status */
RtlRaiseStatus(STATUS_INVALID_PARAMETER_1);
}
/* A normal failure */
return STATUS_INVALID_PARAMETER_1;
}
/* Make sure we got a cookie */
if (!Cookie)
{
/* No cookie check how to fail */
if (Flags & LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* The caller wants us to raise status */
RtlRaiseStatus(STATUS_INVALID_PARAMETER_3);
}
/* A normal failure */
return STATUS_INVALID_PARAMETER_3;
}
/* If the flag is set, make sure we have a valid pointer to use */
if ((Flags & LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY) && !(Disposition))
{
/* No pointer to return the data to */
if (Flags & LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* The caller wants us to raise status */
RtlRaiseStatus(STATUS_INVALID_PARAMETER_2);
}
/* Fail */
return STATUS_INVALID_PARAMETER_2;
}
/* Return now if we are in the init phase */
if (InInit) return STATUS_SUCCESS;
/* Check what locking semantic to use */
if (Flags & LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS)
{
/* Check if we should enter or simply try */
if (Flags & LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY)
{
/* Do a try */
if (!RtlTryEnterCriticalSection(&LdrpLoaderLock))
{
/* It's locked */
*Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED;
}
else
{
/* It worked */
*Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED;
*Cookie = LdrpMakeCookie();
}
}
else
{
/* Do a enter */
RtlEnterCriticalSection(&LdrpLoaderLock);
/* See if result was requested */
if (Disposition) *Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED;
*Cookie = LdrpMakeCookie();
}
}
else
{
/* Wrap this in SEH, since we're not supposed to raise */
_SEH2_TRY
{
/* Check if we should enter or simply try */
if (Flags & LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY)
{
/* Do a try */
if (!RtlTryEnterCriticalSection(&LdrpLoaderLock))
{
/* It's locked */
*Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED;
}
else
{
/* It worked */
*Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED;
*Cookie = LdrpMakeCookie();
}
}
else
{
/* Do an enter */
RtlEnterCriticalSection(&LdrpLoaderLock);
/* See if result was requested */
if (Disposition) *Disposition = LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED;
*Cookie = LdrpMakeCookie();
}
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
/* We should use the LDR Filter instead */
Status = _SEH2_GetExceptionCode();
}
_SEH2_END;
}
/* Return status */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
DECLSPEC_HOTPATCH
LdrLoadDll(
_In_opt_ PWSTR SearchPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_ PVOID *BaseAddress)
{
WCHAR StringBuffer[MAX_PATH];
UNICODE_STRING StaticString, DynamicString;
BOOLEAN RedirectedDll = FALSE;
NTSTATUS Status;
ULONG_PTR Cookie;
PUNICODE_STRING OldTldDll;
PTEB Teb = NtCurrentTeb();
/* Initialize the strings */
RtlInitEmptyUnicodeString(&StaticString, StringBuffer, sizeof(StringBuffer));
RtlInitEmptyUnicodeString(&DynamicString, NULL, 0);
Status = LdrpApplyFileNameRedirection(DllName, &LdrApiDefaultExtension, &StaticString, &DynamicString, &DllName, &RedirectedDll);
/* Lock the loader lock */
LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS, NULL, &Cookie);
/* Check if there's a TLD DLL being loaded */
OldTldDll = LdrpTopLevelDllBeingLoaded;
_SEH2_TRY
{
if (OldTldDll)
{
/* This is a recursive load, do something about it? */
if ((ShowSnaps) || (LdrpShowRecursiveLoads) || (LdrpBreakOnRecursiveDllLoads))
{
/* Print out debug messages */
DPRINT1("[%p, %p] LDR: Recursive DLL Load\n",
Teb->RealClientId.UniqueProcess,
Teb->RealClientId.UniqueThread);
DPRINT1("[%p, %p] Previous DLL being loaded \"%wZ\"\n",
Teb->RealClientId.UniqueProcess,
Teb->RealClientId.UniqueThread,
OldTldDll);
DPRINT1("[%p, %p] DLL being requested \"%wZ\"\n",
Teb->RealClientId.UniqueProcess,
Teb->RealClientId.UniqueThread,
DllName);
/* Was it initializing too? */
if (!LdrpCurrentDllInitializer)
{
DPRINT1("[%p, %p] LDR: No DLL Initializer was running\n",
Teb->RealClientId.UniqueProcess,
Teb->RealClientId.UniqueThread);
}
else
{
DPRINT1("[%p, %p] DLL whose initializer was currently running \"%wZ\"\n",
Teb->ClientId.UniqueProcess,
Teb->ClientId.UniqueThread,
&LdrpCurrentDllInitializer->BaseDllName);
}
}
}
/* Set this one as the TLD DLL being loaded*/
LdrpTopLevelDllBeingLoaded = DllName;
/* Load the DLL */
Status = LdrpLoadDll(RedirectedDll,
SearchPath,
DllCharacteristics,
DllName,
BaseAddress,
TRUE);
if (NT_SUCCESS(Status))
{
Status = STATUS_SUCCESS;
}
else if ((Status != STATUS_NO_SUCH_FILE) &&
(Status != STATUS_DLL_NOT_FOUND) &&
(Status != STATUS_OBJECT_NAME_NOT_FOUND) &&
(Status != STATUS_DLL_INIT_FAILED))
{
DbgPrintEx(DPFLTR_LDR_ID,
DPFLTR_WARNING_LEVEL,
"LDR: %s - failing because LdrpLoadDll(%wZ) returned status %x\n",
__FUNCTION__,
DllName,
Status);
}
}
_SEH2_FINALLY
{
/* Restore the old TLD DLL */
LdrpTopLevelDllBeingLoaded = OldTldDll;
/* Release the lock */
LdrUnlockLoaderLock(LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS, Cookie);
}
_SEH2_END;
/* Do we have a redirect string? */
if (DynamicString.Buffer)
RtlFreeUnicodeString(&DynamicString);
/* Return */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrFindEntryForAddress(
_In_ PVOID Address,
_Out_ PLDR_DATA_TABLE_ENTRY *Module)
{
PLIST_ENTRY ListHead, NextEntry;
PLDR_DATA_TABLE_ENTRY LdrEntry;
PIMAGE_NT_HEADERS NtHeader;
PPEB_LDR_DATA Ldr = NtCurrentPeb()->Ldr;
ULONG_PTR DllBase, DllEnd;
DPRINT("LdrFindEntryForAddress(Address %p)\n", Address);
/* Nothing to do */
if (!Ldr) return STATUS_NO_MORE_ENTRIES;
/* Get the current entry */
LdrEntry = Ldr->EntryInProgress;
if (LdrEntry)
{
/* Get the NT Headers */
NtHeader = RtlImageNtHeader(LdrEntry->DllBase);
if (NtHeader)
{
/* Get the Image Base */
DllBase = (ULONG_PTR)LdrEntry->DllBase;
DllEnd = DllBase + NtHeader->OptionalHeader.SizeOfImage;
/* Check if they match */
if (((ULONG_PTR)Address >= DllBase) &&
((ULONG_PTR)Address < DllEnd))
{
/* Return it */
*Module = LdrEntry;
return STATUS_SUCCESS;
}
}
}
/* Loop the module list */
ListHead = &Ldr->InMemoryOrderModuleList;
NextEntry = ListHead->Flink;
while (NextEntry != ListHead)
{
/* Get the entry and NT Headers */
LdrEntry = CONTAINING_RECORD(NextEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
NtHeader = RtlImageNtHeader(LdrEntry->DllBase);
if (NtHeader)
{
/* Get the Image Base */
DllBase = (ULONG_PTR)LdrEntry->DllBase;
DllEnd = DllBase + NtHeader->OptionalHeader.SizeOfImage;
/* Check if they match */
if (((ULONG_PTR)Address >= DllBase) &&
((ULONG_PTR)Address < DllEnd))
{
/* Return it */
*Module = LdrEntry;
return STATUS_SUCCESS;
}
/* Next Entry */
NextEntry = NextEntry->Flink;
}
}
/* Nothing found */
DbgPrintEx(DPFLTR_LDR_ID,
DPFLTR_WARNING_LEVEL,
"LDR: %s() exiting 0x%08lx\n",
__FUNCTION__,
STATUS_NO_MORE_ENTRIES);
return STATUS_NO_MORE_ENTRIES;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrGetDllHandleEx(
_In_ ULONG Flags,
_In_opt_ PWSTR DllPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_opt_ PVOID *DllHandle)
{
NTSTATUS Status;
PLDR_DATA_TABLE_ENTRY LdrEntry;
UNICODE_STRING RedirectName, DynamicString, RawDllName;
PUNICODE_STRING pRedirectName, CompareName;
PWCHAR p1, p2, p3;
BOOLEAN Locked, RedirectedDll;
ULONG_PTR Cookie;
ULONG LoadFlag, Length;
/* Initialize the strings */
RtlInitEmptyUnicodeString(&DynamicString, NULL, 0);
RtlInitEmptyUnicodeString(&RawDllName, NULL, 0);
RedirectName = *DllName;
pRedirectName = &RedirectName;
/* Initialize state */
RedirectedDll = Locked = FALSE;
LdrEntry = NULL;
Cookie = 0;
/* Clear the handle */
if (DllHandle) *DllHandle = NULL;
/* Check for a valid flag combination */
if ((Flags & ~(LDR_GET_DLL_HANDLE_EX_PIN | LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT)) ||
(!DllHandle && !(Flags & LDR_GET_DLL_HANDLE_EX_PIN)))
{
DPRINT1("Flags are invalid or no DllHandle given\n");
Status = STATUS_INVALID_PARAMETER;
goto Quickie;
}
/* If not initializing */
if (!LdrpInLdrInit)
{
/* Acquire the lock */
Status = LdrLockLoaderLock(0, NULL, &Cookie);
if (!NT_SUCCESS(Status)) goto Quickie;
/* Remember we own it */
Locked = TRUE;
}
Status = LdrpApplyFileNameRedirection(
pRedirectName, &LdrApiDefaultExtension, NULL, &DynamicString, &pRedirectName, &RedirectedDll);
if (!NT_SUCCESS(Status))
{
DPRINT1("LdrpApplyFileNameRedirection FAILED: (Status 0x%x)\n", Status);
goto Quickie;
}
/* Set default failure code */
Status = STATUS_DLL_NOT_FOUND;
/* Use the cache if we can */
if (LdrpGetModuleHandleCache)
{
/* Check if we were redirected */
if (RedirectedDll)
{
/* Check the flag */
if (!(LdrpGetModuleHandleCache->Flags & LDRP_REDIRECTED))
{
goto DontCompare;
}
/* Use the right name */
CompareName = &LdrpGetModuleHandleCache->FullDllName;
}
else
{
/* Check the flag */
if (LdrpGetModuleHandleCache->Flags & LDRP_REDIRECTED)
{
goto DontCompare;
}
/* Use the right name */
CompareName = &LdrpGetModuleHandleCache->BaseDllName;
}
/* Check if the name matches */
if (RtlEqualUnicodeString(pRedirectName,
CompareName,
TRUE))
{
/* Skip the rest */
LdrEntry = LdrpGetModuleHandleCache;
/* Return success */
Status = STATUS_SUCCESS;
goto Quickie;
}
}
DontCompare:
/* Find the name without the extension */
p1 = pRedirectName->Buffer;
p2 = NULL;
p3 = &p1[pRedirectName->Length / sizeof(WCHAR)];
while (p1 != p3)
{
if (*p1++ == L'.')
{
p2 = p1;
}
else if (*p1 == L'\\')
{
p2 = NULL;
}
}
/* Check if no extension was found or if we got a slash */
if (!(p2) || (*p2 == L'\\') || (*p2 == L'/'))
{
/* Check that we have space to add one */
Length = pRedirectName->Length +
LdrApiDefaultExtension.Length + sizeof(UNICODE_NULL);
if (Length >= UNICODE_STRING_MAX_BYTES)
{
/* No space to add the extension */
Status = STATUS_NAME_TOO_LONG;
goto Quickie;
}
/* Setup the string */
RawDllName.MaximumLength = Length;
ASSERT(Length >= sizeof(UNICODE_NULL));
RawDllName.Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
0,
RawDllName.MaximumLength);
if (!RawDllName.Buffer)
{
Status = STATUS_NO_MEMORY;
goto Quickie;
}
/* Copy the string and add extension */
RtlCopyUnicodeString(&RawDllName, pRedirectName);
RtlAppendUnicodeStringToString(&RawDllName, &LdrApiDefaultExtension);
}
else
{
/* Check if there's something in the name */
Length = pRedirectName->Length;
if (Length)
{
/* Check and remove trailing period */
if (pRedirectName->Buffer[Length / sizeof(WCHAR) - sizeof(ANSI_NULL)] == '.')
{
/* Decrease the size */
pRedirectName->Length -= sizeof(WCHAR);
}
}
/* Setup the string */
RawDllName.MaximumLength = pRedirectName->Length + sizeof(WCHAR);
RawDllName.Buffer = RtlAllocateHeap(RtlGetProcessHeap(),
0,
RawDllName.MaximumLength);
if (!RawDllName.Buffer)
{
Status = STATUS_NO_MEMORY;
goto Quickie;
}
/* Copy the string */
RtlCopyUnicodeString(&RawDllName, pRedirectName);
}
/* Display debug string */
if (ShowSnaps)
{
DPRINT1("LDR: LdrGetDllHandleEx, searching for %wZ from %ws\n",
&RawDllName,
DllPath ? ((ULONG_PTR)DllPath == 1 ? L"" : DllPath) : L"");
}
/* Do the lookup */
if (LdrpCheckForLoadedDll(DllPath,
&RawDllName,
((ULONG_PTR)DllPath == 1) ? TRUE : FALSE,
RedirectedDll,
&LdrEntry))
{
/* Update cached entry */
LdrpGetModuleHandleCache = LdrEntry;
/* Return success */
Status = STATUS_SUCCESS;
}
else
{
/* Make sure to NULL this */
LdrEntry = NULL;
}
Quickie:
/* The success path must have a valid loader entry */
ASSERT((LdrEntry != NULL) == NT_SUCCESS(Status));
/* Check if we got an entry and success */
DPRINT("Got LdrEntry->BaseDllName %wZ\n", LdrEntry ? &LdrEntry->BaseDllName : NULL);
if ((LdrEntry) && (NT_SUCCESS(Status)))
{
/* Check if the DLL is locked */
if ((LdrEntry->LoadCount != 0xFFFF) &&
!(Flags & LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT))
{
/* Check what to do with the load count */
if (Flags & LDR_GET_DLL_HANDLE_EX_PIN)
{
/* Pin it */
LdrEntry->LoadCount = 0xFFFF;
LoadFlag = LDRP_UPDATE_PIN;
}
else
{
/* Increase the load count */
LdrEntry->LoadCount++;
LoadFlag = LDRP_UPDATE_REFCOUNT;
}
/* Update the load count now */
LdrpUpdateLoadCount2(LdrEntry, LoadFlag);
LdrpClearLoadInProgress();
}
/* Check if the caller is requesting the handle */
if (DllHandle) *DllHandle = LdrEntry->DllBase;
}
/* Free string if needed */
if (DynamicString.Buffer) RtlFreeUnicodeString(&DynamicString);
/* Free the raw DLL Name if needed */
if (RawDllName.Buffer)
{
/* Free the heap-allocated buffer */
RtlFreeHeap(RtlGetProcessHeap(), 0, RawDllName.Buffer);
RawDllName.Buffer = NULL;
}
/* Release lock */
if (Locked)
{
LdrUnlockLoaderLock(LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS,
Cookie);
}
/* Return */
return Status;
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrGetDllHandle(
_In_opt_ PWSTR DllPath,
_In_opt_ PULONG DllCharacteristics,
_In_ PUNICODE_STRING DllName,
_Out_ PVOID *DllHandle)
{
/* Call the newer API */
return LdrGetDllHandleEx(LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT,
DllPath,
DllCharacteristics,
DllName,
DllHandle);
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrGetProcedureAddress(
_In_ PVOID BaseAddress,
_In_opt_ _When_(Ordinal == 0, _Notnull_) PANSI_STRING Name,
_In_opt_ _When_(Name == NULL, _In_range_(>, 0)) ULONG Ordinal,
_Out_ PVOID *ProcedureAddress)
{
/* Call the internal routine and tell it to execute DllInit */
return LdrpGetProcedureAddress(BaseAddress, Name, Ordinal, ProcedureAddress, TRUE);
}
/*
* @implemented
*/
NTSTATUS
NTAPI
LdrVerifyImageMatchesChecksum(
_In_ HANDLE FileHandle,
_In_ PLDR_CALLBACK Callback,
_In_ PVOID CallbackContext,
_Out_ PUSHORT ImageCharacteristics)
{
FILE_STANDARD_INFORMATION FileStandardInfo;
PIMAGE_IMPORT_DESCRIPTOR ImportData;
PIMAGE_SECTION_HEADER LastSection = NULL;
IO_STATUS_BLOCK IoStatusBlock;
PIMAGE_NT_HEADERS NtHeader;
HANDLE SectionHandle;
SIZE_T ViewSize;
PVOID ViewBase;
BOOLEAN Result, NoActualCheck;
NTSTATUS Status;
PVOID ImportName;
ULONG Size;
DPRINT("LdrVerifyImageMatchesChecksum() called\n");
/* If the handle has the magic KnownDll flag, skip actual checksums */
NoActualCheck = ((ULONG_PTR)FileHandle & 1);
/* Create the section */
Status = NtCreateSection(&SectionHandle,
SECTION_MAP_EXECUTE,
NULL,
NULL,
PAGE_EXECUTE,
SEC_COMMIT,
FileHandle);
if (!NT_SUCCESS(Status))
{
DPRINT1 ("NtCreateSection() failed (Status 0x%x)\n", Status);
return Status;
}
/* Map the section */
ViewSize = 0;
ViewBase = NULL;
Status = NtMapViewOfSection(SectionHandle,
NtCurrentProcess(),
&ViewBase,
0,
0,
NULL,
&ViewSize,
ViewShare,
0,
PAGE_EXECUTE);
if (!NT_SUCCESS(Status))
{
DPRINT1("NtMapViewOfSection() failed (Status 0x%x)\n", Status);
NtClose(SectionHandle);
return Status;
}
/* Get the file information */
Status = NtQueryInformationFile(FileHandle,
&IoStatusBlock,
&FileStandardInfo,
sizeof(FILE_STANDARD_INFORMATION),
FileStandardInformation);
if (!NT_SUCCESS(Status))
{
DPRINT1("NtMapViewOfSection() failed (Status 0x%x)\n", Status);
NtUnmapViewOfSection(NtCurrentProcess(), ViewBase);
NtClose(SectionHandle);
return Status;
}
/* Protect with SEH */
_SEH2_TRY
{
/* Check if this is the KnownDll hack */
if (NoActualCheck)
{
/* Don't actually do it */
Result = TRUE;
}
else
{
/* Verify the checksum */
Result = LdrVerifyMappedImageMatchesChecksum(ViewBase,
FileStandardInfo.EndOfFile.LowPart,
FileStandardInfo.EndOfFile.LowPart);
}
/* Check if a callback was supplied */
if ((Result) && (Callback))
{
/* Get the NT Header */
NtHeader = RtlImageNtHeader(ViewBase);
/* Check if caller requested this back */
if (ImageCharacteristics)
{
/* Return to caller */
*ImageCharacteristics = NtHeader->FileHeader.Characteristics;
}
/* Get the Import Directory Data */
ImportData = RtlImageDirectoryEntryToData(ViewBase,
FALSE,
IMAGE_DIRECTORY_ENTRY_IMPORT,
&Size);
/* Make sure there is one */
if (ImportData)
{
/* Loop the imports */
while (ImportData->Name)
{
/* Get the name */
ImportName = RtlImageRvaToVa(NtHeader,
ViewBase,
ImportData->Name,
&LastSection);
/* Notify the callback */
Callback(CallbackContext, ImportName);
ImportData++;
}
}
}
}
_SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
{
/* Fail the request returning STATUS_IMAGE_CHECKSUM_MISMATCH */
Result = FALSE;
}
_SEH2_END;
/* Unmap file and close handle */
NtUnmapViewOfSection(NtCurrentProcess(), ViewBase);
NtClose(SectionHandle);
/* Return status */
return Result ? Status : STATUS_IMAGE_CHECKSUM_MISMATCH;
}
NTSTATUS
NTAPI
LdrQueryProcessModuleInformationEx(
_In_opt_ ULONG ProcessId,
_Reserved_ ULONG Reserved,
_Out_writes_bytes_to_(Size, *ReturnedSize) PRTL_PROCESS_MODULES ModuleInformation,
_In_ ULONG Size,
_Out_opt_ PULONG ReturnedSize)
{
PLIST_ENTRY ModuleListHead, InitListHead;
PLIST_ENTRY Entry, InitEntry;
PLDR_DATA_TABLE_ENTRY Module, InitModule;
PRTL_PROCESS_MODULE_INFORMATION ModulePtr = NULL;
NTSTATUS Status = STATUS_SUCCESS;
ULONG UsedSize = FIELD_OFFSET(RTL_PROCESS_MODULES, Modules);
ANSI_STRING AnsiString;
PCHAR p;
DPRINT("LdrQueryProcessModuleInformation() called\n");
/* Acquire loader lock */
RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock);
_SEH2_TRY
{
/* Check if we were given enough space */
if (Size < UsedSize)
{
Status = STATUS_INFO_LENGTH_MISMATCH;
}
else
{
ModuleInformation->NumberOfModules = 0;
ModulePtr = &ModuleInformation->Modules[0];
Status = STATUS_SUCCESS;
}
/* Traverse the list of modules */
ModuleListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
Entry = ModuleListHead->Flink;
while (Entry != ModuleListHead)
{
Module = CONTAINING_RECORD(Entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
DPRINT(" Module %wZ\n", &Module->FullDllName);
/* Increase the used size */
UsedSize += sizeof(RTL_PROCESS_MODULE_INFORMATION);
if (UsedSize > Size)
{
Status = STATUS_INFO_LENGTH_MISMATCH;
}
else
{