2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/sysldr.c
5 * PURPOSE: Contains the Kernel Loader (SYSLDR) for loading PE files.
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * ReactOS Portable Systems Group
10 /* INCLUDES *******************************************************************/
16 #line 16 "ARMĀ³::LOADER"
17 #define MODULE_INVOLVED_IN_ARM3
18 #include "../ARM3/miarm.h"
20 /* GCC's incompetence strikes again */
23 sprintf_nt(IN PCHAR Buffer
,
29 vsprintf(Buffer
, Format
, ap
);
33 /* GLOBALS ********************************************************************/
35 LIST_ENTRY PsLoadedModuleList
;
36 LIST_ENTRY MmLoadedUserImageList
;
37 KSPIN_LOCK PsLoadedModuleSpinLock
;
38 ERESOURCE PsLoadedModuleResource
;
39 ULONG_PTR PsNtosImageBase
;
40 KMUTANT MmSystemLoadLock
;
42 PFN_NUMBER MmTotalSystemDriverPages
;
44 PVOID MmUnloadedDrivers
;
45 PVOID MmLastUnloadedDrivers
;
47 BOOLEAN MmMakeLowMemory
;
48 BOOLEAN MmEnforceWriteProtection
= TRUE
;
50 PMMPTE MiKernelResourceStartPte
, MiKernelResourceEndPte
;
51 ULONG_PTR ExPoolCodeStart
, ExPoolCodeEnd
, MmPoolCodeStart
, MmPoolCodeEnd
;
52 ULONG_PTR MmPteCodeStart
, MmPteCodeEnd
;
54 /* FUNCTIONS ******************************************************************/
58 MiCacheImageSymbols(IN PVOID BaseAddress
)
61 PVOID DebugDirectory
= NULL
;
64 /* Make sure it's safe to access the image */
67 /* Get the debug directory */
68 DebugDirectory
= RtlImageDirectoryEntryToData(BaseAddress
,
70 IMAGE_DIRECTORY_ENTRY_DEBUG
,
73 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
79 /* Return the directory */
80 return DebugDirectory
;
85 MiLoadImageSection(IN OUT PVOID
*SectionPtr
,
87 IN PUNICODE_STRING FileName
,
88 IN BOOLEAN SessionLoad
,
89 IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
91 PROS_SECTION_OBJECT Section
= *SectionPtr
;
97 LARGE_INTEGER SectionOffset
= {{0, 0}};
98 BOOLEAN LoadSymbols
= FALSE
;
100 PMMPTE PointerPte
, LastPte
;
105 /* Detect session load */
109 DPRINT1("Session loading not yet supported!\n");
113 /* Not session load, shouldn't have an entry */
114 ASSERT(LdrEntry
== NULL
);
116 /* Attach to the system process */
117 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
119 /* Check if we need to load symbols */
120 if (NtGlobalFlag
& FLG_ENABLE_KDEBUG_SYMBOL_LOAD
)
124 NtGlobalFlag
&= ~FLG_ENABLE_KDEBUG_SYMBOL_LOAD
;
128 Process
= PsGetCurrentProcess();
129 Status
= MmMapViewOfSection(Section
,
140 /* Re-enable the flag */
141 if (LoadSymbols
) NtGlobalFlag
|= FLG_ENABLE_KDEBUG_SYMBOL_LOAD
;
143 /* Check if we failed with distinguished status code */
144 if (Status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
)
146 /* Change it to something more generic */
147 Status
= STATUS_INVALID_IMAGE_FORMAT
;
150 /* Now check if we failed */
151 if (!NT_SUCCESS(Status
))
153 /* Detach and return */
154 KeUnstackDetachProcess(&ApcState
);
158 /* Reserve system PTEs needed */
159 PteCount
= ROUND_TO_PAGES(Section
->ImageSection
->ImageSize
) >> PAGE_SHIFT
;
160 PointerPte
= MiReserveSystemPtes(PteCount
, SystemPteSpace
);
161 if (!PointerPte
) return STATUS_INSUFFICIENT_RESOURCES
;
163 /* New driver base */
164 LastPte
= PointerPte
+ PteCount
;
165 DriverBase
= MiPteToAddress(PointerPte
);
167 /* The driver is here */
168 *ImageBase
= DriverBase
;
170 /* Loop the new driver PTEs */
171 TempPte
= ValidKernelPte
;
172 while (PointerPte
< LastPte
)
174 /* Allocate a page */
175 TempPte
.u
.Hard
.PageFrameNumber
= MiAllocatePfn(PointerPte
, MM_EXECUTE
);
178 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
185 RtlCopyMemory(DriverBase
, Base
, PteCount
<< PAGE_SHIFT
);
187 /* Now unmap the view */
188 Status
= MmUnmapViewOfSection(Process
, Base
);
189 ASSERT(NT_SUCCESS(Status
));
191 /* Detach and return status */
192 KeUnstackDetachProcess(&ApcState
);
198 MiLocateExportName(IN PVOID DllBase
,
202 PUSHORT OrdinalTable
;
203 PIMAGE_EXPORT_DIRECTORY ExportDirectory
;
204 LONG Low
= 0, Mid
= 0, High
, Ret
;
211 /* Get the export directory */
212 ExportDirectory
= RtlImageDirectoryEntryToData(DllBase
,
214 IMAGE_DIRECTORY_ENTRY_EXPORT
,
216 if (!ExportDirectory
) return NULL
;
218 /* Setup name tables */
219 NameTable
= (PULONG
)((ULONG_PTR
)DllBase
+
220 ExportDirectory
->AddressOfNames
);
221 OrdinalTable
= (PUSHORT
)((ULONG_PTR
)DllBase
+
222 ExportDirectory
->AddressOfNameOrdinals
);
224 /* Do a binary search */
225 High
= ExportDirectory
->NumberOfNames
- 1;
228 /* Get new middle value */
229 Mid
= (Low
+ High
) >> 1;
232 Ret
= strcmp(ExportName
, (PCHAR
)DllBase
+ NameTable
[Mid
]);
250 /* Check if we couldn't find it */
251 if (High
< Low
) return NULL
;
253 /* Otherwise, this is the ordinal */
254 Ordinal
= OrdinalTable
[Mid
];
256 /* Resolve the address and write it */
257 ExportTable
= (PULONG
)((ULONG_PTR
)DllBase
+
258 ExportDirectory
->AddressOfFunctions
);
259 Function
= (PVOID
)((ULONG_PTR
)DllBase
+ ExportTable
[Ordinal
]);
261 /* Check if the function is actually a forwarder */
262 if (((ULONG_PTR
)Function
> (ULONG_PTR
)ExportDirectory
) &&
263 ((ULONG_PTR
)Function
< ((ULONG_PTR
)ExportDirectory
+ ExportSize
)))
275 MmCallDllInitialize(IN PLDR_DATA_TABLE_ENTRY LdrEntry
,
276 IN PLIST_ENTRY ListHead
)
278 UNICODE_STRING ServicesKeyName
= RTL_CONSTANT_STRING(
279 L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\");
280 PMM_DLL_INITIALIZE DllInit
;
281 UNICODE_STRING RegPath
, ImportName
;
284 /* Try to see if the image exports a DllInitialize routine */
285 DllInit
= (PMM_DLL_INITIALIZE
)MiLocateExportName(LdrEntry
->DllBase
,
287 if (!DllInit
) return STATUS_SUCCESS
;
289 /* Do a temporary copy of BaseDllName called ImportName
290 * because we'll alter the length of the string
292 ImportName
.Length
= LdrEntry
->BaseDllName
.Length
;
293 ImportName
.MaximumLength
= LdrEntry
->BaseDllName
.MaximumLength
;
294 ImportName
.Buffer
= LdrEntry
->BaseDllName
.Buffer
;
296 /* Obtain the path to this dll's service in the registry */
297 RegPath
.MaximumLength
= ServicesKeyName
.Length
+
298 ImportName
.Length
+ sizeof(UNICODE_NULL
);
299 RegPath
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
300 RegPath
.MaximumLength
,
303 /* Check if this allocation was unsuccessful */
304 if (!RegPath
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
306 /* Build and append the service name itself */
307 RegPath
.Length
= ServicesKeyName
.Length
;
308 RtlCopyMemory(RegPath
.Buffer
,
309 ServicesKeyName
.Buffer
,
310 ServicesKeyName
.Length
);
312 /* Check if there is a dot in the filename */
313 if (wcschr(ImportName
.Buffer
, L
'.'))
315 /* Remove the extension */
316 ImportName
.Length
= (wcschr(ImportName
.Buffer
, L
'.') -
317 ImportName
.Buffer
) * sizeof(WCHAR
);
320 /* Append service name (the basename without extension) */
321 RtlAppendUnicodeStringToString(&RegPath
, &ImportName
);
323 /* Now call the DllInit func */
324 DPRINT("Calling DllInit(%wZ)\n", &RegPath
);
325 Status
= DllInit(&RegPath
);
328 ExFreePool(RegPath
.Buffer
);
330 /* Return status value which DllInitialize returned */
336 MiCallDllUnloadAndUnloadDll(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
342 /* Get the unload routine */
343 Func
= (PMM_DLL_UNLOAD
)MiLocateExportName(LdrEntry
->DllBase
, "DllUnload");
344 if (!Func
) return FALSE
;
346 /* Call it and check for success */
348 if (!NT_SUCCESS(Status
)) return FALSE
;
350 /* Lie about the load count so we can unload the image */
351 ASSERT(LdrEntry
->LoadCount
== 0);
352 LdrEntry
->LoadCount
= 1;
354 /* Unload it and return true */
355 MmUnloadSystemImage(LdrEntry
);
361 MiDereferenceImports(IN PLOAD_IMPORTS ImportList
)
364 LOAD_IMPORTS SingleEntry
;
365 PLDR_DATA_TABLE_ENTRY LdrEntry
;
366 PVOID CurrentImports
;
369 /* Check if there's no imports or if we're a boot driver */
370 if ((ImportList
== MM_SYSLDR_NO_IMPORTS
) ||
371 (ImportList
== MM_SYSLDR_BOOT_LOADED
) ||
372 (ImportList
->Count
== 0))
374 /* Then there's nothing to do */
375 return STATUS_SUCCESS
;
378 /* Check for single-entry */
379 if ((ULONG_PTR
)ImportList
& MM_SYSLDR_SINGLE_ENTRY
)
382 SingleEntry
.Count
= 1;
383 SingleEntry
.Entry
[0] = (PVOID
)((ULONG_PTR
)ImportList
&~ MM_SYSLDR_SINGLE_ENTRY
);
385 /* Use this as the import list */
386 ImportList
= &SingleEntry
;
389 /* Loop the import list */
390 for (i
= 0; (i
< ImportList
->Count
) && (ImportList
->Entry
[i
]); i
++)
393 LdrEntry
= ImportList
->Entry
[i
];
394 DPRINT1("%wZ <%wZ>\n", &LdrEntry
->FullDllName
, &LdrEntry
->BaseDllName
);
396 /* Skip boot loaded images */
397 if (LdrEntry
->LoadedImports
== MM_SYSLDR_BOOT_LOADED
) continue;
399 /* Dereference the entry */
400 ASSERT(LdrEntry
->LoadCount
>= 1);
401 if (!--LdrEntry
->LoadCount
)
403 /* Save the import data in case unload fails */
404 CurrentImports
= LdrEntry
->LoadedImports
;
406 /* This is the last entry */
407 LdrEntry
->LoadedImports
= MM_SYSLDR_NO_IMPORTS
;
408 if (MiCallDllUnloadAndUnloadDll(LdrEntry
))
410 /* Unloading worked, parse this DLL's imports too */
411 MiDereferenceImports(CurrentImports
);
413 /* Check if we had valid imports */
414 if ((CurrentImports
!= MM_SYSLDR_BOOT_LOADED
) ||
415 (CurrentImports
!= MM_SYSLDR_NO_IMPORTS
) ||
416 !((ULONG_PTR
)LdrEntry
->LoadedImports
& MM_SYSLDR_SINGLE_ENTRY
))
419 ExFreePool(CurrentImports
);
424 /* Unload failed, restore imports */
425 LdrEntry
->LoadedImports
= CurrentImports
;
431 return STATUS_SUCCESS
;
436 MiClearImports(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
440 /* Check if there's no imports or we're a boot driver or only one entry */
441 if ((LdrEntry
->LoadedImports
== MM_SYSLDR_BOOT_LOADED
) ||
442 (LdrEntry
->LoadedImports
== MM_SYSLDR_NO_IMPORTS
) ||
443 ((ULONG_PTR
)LdrEntry
->LoadedImports
& MM_SYSLDR_SINGLE_ENTRY
))
449 /* Otherwise, free the import list */
450 ExFreePool(LdrEntry
->LoadedImports
);
451 LdrEntry
->LoadedImports
= MM_SYSLDR_BOOT_LOADED
;
456 MiFindExportedRoutineByName(IN PVOID DllBase
,
457 IN PANSI_STRING ExportName
)
460 PUSHORT OrdinalTable
;
461 PIMAGE_EXPORT_DIRECTORY ExportDirectory
;
462 LONG Low
= 0, Mid
= 0, High
, Ret
;
469 /* Get the export directory */
470 ExportDirectory
= RtlImageDirectoryEntryToData(DllBase
,
472 IMAGE_DIRECTORY_ENTRY_EXPORT
,
474 if (!ExportDirectory
) return NULL
;
476 /* Setup name tables */
477 NameTable
= (PULONG
)((ULONG_PTR
)DllBase
+
478 ExportDirectory
->AddressOfNames
);
479 OrdinalTable
= (PUSHORT
)((ULONG_PTR
)DllBase
+
480 ExportDirectory
->AddressOfNameOrdinals
);
482 /* Do a binary search */
483 High
= ExportDirectory
->NumberOfNames
- 1;
486 /* Get new middle value */
487 Mid
= (Low
+ High
) >> 1;
490 Ret
= strcmp(ExportName
->Buffer
, (PCHAR
)DllBase
+ NameTable
[Mid
]);
508 /* Check if we couldn't find it */
509 if (High
< Low
) return NULL
;
511 /* Otherwise, this is the ordinal */
512 Ordinal
= OrdinalTable
[Mid
];
514 /* Validate the ordinal */
515 if (Ordinal
>= ExportDirectory
->NumberOfFunctions
) return NULL
;
517 /* Resolve the address and write it */
518 ExportTable
= (PULONG
)((ULONG_PTR
)DllBase
+
519 ExportDirectory
->AddressOfFunctions
);
520 Function
= (PVOID
)((ULONG_PTR
)DllBase
+ ExportTable
[Ordinal
]);
523 ASSERT(!(Function
> (PVOID
)ExportDirectory
) &&
524 (Function
< (PVOID
)((ULONG_PTR
)ExportDirectory
+ ExportSize
)));
530 MiProcessLoaderEntry(IN PLDR_DATA_TABLE_ENTRY LdrEntry
,
535 /* Acquire module list lock */
536 KeEnterCriticalRegion();
537 ExAcquireResourceExclusiveLite(&PsLoadedModuleResource
, TRUE
);
539 /* Acquire the spinlock too as we will insert or remove the entry */
540 OldIrql
= KeAcquireSpinLockRaiseToSynch(&PsLoadedModuleSpinLock
);
542 /* Insert or remove from the list */
543 Insert
? InsertTailList(&PsLoadedModuleList
, &LdrEntry
->InLoadOrderLinks
) :
544 RemoveEntryList(&LdrEntry
->InLoadOrderLinks
);
547 KeReleaseSpinLock(&PsLoadedModuleSpinLock
, OldIrql
);
548 ExReleaseResourceLite(&PsLoadedModuleResource
);
549 KeLeaveCriticalRegion();
554 MiUpdateThunks(IN PLOADER_PARAMETER_BLOCK LoaderBlock
,
559 ULONG_PTR OldBaseTop
, Delta
;
560 PLDR_DATA_TABLE_ENTRY LdrEntry
;
561 PLIST_ENTRY NextEntry
;
563 PULONG_PTR ImageThunk
;
564 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
;
566 /* Calculate the top and delta */
567 OldBaseTop
= (ULONG_PTR
)OldBase
+ Size
- 1;
568 Delta
= (ULONG_PTR
)NewBase
- (ULONG_PTR
)OldBase
;
570 /* Loop the loader block */
571 for (NextEntry
= LoaderBlock
->LoadOrderListHead
.Flink
;
572 NextEntry
!= &LoaderBlock
->LoadOrderListHead
;
573 NextEntry
= NextEntry
->Flink
)
575 /* Get the loader entry */
576 LdrEntry
= CONTAINING_RECORD(NextEntry
,
577 LDR_DATA_TABLE_ENTRY
,
579 #ifdef _WORKING_LINKER_
581 ImageThunk
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
583 IMAGE_DIRECTORY_ENTRY_IAT
,
585 if (!ImageThunk
) continue;
587 /* Make sure we have an IAT */
588 DPRINT("[Mm0]: Updating thunks in: %wZ\n", &LdrEntry
->BaseDllName
);
589 for (i
= 0; i
< ImportSize
; i
++, ImageThunk
++)
591 /* Check if it's within this module */
592 if ((*ImageThunk
>= (ULONG_PTR
)OldBase
) && (*ImageThunk
<= OldBaseTop
))
595 DPRINT("[Mm0]: Updating IAT at: %p. Old Entry: %p. New Entry: %p.\n",
596 ImageThunk
, *ImageThunk
, *ImageThunk
+ Delta
);
597 *ImageThunk
+= Delta
;
601 /* Get the import table */
603 ImportDescriptor
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
605 IMAGE_DIRECTORY_ENTRY_IMPORT
,
607 if (!ImportDescriptor
) continue;
609 /* Make sure we have an IAT */
610 DPRINT("[Mm0]: Updating thunks in: %wZ\n", &LdrEntry
->BaseDllName
);
611 while ((ImportDescriptor
->Name
) &&
612 (ImportDescriptor
->OriginalFirstThunk
))
614 /* Get the image thunk */
615 ImageThunk
= (PVOID
)((ULONG_PTR
)LdrEntry
->DllBase
+
616 ImportDescriptor
->FirstThunk
);
619 /* Check if it's within this module */
620 if ((*ImageThunk
>= (ULONG_PTR
)OldBase
) && (*ImageThunk
<= OldBaseTop
))
623 DPRINT("[Mm0]: Updating IAT at: %p. Old Entry: %p. New Entry: %p.\n",
624 ImageThunk
, *ImageThunk
, *ImageThunk
+ Delta
);
625 *ImageThunk
+= Delta
;
628 /* Go to the next thunk */
632 /* Go to the next import */
641 MiSnapThunk(IN PVOID DllBase
,
643 IN PIMAGE_THUNK_DATA Name
,
644 IN PIMAGE_THUNK_DATA Address
,
645 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory
,
647 IN BOOLEAN SnapForwarder
,
648 OUT PCHAR
*MissingApi
)
653 PUSHORT OrdinalTable
;
654 PIMAGE_IMPORT_BY_NAME NameImport
;
656 ULONG Low
= 0, Mid
= 0, High
;
659 PCHAR MissingForwarder
;
660 CHAR NameBuffer
[MAXIMUM_FILENAME_LENGTH
];
663 UNICODE_STRING ForwarderName
;
664 PLIST_ENTRY NextEntry
;
665 PLDR_DATA_TABLE_ENTRY LdrEntry
;
666 ULONG ForwardExportSize
;
667 PIMAGE_EXPORT_DIRECTORY ForwardExportDirectory
;
668 PIMAGE_IMPORT_BY_NAME ForwardName
;
670 IMAGE_THUNK_DATA ForwardThunk
;
673 /* Check if this is an ordinal */
674 IsOrdinal
= IMAGE_SNAP_BY_ORDINAL(Name
->u1
.Ordinal
);
675 if ((IsOrdinal
) && !(SnapForwarder
))
677 /* Get the ordinal number and set it as missing */
678 Ordinal
= (USHORT
)(IMAGE_ORDINAL(Name
->u1
.Ordinal
) -
679 ExportDirectory
->Base
);
680 *MissingApi
= (PCHAR
)(ULONG_PTR
)Ordinal
;
684 /* Get the VA if we don't have to snap */
685 if (!SnapForwarder
) Name
->u1
.AddressOfData
+= (ULONG_PTR
)ImageBase
;
686 NameImport
= (PIMAGE_IMPORT_BY_NAME
)Name
->u1
.AddressOfData
;
688 /* Copy the procedure name */
690 (PCHAR
)&NameImport
->Name
[0],
691 MAXIMUM_FILENAME_LENGTH
- 1);
693 /* Setup name tables */
694 DPRINT("Import name: %s\n", NameImport
->Name
);
695 NameTable
= (PULONG
)((ULONG_PTR
)DllBase
+
696 ExportDirectory
->AddressOfNames
);
697 OrdinalTable
= (PUSHORT
)((ULONG_PTR
)DllBase
+
698 ExportDirectory
->AddressOfNameOrdinals
);
700 /* Get the hint and check if it's valid */
701 Hint
= NameImport
->Hint
;
702 if ((Hint
< ExportDirectory
->NumberOfNames
) &&
703 !(strcmp((PCHAR
)NameImport
->Name
, (PCHAR
)DllBase
+ NameTable
[Hint
])))
705 /* We have a match, get the ordinal number from here */
706 Ordinal
= OrdinalTable
[Hint
];
710 /* Do a binary search */
711 High
= ExportDirectory
->NumberOfNames
- 1;
714 /* Get new middle value */
715 Mid
= (Low
+ High
) >> 1;
718 Ret
= strcmp((PCHAR
)NameImport
->Name
, (PCHAR
)DllBase
+ NameTable
[Mid
]);
736 /* Check if we couldn't find it */
737 if (High
< Low
) return STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
;
739 /* Otherwise, this is the ordinal */
740 Ordinal
= OrdinalTable
[Mid
];
744 /* Check if the ordinal is invalid */
745 if (Ordinal
>= ExportDirectory
->NumberOfFunctions
)
748 Status
= STATUS_DRIVER_ORDINAL_NOT_FOUND
;
752 /* In case the forwarder is missing */
753 MissingForwarder
= NameBuffer
;
755 /* Resolve the address and write it */
756 ExportTable
= (PULONG
)((ULONG_PTR
)DllBase
+
757 ExportDirectory
->AddressOfFunctions
);
758 Address
->u1
.Function
= (ULONG_PTR
)DllBase
+ ExportTable
[Ordinal
];
760 /* Assume success from now on */
761 Status
= STATUS_SUCCESS
;
763 /* Check if the function is actually a forwarder */
764 if ((Address
->u1
.Function
> (ULONG_PTR
)ExportDirectory
) &&
765 (Address
->u1
.Function
< ((ULONG_PTR
)ExportDirectory
+ ExportSize
)))
767 /* Now assume failure in case the forwarder doesn't exist */
768 Status
= STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
;
770 /* Build the forwarder name */
771 DllName
.Buffer
= (PCHAR
)Address
->u1
.Function
;
772 DllName
.Length
= strchr(DllName
.Buffer
, '.') -
775 DllName
.MaximumLength
= DllName
.Length
;
778 if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&ForwarderName
,
782 /* We failed, just return an error */
786 /* Loop the module list */
787 NextEntry
= PsLoadedModuleList
.Flink
;
788 while (NextEntry
!= &PsLoadedModuleList
)
790 /* Get the loader entry */
791 LdrEntry
= CONTAINING_RECORD(NextEntry
,
792 LDR_DATA_TABLE_ENTRY
,
795 /* Check if it matches */
796 if (RtlPrefixString((PSTRING
)&ForwarderName
,
797 (PSTRING
)&LdrEntry
->BaseDllName
,
800 /* Get the forwarder export directory */
801 ForwardExportDirectory
=
802 RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
804 IMAGE_DIRECTORY_ENTRY_EXPORT
,
806 if (!ForwardExportDirectory
) break;
808 /* Allocate a name entry */
809 ForwardLength
= strlen(DllName
.Buffer
+ DllName
.Length
) +
811 ForwardName
= ExAllocatePoolWithTag(PagedPool
,
812 sizeof(*ForwardName
) +
815 if (!ForwardName
) break;
818 RtlCopyMemory(&ForwardName
->Name
[0],
819 DllName
.Buffer
+ DllName
.Length
,
821 ForwardName
->Hint
= 0;
823 /* Set the new address */
824 ForwardThunk
.u1
.AddressOfData
= (ULONG_PTR
)ForwardName
;
826 /* Snap the forwarder */
827 Status
= MiSnapThunk(LdrEntry
->DllBase
,
831 ForwardExportDirectory
,
836 /* Free the forwarder name and set the thunk */
837 ExFreePoolWithTag(ForwardName
, TAG_LDR_WSTR
);
838 Address
->u1
= ForwardThunk
.u1
;
842 /* Go to the next entry */
843 NextEntry
= NextEntry
->Flink
;
847 RtlFreeUnicodeString(&ForwarderName
);
857 MmUnloadSystemImage(IN PVOID ImageHandle
)
859 PLDR_DATA_TABLE_ENTRY LdrEntry
= ImageHandle
;
860 PVOID BaseAddress
= LdrEntry
->DllBase
;
863 BOOLEAN HadEntry
= FALSE
;
865 /* Acquire the loader lock */
866 KeEnterCriticalRegion();
867 KeWaitForSingleObject(&MmSystemLoadLock
,
873 /* Check if this driver was loaded at boot and didn't get imports parsed */
874 if (LdrEntry
->LoadedImports
== MM_SYSLDR_BOOT_LOADED
) goto Done
;
876 /* We should still be alive */
877 ASSERT(LdrEntry
->LoadCount
!= 0);
878 LdrEntry
->LoadCount
--;
880 /* Check if we're still loaded */
881 if (LdrEntry
->LoadCount
) goto Done
;
883 /* We should cleanup... are symbols loaded */
884 if (LdrEntry
->Flags
& LDRP_DEBUG_SYMBOLS_LOADED
)
886 /* Create the ANSI name */
887 Status
= RtlUnicodeStringToAnsiString(&TempName
,
888 &LdrEntry
->BaseDllName
,
890 if (NT_SUCCESS(Status
))
892 /* Unload the symbols */
893 DbgUnLoadImageSymbols(&TempName
,
895 (ULONG_PTR
)ZwCurrentProcess());
896 RtlFreeAnsiString(&TempName
);
900 /* FIXME: Free the driver */
901 DPRINT1("Leaking driver: %wZ\n", &LdrEntry
->BaseDllName
);
902 //MmFreeSection(LdrEntry->DllBase);
904 /* Check if we're linked in */
905 if (LdrEntry
->InLoadOrderLinks
.Flink
)
908 MiProcessLoaderEntry(LdrEntry
, FALSE
);
912 /* Dereference and clear the imports */
913 MiDereferenceImports(LdrEntry
->LoadedImports
);
914 MiClearImports(LdrEntry
);
916 /* Check if the entry needs to go away */
919 /* Check if it had a name */
920 if (LdrEntry
->FullDllName
.Buffer
)
923 ExFreePool(LdrEntry
->FullDllName
.Buffer
);
926 /* Check if we had a section */
927 if (LdrEntry
->SectionPointer
)
930 ObDereferenceObject(LdrEntry
->SectionPointer
);
934 ExFreePool(LdrEntry
);
937 /* Release the system lock and return */
939 KeReleaseMutant(&MmSystemLoadLock
, 1, FALSE
, FALSE
);
940 KeLeaveCriticalRegion();
941 return STATUS_SUCCESS
;
946 MiResolveImageReferences(IN PVOID ImageBase
,
947 IN PUNICODE_STRING ImageFileDirectory
,
948 IN PUNICODE_STRING NamePrefix OPTIONAL
,
949 OUT PCHAR
*MissingApi
,
950 OUT PWCHAR
*MissingDriver
,
951 OUT PLOAD_IMPORTS
*LoadImports
)
953 PCHAR MissingApiBuffer
= *MissingApi
, ImportName
;
954 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
, CurrentImport
;
955 ULONG ImportSize
, ImportCount
= 0, LoadedImportsSize
, ExportSize
;
956 PLOAD_IMPORTS LoadedImports
, NewImports
;
957 ULONG GdiLink
, NormalLink
, i
;
958 BOOLEAN ReferenceNeeded
, Loaded
;
959 ANSI_STRING TempString
;
960 UNICODE_STRING NameString
, DllName
;
961 PLDR_DATA_TABLE_ENTRY LdrEntry
= NULL
, DllEntry
, ImportEntry
= NULL
;
962 PVOID ImportBase
, DllBase
;
963 PLIST_ENTRY NextEntry
;
964 PIMAGE_EXPORT_DIRECTORY ExportDirectory
;
966 PIMAGE_THUNK_DATA OrigThunk
, FirstThunk
;
968 DPRINT("%s - ImageBase: %p. ImageFileDirectory: %wZ\n",
969 __FUNCTION__
, ImageBase
, ImageFileDirectory
);
971 /* Assume no imports */
972 *LoadImports
= MM_SYSLDR_NO_IMPORTS
;
974 /* Get the import descriptor */
975 ImportDescriptor
= RtlImageDirectoryEntryToData(ImageBase
,
977 IMAGE_DIRECTORY_ENTRY_IMPORT
,
979 if (!ImportDescriptor
) return STATUS_SUCCESS
;
981 /* Loop all imports to count them */
982 for (CurrentImport
= ImportDescriptor
;
983 (CurrentImport
->Name
) && (CurrentImport
->OriginalFirstThunk
);
990 /* Make sure we have non-zero imports */
993 /* Calculate and allocate the list we'll need */
994 LoadedImportsSize
= ImportCount
* sizeof(PVOID
) + sizeof(SIZE_T
);
995 LoadedImports
= ExAllocatePoolWithTag(PagedPool
,
1001 RtlZeroMemory(LoadedImports
, LoadedImportsSize
);
1002 LoadedImports
->Count
= ImportCount
;
1008 LoadedImports
= NULL
;
1011 /* Reset the import count and loop descriptors again */
1012 ImportCount
= GdiLink
= NormalLink
= 0;
1013 while ((ImportDescriptor
->Name
) && (ImportDescriptor
->OriginalFirstThunk
))
1016 ImportName
= (PCHAR
)((ULONG_PTR
)ImageBase
+ ImportDescriptor
->Name
);
1018 /* Check if this is a GDI driver */
1020 !(_strnicmp(ImportName
, "win32k", sizeof("win32k") - 1));
1022 /* We can also allow dxapi (for Windows compat, allow IRT and coverage )*/
1023 NormalLink
= NormalLink
|
1024 ((_strnicmp(ImportName
, "win32k", sizeof("win32k") - 1)) &&
1025 (_strnicmp(ImportName
, "dxapi", sizeof("dxapi") - 1)) &&
1026 (_strnicmp(ImportName
, "coverage", sizeof("coverage") - 1)) &&
1027 (_strnicmp(ImportName
, "irt", sizeof("irt") - 1)));
1029 /* Check if this is a valid GDI driver */
1030 if ((GdiLink
) && (NormalLink
))
1032 /* It's not, it's importing stuff it shouldn't be! */
1033 MiDereferenceImports(LoadedImports
);
1034 if (LoadedImports
) ExFreePool(LoadedImports
);
1035 return STATUS_PROCEDURE_NOT_FOUND
;
1038 /* Check for user-mode printer or video card drivers, which don't belong */
1039 if (!(_strnicmp(ImportName
, "ntdll", sizeof("ntdll") - 1)) ||
1040 !(_strnicmp(ImportName
, "winsrv", sizeof("winsrv") - 1)) ||
1041 !(_strnicmp(ImportName
, "advapi32", sizeof("advapi32") - 1)) ||
1042 !(_strnicmp(ImportName
, "kernel32", sizeof("kernel32") - 1)) ||
1043 !(_strnicmp(ImportName
, "user32", sizeof("user32") - 1)) ||
1044 !(_strnicmp(ImportName
, "gdi32", sizeof("gdi32") - 1)))
1046 /* This is not kernel code */
1047 MiDereferenceImports(LoadedImports
);
1048 if (LoadedImports
) ExFreePool(LoadedImports
);
1049 return STATUS_PROCEDURE_NOT_FOUND
;
1052 /* Check if this is a "core" import, which doesn't get referenced */
1053 if (!(_strnicmp(ImportName
, "ntoskrnl", sizeof("ntoskrnl") - 1)) ||
1054 !(_strnicmp(ImportName
, "win32k", sizeof("win32k") - 1)) ||
1055 !(_strnicmp(ImportName
, "hal", sizeof("hal") - 1)))
1057 /* Don't reference this */
1058 ReferenceNeeded
= FALSE
;
1062 /* Reference these modules */
1063 ReferenceNeeded
= TRUE
;
1066 /* Now setup a unicode string for the import */
1067 RtlInitAnsiString(&TempString
, ImportName
);
1068 Status
= RtlAnsiStringToUnicodeString(&NameString
, &TempString
, TRUE
);
1069 if (!NT_SUCCESS(Status
))
1072 MiDereferenceImports(LoadedImports
);
1073 if (LoadedImports
) ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1077 /* We don't support name prefixes yet */
1078 if (NamePrefix
) DPRINT1("Name Prefix not yet supported!\n");
1080 /* Remember that we haven't loaded the import at this point */
1085 /* Loop the driver list */
1086 NextEntry
= PsLoadedModuleList
.Flink
;
1087 while (NextEntry
!= &PsLoadedModuleList
)
1089 /* Get the loader entry and compare the name */
1090 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1091 LDR_DATA_TABLE_ENTRY
,
1093 if (RtlEqualUnicodeString(&NameString
,
1094 &LdrEntry
->BaseDllName
,
1097 /* Get the base address */
1098 ImportBase
= LdrEntry
->DllBase
;
1100 /* Check if we haven't loaded yet, and we need references */
1101 if (!(Loaded
) && (ReferenceNeeded
))
1103 /* Make sure we're not already loading */
1104 if (!(LdrEntry
->Flags
& LDRP_LOAD_IN_PROGRESS
))
1106 /* Increase the load count */
1107 LdrEntry
->LoadCount
++;
1111 /* Done, break out */
1115 /* Go to the next entry */
1116 NextEntry
= NextEntry
->Flink
;
1119 /* Check if we haven't loaded the import yet */
1122 /* Setup the import DLL name */
1123 DllName
.MaximumLength
= NameString
.Length
+
1124 ImageFileDirectory
->Length
+
1125 sizeof(UNICODE_NULL
);
1126 DllName
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
1127 DllName
.MaximumLength
,
1131 /* Setup the base length and copy it */
1132 DllName
.Length
= ImageFileDirectory
->Length
;
1133 RtlCopyMemory(DllName
.Buffer
,
1134 ImageFileDirectory
->Buffer
,
1135 ImageFileDirectory
->Length
);
1137 /* Now add the import name and null-terminate it */
1138 RtlAppendStringToString((PSTRING
)&DllName
,
1139 (PSTRING
)&NameString
);
1140 DllName
.Buffer
[(DllName
.MaximumLength
- 1) / sizeof(WCHAR
)] = UNICODE_NULL
;
1142 /* Load the image */
1143 Status
= MmLoadSystemImage(&DllName
,
1149 if (NT_SUCCESS(Status
))
1151 /* We can free the DLL Name */
1152 ExFreePool(DllName
.Buffer
);
1156 /* Fill out the information for the error */
1157 *MissingDriver
= DllName
.Buffer
;
1158 *(PULONG
)MissingDriver
|= 1;
1164 /* We're out of resources */
1165 Status
= STATUS_INSUFFICIENT_RESOURCES
;
1168 /* Check if we're OK until now */
1169 if (NT_SUCCESS(Status
))
1171 /* We're now loaded */
1175 ASSERT(DllBase
= DllEntry
->DllBase
);
1177 /* Call the initialization routines */
1178 Status
= MmCallDllInitialize(DllEntry
, &PsLoadedModuleList
);
1179 if (!NT_SUCCESS(Status
))
1181 /* We failed, unload the image */
1182 MmUnloadSystemImage(DllEntry
);
1188 /* Check if we failed by here */
1189 if (!NT_SUCCESS(Status
))
1191 /* Cleanup and return */
1192 RtlFreeUnicodeString(&NameString
);
1193 MiDereferenceImports(LoadedImports
);
1194 if (LoadedImports
) ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1198 /* Loop again to make sure that everything is OK */
1202 /* Check if we're support to reference this import */
1203 if ((ReferenceNeeded
) && (LoadedImports
))
1205 /* Make sure we're not already loading */
1206 if (!(LdrEntry
->Flags
& LDRP_LOAD_IN_PROGRESS
))
1209 LoadedImports
->Entry
[ImportCount
] = LdrEntry
;
1214 /* Free the import name */
1215 RtlFreeUnicodeString(&NameString
);
1217 /* Set the missing driver name and get the export directory */
1218 *MissingDriver
= LdrEntry
->BaseDllName
.Buffer
;
1219 ExportDirectory
= RtlImageDirectoryEntryToData(ImportBase
,
1221 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1223 if (!ExportDirectory
)
1225 /* Cleanup and return */
1226 MiDereferenceImports(LoadedImports
);
1227 if (LoadedImports
) ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1228 return STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
;
1231 /* Make sure we have an IAT */
1232 if (ImportDescriptor
->OriginalFirstThunk
)
1234 /* Get the first thunks */
1235 OrigThunk
= (PVOID
)((ULONG_PTR
)ImageBase
+
1236 ImportDescriptor
->OriginalFirstThunk
);
1237 FirstThunk
= (PVOID
)((ULONG_PTR
)ImageBase
+
1238 ImportDescriptor
->FirstThunk
);
1241 while (OrigThunk
->u1
.AddressOfData
)
1244 Status
= MiSnapThunk(ImportBase
,
1252 if (!NT_SUCCESS(Status
))
1254 /* Cleanup and return */
1255 MiDereferenceImports(LoadedImports
);
1256 if (LoadedImports
) ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1260 /* Reset the buffer */
1261 *MissingApi
= MissingApiBuffer
;
1265 /* Go to the next import */
1269 /* Check if we have an import list */
1272 /* Reset the count again, and loop entries*/
1274 for (i
= 0; i
< LoadedImports
->Count
; i
++)
1276 if (LoadedImports
->Entry
[i
])
1278 /* Got an entry, OR it with 1 in case it's the single entry */
1279 ImportEntry
= (PVOID
)((ULONG_PTR
)LoadedImports
->Entry
[i
] |
1280 MM_SYSLDR_SINGLE_ENTRY
);
1285 /* Check if we had no imports */
1288 /* Free the list and set it to no imports */
1289 ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1290 LoadedImports
= MM_SYSLDR_NO_IMPORTS
;
1292 else if (ImportCount
== 1)
1294 /* Just one entry, we can free the table and only use our entry */
1295 ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1296 LoadedImports
= (PLOAD_IMPORTS
)ImportEntry
;
1298 else if (ImportCount
!= LoadedImports
->Count
)
1300 /* Allocate a new list */
1301 LoadedImportsSize
= ImportCount
* sizeof(PVOID
) + sizeof(SIZE_T
);
1302 NewImports
= ExAllocatePoolWithTag(PagedPool
,
1308 NewImports
->Count
= 0;
1310 /* Loop all the imports */
1311 for (i
= 0; i
< LoadedImports
->Count
; i
++)
1313 /* Make sure it's valid */
1314 if (LoadedImports
->Entry
[i
])
1317 NewImports
->Entry
[NewImports
->Count
] = LoadedImports
->Entry
[i
];
1318 NewImports
->Count
++;
1322 /* Free the old copy */
1323 ExFreePoolWithTag(LoadedImports
, TAG_LDR_WSTR
);
1324 LoadedImports
= NewImports
;
1328 /* Return the list */
1329 *LoadImports
= LoadedImports
;
1332 /* Return success */
1333 return STATUS_SUCCESS
;
1338 MiReloadBootLoadedDrivers(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
1340 PLIST_ENTRY NextEntry
;
1342 PIMAGE_NT_HEADERS NtHeader
;
1343 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1344 PIMAGE_FILE_HEADER FileHeader
;
1345 BOOLEAN ValidRelocs
;
1346 PIMAGE_DATA_DIRECTORY DataDirectory
;
1347 PVOID DllBase
, NewImageAddress
;
1349 PMMPTE PointerPte
, StartPte
, LastPte
;
1350 PFN_NUMBER PteCount
;
1352 MMPTE TempPte
, OldPte
;
1354 /* Loop driver list */
1355 for (NextEntry
= LoaderBlock
->LoadOrderListHead
.Flink
;
1356 NextEntry
!= &LoaderBlock
->LoadOrderListHead
;
1357 NextEntry
= NextEntry
->Flink
)
1359 /* Get the loader entry and NT header */
1360 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1361 LDR_DATA_TABLE_ENTRY
,
1363 NtHeader
= RtlImageNtHeader(LdrEntry
->DllBase
);
1366 DPRINT("[Mm0]: Driver at: %p ending at: %p for module: %wZ\n",
1368 (ULONG_PTR
)LdrEntry
->DllBase
+ LdrEntry
->SizeOfImage
,
1369 &LdrEntry
->FullDllName
);
1371 /* Skip kernel and HAL */
1372 /* ROS HACK: Skip BOOTVID/KDCOM too */
1374 if (i
<= 4) continue;
1376 /* Skip non-drivers */
1377 if (!NtHeader
) continue;
1379 /* Get the file header and make sure we can relocate */
1380 FileHeader
= &NtHeader
->FileHeader
;
1381 if (FileHeader
->Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
) continue;
1382 if (NtHeader
->OptionalHeader
.NumberOfRvaAndSizes
<
1383 IMAGE_DIRECTORY_ENTRY_BASERELOC
) continue;
1385 /* Everything made sense until now, check the relocation section too */
1386 DataDirectory
= &NtHeader
->OptionalHeader
.
1387 DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1388 if (!DataDirectory
->VirtualAddress
)
1390 /* We don't really have relocations */
1391 ValidRelocs
= FALSE
;
1395 /* Make sure the size is valid */
1396 if ((DataDirectory
->VirtualAddress
+ DataDirectory
->Size
) >
1397 LdrEntry
->SizeOfImage
)
1399 /* They're not, skip */
1403 /* We have relocations */
1407 /* Remember the original address */
1408 DllBase
= LdrEntry
->DllBase
;
1410 /* Get the first PTE and the number of PTEs we'll need */
1411 PointerPte
= StartPte
= MiAddressToPte(LdrEntry
->DllBase
);
1412 PteCount
= ROUND_TO_PAGES(LdrEntry
->SizeOfImage
) >> PAGE_SHIFT
;
1413 LastPte
= StartPte
+ PteCount
;
1416 while (PointerPte
< LastPte
)
1418 /* Mark the page modified in the PFN database */
1419 ASSERT(PointerPte
->u
.Hard
.Valid
== 1);
1420 Pfn1
= MiGetPfnEntry(PFN_FROM_PTE(PointerPte
));
1421 ASSERT(Pfn1
->u3
.e1
.Rom
== 0);
1422 Pfn1
->u3
.e1
.Modified
= TRUE
;
1428 /* Now reserve system PTEs for the image */
1429 PointerPte
= MiReserveSystemPtes(PteCount
, SystemPteSpace
);
1432 /* Shouldn't happen */
1433 DPRINT1("[Mm0]: Couldn't allocate driver section!\n");
1437 /* This is the new virtual address for the module */
1438 LastPte
= PointerPte
+ PteCount
;
1439 NewImageAddress
= MiPteToAddress(PointerPte
);
1442 DPRINT("[Mm0]: Copying from: %p to: %p\n", DllBase
, NewImageAddress
);
1443 ASSERT(ExpInitializationPhase
== 0);
1445 /* Loop the new driver PTEs */
1446 TempPte
= ValidKernelPte
;
1447 while (PointerPte
< LastPte
)
1449 /* Copy the old data */
1451 ASSERT(OldPte
.u
.Hard
.Valid
== 1);
1453 /* Set page number from the loader's memory */
1454 TempPte
.u
.Hard
.PageFrameNumber
= OldPte
.u
.Hard
.PageFrameNumber
;
1457 MI_WRITE_VALID_PTE(PointerPte
, TempPte
);
1464 /* Update position */
1465 PointerPte
-= PteCount
;
1468 ASSERT(*(PULONG
)NewImageAddress
== *(PULONG
)DllBase
);
1470 /* Set the image base to the address where the loader put it */
1471 NtHeader
->OptionalHeader
.ImageBase
= (ULONG_PTR
)DllBase
;
1473 /* Check if we had relocations */
1476 /* Relocate the image */
1477 Status
= LdrRelocateImageWithBias(NewImageAddress
,
1481 STATUS_CONFLICTING_ADDRESSES
,
1482 STATUS_INVALID_IMAGE_FORMAT
);
1483 if (!NT_SUCCESS(Status
))
1485 /* This shouldn't happen */
1486 DPRINT1("Relocations failed!\n");
1491 /* Update the loader entry */
1492 LdrEntry
->DllBase
= NewImageAddress
;
1494 /* Update the thunks */
1495 DPRINT("[Mm0]: Updating thunks to: %wZ\n", &LdrEntry
->BaseDllName
);
1496 MiUpdateThunks(LoaderBlock
,
1499 LdrEntry
->SizeOfImage
);
1501 /* Update the loader entry */
1502 LdrEntry
->Flags
|= LDRP_SYSTEM_MAPPED
;
1503 LdrEntry
->EntryPoint
= (PVOID
)((ULONG_PTR
)NewImageAddress
+
1504 NtHeader
->OptionalHeader
.AddressOfEntryPoint
);
1505 LdrEntry
->SizeOfImage
= PteCount
<< PAGE_SHIFT
;
1507 /* FIXME: We'll need to fixup the PFN linkage when switching to ARM3 */
1513 MiBuildImportsForBootDrivers(VOID
)
1515 PLIST_ENTRY NextEntry
, NextEntry2
;
1516 PLDR_DATA_TABLE_ENTRY LdrEntry
, KernelEntry
, HalEntry
, LdrEntry2
, LastEntry
;
1517 PLDR_DATA_TABLE_ENTRY
* EntryArray
;
1518 UNICODE_STRING KernelName
= RTL_CONSTANT_STRING(L
"ntoskrnl.exe");
1519 UNICODE_STRING HalName
= RTL_CONSTANT_STRING(L
"hal.dll");
1520 PLOAD_IMPORTS LoadedImports
;
1521 ULONG LoadedImportsSize
, ImportSize
;
1522 PULONG_PTR ImageThunk
;
1523 ULONG_PTR DllBase
, DllEnd
;
1524 ULONG Modules
= 0, i
, j
= 0;
1525 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
;
1527 /* Initialize variables */
1528 KernelEntry
= HalEntry
= LastEntry
= NULL
;
1530 /* Loop the loaded module list... we are early enough that no lock is needed */
1531 NextEntry
= PsLoadedModuleList
.Flink
;
1532 while (NextEntry
!= &PsLoadedModuleList
)
1535 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1536 LDR_DATA_TABLE_ENTRY
,
1539 /* Check if it's the kernel or HAL */
1540 if (RtlEqualUnicodeString(&KernelName
, &LdrEntry
->BaseDllName
, TRUE
))
1543 KernelEntry
= LdrEntry
;
1545 else if (RtlEqualUnicodeString(&HalName
, &LdrEntry
->BaseDllName
, TRUE
))
1548 HalEntry
= LdrEntry
;
1551 /* Check if this is a driver DLL */
1552 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
1554 /* Check if this is the HAL or kernel */
1555 if ((LdrEntry
== HalEntry
) || (LdrEntry
== KernelEntry
))
1557 /* Add a reference */
1558 LdrEntry
->LoadCount
= 1;
1562 /* No referencing needed */
1563 LdrEntry
->LoadCount
= 0;
1568 /* No referencing needed */
1569 LdrEntry
->LoadCount
= 0;
1572 /* Remember this came from the loader */
1573 LdrEntry
->LoadedImports
= MM_SYSLDR_BOOT_LOADED
;
1576 NextEntry
= NextEntry
->Flink
;
1580 /* We must have at least found the kernel and HAL */
1581 if (!(HalEntry
) || (!KernelEntry
)) return STATUS_NOT_FOUND
;
1583 /* Allocate the list */
1584 EntryArray
= ExAllocatePoolWithTag(PagedPool
, Modules
* sizeof(PVOID
), 'TDmM');
1585 if (!EntryArray
) return STATUS_INSUFFICIENT_RESOURCES
;
1587 /* Loop the loaded module list again */
1588 NextEntry
= PsLoadedModuleList
.Flink
;
1589 while (NextEntry
!= &PsLoadedModuleList
)
1592 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1593 LDR_DATA_TABLE_ENTRY
,
1595 #ifdef _WORKING_LOADER_
1596 /* Get its imports */
1597 ImageThunk
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
1599 IMAGE_DIRECTORY_ENTRY_IAT
,
1603 /* Get its imports */
1604 ImportDescriptor
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
1606 IMAGE_DIRECTORY_ENTRY_IMPORT
,
1608 if (!ImportDescriptor
)
1612 LdrEntry
->LoadedImports
= MM_SYSLDR_NO_IMPORTS
;
1613 NextEntry
= NextEntry
->Flink
;
1617 /* Clear the list and count the number of IAT thunks */
1618 RtlZeroMemory(EntryArray
, Modules
* sizeof(PVOID
));
1619 #ifdef _WORKING_LOADER_
1620 ImportSize
/= sizeof(ULONG_PTR
);
1622 /* Scan the thunks */
1623 for (i
= 0, DllBase
= 0, DllEnd
= 0; i
< ImportSize
; i
++, ImageThunk
++)
1625 i
= DllBase
= DllEnd
= 0;
1626 while ((ImportDescriptor
->Name
) &&
1627 (ImportDescriptor
->OriginalFirstThunk
))
1629 /* Get the image thunk */
1630 ImageThunk
= (PVOID
)((ULONG_PTR
)LdrEntry
->DllBase
+
1631 ImportDescriptor
->FirstThunk
);
1635 /* Do we already have an address? */
1638 /* Is the thunk in the same address? */
1639 if ((*ImageThunk
>= DllBase
) && (*ImageThunk
< DllEnd
))
1641 /* Skip it, we already have a reference for it */
1642 ASSERT(EntryArray
[j
]);
1648 /* Loop the loaded module list to locate this address owner */
1650 NextEntry2
= PsLoadedModuleList
.Flink
;
1651 while (NextEntry2
!= &PsLoadedModuleList
)
1654 LdrEntry2
= CONTAINING_RECORD(NextEntry2
,
1655 LDR_DATA_TABLE_ENTRY
,
1658 /* Get the address range for this module */
1659 DllBase
= (ULONG_PTR
)LdrEntry2
->DllBase
;
1660 DllEnd
= DllBase
+ LdrEntry2
->SizeOfImage
;
1662 /* Check if this IAT entry matches it */
1663 if ((*ImageThunk
>= DllBase
) && (*ImageThunk
< DllEnd
))
1666 //DPRINT1("Found imported dll: %wZ\n", &LdrEntry2->BaseDllName);
1667 EntryArray
[j
] = LdrEntry2
;
1671 /* Keep searching */
1672 NextEntry2
= NextEntry2
->Flink
;
1676 /* Do we have a thunk outside the range? */
1677 if ((*ImageThunk
< DllBase
) || (*ImageThunk
>= DllEnd
))
1682 /* Should not be happening */
1683 DPRINT1("Broken IAT entry for %p at %p (%lx)\n",
1684 LdrEntry
, ImageThunk
, *ImageThunk
);
1688 /* Reset if we hit this */
1691 #ifndef _WORKING_LOADER_
1700 /* Now scan how many imports we really have */
1701 for (i
= 0, ImportSize
= 0; i
< Modules
; i
++)
1703 /* Skip HAL and kernel */
1704 if ((EntryArray
[i
]) &&
1705 (EntryArray
[i
] != HalEntry
) &&
1706 (EntryArray
[i
] != KernelEntry
))
1708 /* A valid reference */
1709 LastEntry
= EntryArray
[i
];
1714 /* Do we have any imports after all? */
1718 LdrEntry
->LoadedImports
= MM_SYSLDR_NO_IMPORTS
;
1720 else if (ImportSize
== 1)
1722 /* A single entry import */
1723 LdrEntry
->LoadedImports
= (PVOID
)((ULONG_PTR
)LastEntry
| MM_SYSLDR_SINGLE_ENTRY
);
1724 LastEntry
->LoadCount
++;
1728 /* We need an import table */
1729 LoadedImportsSize
= ImportSize
* sizeof(PVOID
) + sizeof(SIZE_T
);
1730 LoadedImports
= ExAllocatePoolWithTag(PagedPool
,
1733 ASSERT(LoadedImports
);
1735 /* Save the count */
1736 LoadedImports
->Count
= ImportSize
;
1738 /* Now copy all imports */
1739 for (i
= 0, j
= 0; i
< Modules
; i
++)
1741 /* Skip HAL and kernel */
1742 if ((EntryArray
[i
]) &&
1743 (EntryArray
[i
] != HalEntry
) &&
1744 (EntryArray
[i
] != KernelEntry
))
1746 /* A valid reference */
1747 //DPRINT1("Found valid entry: %p\n", EntryArray[i]);
1748 LoadedImports
->Entry
[j
] = EntryArray
[i
];
1749 EntryArray
[i
]->LoadCount
++;
1754 /* Should had as many entries as we expected */
1755 ASSERT(j
== ImportSize
);
1756 LdrEntry
->LoadedImports
= LoadedImports
;
1760 NextEntry
= NextEntry
->Flink
;
1763 /* Free the initial array */
1764 ExFreePool(EntryArray
);
1766 /* FIXME: Might not need to keep the HAL/Kernel imports around */
1768 /* Kernel and HAL are loaded at boot */
1769 KernelEntry
->LoadedImports
= MM_SYSLDR_BOOT_LOADED
;
1770 HalEntry
->LoadedImports
= MM_SYSLDR_BOOT_LOADED
;
1772 /* All worked well */
1773 return STATUS_SUCCESS
;
1778 MiLocateKernelSections(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
1781 PIMAGE_NT_HEADERS NtHeaders
;
1782 PIMAGE_SECTION_HEADER SectionHeader
;
1783 ULONG Sections
, Size
;
1785 /* Get the kernel section header */
1786 DllBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
1787 NtHeaders
= RtlImageNtHeader((PVOID
)DllBase
);
1788 SectionHeader
= IMAGE_FIRST_SECTION(NtHeaders
);
1790 /* Loop all the sections */
1791 Sections
= NtHeaders
->FileHeader
.NumberOfSections
;
1794 /* Grab the size of the section */
1795 Size
= max(SectionHeader
->SizeOfRawData
, SectionHeader
->Misc
.VirtualSize
);
1797 /* Check for .RSRC section */
1798 if (*(PULONG
)SectionHeader
->Name
== 'rsr.')
1800 /* Remember the PTEs so we can modify them later */
1801 MiKernelResourceStartPte
= MiAddressToPte(DllBase
+
1802 SectionHeader
->VirtualAddress
);
1803 MiKernelResourceEndPte
= MiKernelResourceStartPte
+
1804 BYTES_TO_PAGES(SectionHeader
->VirtualAddress
+ Size
);
1806 else if (*(PULONG
)SectionHeader
->Name
== 'LOOP')
1808 /* POOLCODE vs. POOLMI */
1809 if (*(PULONG
)&SectionHeader
->Name
[4] == 'EDOC')
1811 /* Found Ex* Pool code */
1812 ExPoolCodeStart
= DllBase
+ SectionHeader
->VirtualAddress
;
1813 ExPoolCodeEnd
= ExPoolCodeStart
+ Size
;
1815 else if (*(PUSHORT
)&SectionHeader
->Name
[4] == 'MI')
1817 /* Found Mm* Pool code */
1818 MmPoolCodeStart
= DllBase
+ SectionHeader
->VirtualAddress
;
1819 MmPoolCodeEnd
= ExPoolCodeStart
+ Size
;
1822 else if ((*(PULONG
)SectionHeader
->Name
== 'YSIM') &&
1823 (*(PULONG
)&SectionHeader
->Name
[4] == 'ETPS'))
1825 /* Found MISYSPTE (Mm System PTE code)*/
1826 MmPteCodeStart
= DllBase
+ SectionHeader
->VirtualAddress
;
1827 MmPteCodeEnd
= ExPoolCodeStart
+ Size
;
1838 MiInitializeLoadedModuleList(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
1840 PLDR_DATA_TABLE_ENTRY LdrEntry
, NewEntry
;
1841 PLIST_ENTRY ListHead
, NextEntry
;
1844 /* Setup the loaded module list and locks */
1845 ExInitializeResourceLite(&PsLoadedModuleResource
);
1846 KeInitializeSpinLock(&PsLoadedModuleSpinLock
);
1847 InitializeListHead(&PsLoadedModuleList
);
1849 /* Get loop variables and the kernel entry */
1850 ListHead
= &LoaderBlock
->LoadOrderListHead
;
1851 NextEntry
= ListHead
->Flink
;
1852 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1853 LDR_DATA_TABLE_ENTRY
,
1855 PsNtosImageBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
1857 /* Locate resource section, pool code, and system pte code */
1858 MiLocateKernelSections(LdrEntry
);
1860 /* Loop the loader block */
1861 while (NextEntry
!= ListHead
)
1863 /* Get the loader entry */
1864 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1865 LDR_DATA_TABLE_ENTRY
,
1868 /* FIXME: ROS HACK. Make sure this is a driver */
1869 if (!RtlImageNtHeader(LdrEntry
->DllBase
))
1871 /* Skip this entry */
1872 NextEntry
= NextEntry
->Flink
;
1876 /* Calculate the size we'll need and allocate a copy */
1877 EntrySize
= sizeof(LDR_DATA_TABLE_ENTRY
) +
1878 LdrEntry
->BaseDllName
.MaximumLength
+
1879 sizeof(UNICODE_NULL
);
1880 NewEntry
= ExAllocatePoolWithTag(NonPagedPool
, EntrySize
, TAG_LDR_WSTR
);
1881 if (!NewEntry
) return FALSE
;
1883 /* Copy the entry over */
1884 *NewEntry
= *LdrEntry
;
1886 /* Allocate the name */
1887 NewEntry
->FullDllName
.Buffer
=
1888 ExAllocatePoolWithTag(PagedPool
,
1889 LdrEntry
->FullDllName
.MaximumLength
+
1890 sizeof(UNICODE_NULL
),
1892 if (!NewEntry
->FullDllName
.Buffer
) return FALSE
;
1894 /* Set the base name */
1895 NewEntry
->BaseDllName
.Buffer
= (PVOID
)(NewEntry
+ 1);
1897 /* Copy the full and base name */
1898 RtlCopyMemory(NewEntry
->FullDllName
.Buffer
,
1899 LdrEntry
->FullDllName
.Buffer
,
1900 LdrEntry
->FullDllName
.MaximumLength
);
1901 RtlCopyMemory(NewEntry
->BaseDllName
.Buffer
,
1902 LdrEntry
->BaseDllName
.Buffer
,
1903 LdrEntry
->BaseDllName
.MaximumLength
);
1905 /* Null-terminate the base name */
1906 NewEntry
->BaseDllName
.Buffer
[NewEntry
->BaseDllName
.Length
/
1907 sizeof(WCHAR
)] = UNICODE_NULL
;
1909 /* Insert the entry into the list */
1910 InsertTailList(&PsLoadedModuleList
, &NewEntry
->InLoadOrderLinks
);
1911 NextEntry
= NextEntry
->Flink
;
1914 /* Build the import lists for the boot drivers */
1915 MiBuildImportsForBootDrivers();
1923 MiUseLargeDriverPage(IN ULONG NumberOfPtes
,
1924 IN OUT PVOID
*ImageBaseAddress
,
1925 IN PUNICODE_STRING BaseImageName
,
1926 IN BOOLEAN BootDriver
)
1928 PLIST_ENTRY NextEntry
;
1929 BOOLEAN DriverFound
= FALSE
;
1930 PMI_LARGE_PAGE_DRIVER_ENTRY LargePageDriverEntry
;
1931 ASSERT(KeGetCurrentIrql () <= APC_LEVEL
);
1932 ASSERT(*ImageBaseAddress
>= MmSystemRangeStart
);
1935 if (!(KeFeatureBits
& KF_LARGE_PAGE
)) return FALSE
;
1936 if (!(__readcr4() & CR4_PSE
)) return FALSE
;
1939 /* Make sure there's enough system PTEs for a large page driver */
1940 if (MmTotalFreeSystemPtes
[SystemPteSpace
] < (16 * (PDE_MAPPED_VA
>> PAGE_SHIFT
)))
1945 /* This happens if the registry key had a "*" (wildcard) in it */
1946 if (MiLargePageAllDrivers
== 0)
1948 /* It didn't, so scan the list */
1949 NextEntry
= MiLargePageDriverList
.Flink
;
1950 while (NextEntry
!= &MiLargePageDriverList
)
1952 /* Check if the driver name matches */
1953 LargePageDriverEntry
= CONTAINING_RECORD(NextEntry
,
1954 MI_LARGE_PAGE_DRIVER_ENTRY
,
1956 if (RtlEqualUnicodeString(BaseImageName
,
1957 &LargePageDriverEntry
->BaseName
,
1960 /* Enable large pages for this driver */
1966 NextEntry
= NextEntry
->Flink
;
1969 /* If we didn't find the driver, it doesn't need large pages */
1970 if (DriverFound
== FALSE
) return FALSE
;
1973 /* Nothing to do yet */
1974 DPRINT1("Large pages not supported!\n");
1980 MiComputeDriverProtection(IN BOOLEAN SessionSpace
,
1981 IN ULONG SectionProtection
)
1983 ULONG Protection
= MM_ZERO_ACCESS
;
1985 /* Check if the caller gave anything */
1986 if (SectionProtection
)
1988 /* Always turn on execute access */
1989 SectionProtection
|= IMAGE_SCN_MEM_EXECUTE
;
1991 /* Check if the registry setting is on or not */
1992 if (!MmEnforceWriteProtection
)
1994 /* Turn on write access too */
1995 SectionProtection
|= (IMAGE_SCN_MEM_WRITE
| IMAGE_SCN_MEM_EXECUTE
);
1999 /* Convert to internal PTE flags */
2000 if (SectionProtection
& IMAGE_SCN_MEM_EXECUTE
) Protection
|= MM_EXECUTE
;
2001 if (SectionProtection
& IMAGE_SCN_MEM_READ
) Protection
|= MM_READONLY
;
2003 /* Check for write access */
2004 if (SectionProtection
& IMAGE_SCN_MEM_WRITE
)
2006 /* Session space is not supported */
2009 DPRINT1("Session drivers not supported\n");
2010 ASSERT(SessionSpace
== FALSE
);
2014 /* Convert to internal PTE flag */
2015 Protection
= (Protection
& MM_EXECUTE
) ? MM_EXECUTE_READWRITE
: MM_READWRITE
;
2019 /* If there's no access at all by now, convert to internal no access flag */
2020 if (Protection
== MM_ZERO_ACCESS
) Protection
= MM_NOACCESS
;
2022 /* Return the computed PTE protection */
2028 MiSetSystemCodeProtection(IN PMMPTE FirstPte
,
2030 IN ULONG ProtectionMask
)
2032 /* I'm afraid to introduce regressions at the moment... */
2038 MiWriteProtectSystemImage(IN PVOID ImageBase
)
2040 PIMAGE_NT_HEADERS NtHeaders
;
2041 PIMAGE_SECTION_HEADER Section
;
2042 PFN_NUMBER DriverPages
;
2043 ULONG CurrentProtection
, SectionProtection
, CombinedProtection
, ProtectionMask
;
2044 ULONG Sections
, Size
;
2045 ULONG_PTR BaseAddress
, CurrentAddress
;
2046 PMMPTE PointerPte
, StartPte
, LastPte
, CurrentPte
, ComboPte
= NULL
;
2047 ULONG CurrentMask
, CombinedMask
= 0;
2050 /* No need to write protect physical memory-backed drivers (large pages) */
2051 if (MI_IS_PHYSICAL_ADDRESS(ImageBase
)) return;
2053 /* Get the image headers */
2054 NtHeaders
= RtlImageNtHeader(ImageBase
);
2055 if (!NtHeaders
) return;
2057 /* Check if this is a session driver or not */
2058 if (!MI_IS_SESSION_ADDRESS(ImageBase
))
2060 /* Don't touch NT4 drivers */
2061 if (NtHeaders
->OptionalHeader
.MajorOperatingSystemVersion
< 5) return;
2062 if (NtHeaders
->OptionalHeader
.MajorImageVersion
< 5) return;
2067 DPRINT1("Session drivers not supported\n");
2071 /* These are the only protection masks we care about */
2072 ProtectionMask
= IMAGE_SCN_MEM_WRITE
| IMAGE_SCN_MEM_READ
| IMAGE_SCN_MEM_EXECUTE
;
2074 /* Calculate the number of pages this driver is occupying */
2075 DriverPages
= BYTES_TO_PAGES(NtHeaders
->OptionalHeader
.SizeOfImage
);
2077 /* Get the number of sections and the first section header */
2078 Sections
= NtHeaders
->FileHeader
.NumberOfSections
;
2079 ASSERT(Sections
!= 0);
2080 Section
= IMAGE_FIRST_SECTION(NtHeaders
);
2082 /* Loop all the sections */
2083 CurrentAddress
= (ULONG_PTR
)ImageBase
;
2086 /* Get the section size */
2087 Size
= max(Section
->SizeOfRawData
, Section
->Misc
.VirtualSize
);
2089 /* Get its virtual address */
2090 BaseAddress
= (ULONG_PTR
)ImageBase
+ Section
->VirtualAddress
;
2091 if (BaseAddress
< CurrentAddress
)
2093 /* Windows doesn't like these */
2094 DPRINT1("Badly linked image!\n");
2098 /* Remember the current address */
2099 CurrentAddress
= BaseAddress
+ Size
- 1;
2106 /* Get the number of sections and the first section header */
2107 Sections
= NtHeaders
->FileHeader
.NumberOfSections
;
2108 ASSERT(Sections
!= 0);
2109 Section
= IMAGE_FIRST_SECTION(NtHeaders
);
2111 /* Set the address at the end to initialize the loop */
2112 CurrentAddress
= (ULONG_PTR
)Section
+ Sections
- 1;
2113 CurrentProtection
= IMAGE_SCN_MEM_WRITE
| IMAGE_SCN_MEM_READ
;
2115 /* Set the PTE points for the image, and loop its sections */
2116 StartPte
= MiAddressToPte(ImageBase
);
2117 LastPte
= StartPte
+ DriverPages
;
2120 /* Get the section size */
2121 Size
= max(Section
->SizeOfRawData
, Section
->Misc
.VirtualSize
);
2123 /* Get its virtual address and PTE */
2124 BaseAddress
= (ULONG_PTR
)ImageBase
+ Section
->VirtualAddress
;
2125 PointerPte
= MiAddressToPte(BaseAddress
);
2127 /* Check if we were already protecting a run, and found a new run */
2128 if ((ComboPte
) && (PointerPte
> ComboPte
))
2130 /* Compute protection */
2131 CombinedMask
= MiComputeDriverProtection(FALSE
, CombinedProtection
);
2134 MiSetSystemCodeProtection(ComboPte
, ComboPte
, CombinedMask
);
2136 /* Check for overlap */
2137 if (ComboPte
== StartPte
) StartPte
++;
2139 /* One done, reset variables */
2141 CombinedProtection
= 0;
2144 /* Break out when needed */
2145 if (PointerPte
>= LastPte
) break;
2147 /* Get the requested protection from the image header */
2148 SectionProtection
= Section
->Characteristics
& ProtectionMask
;
2149 if (SectionProtection
== CurrentProtection
)
2151 /* Same protection, so merge the request */
2152 CurrentAddress
= BaseAddress
+ Size
- 1;
2160 /* This is now a new section, so close up the old one */
2161 CurrentPte
= MiAddressToPte(CurrentAddress
);
2163 /* Check for overlap */
2164 if (CurrentPte
== PointerPte
)
2166 /* Skip the last PTE, since it overlaps with us */
2169 /* And set the PTE we will merge with */
2170 ASSERT((ComboPte
== NULL
) || (ComboPte
== PointerPte
));
2171 ComboPte
= PointerPte
;
2173 /* Get the most flexible protection by merging both */
2174 CombinedMask
|= (SectionProtection
| CurrentProtection
);
2177 /* Loop any PTEs left */
2178 if (CurrentPte
>= StartPte
)
2181 ASSERT(StartPte
< LastPte
);
2183 /* Make sure we don't overflow past the last PTE in the driver */
2184 if (CurrentPte
>= LastPte
) CurrentPte
= LastPte
- 1;
2185 ASSERT(CurrentPte
>= StartPte
);
2187 /* Compute the protection and set it */
2188 CurrentMask
= MiComputeDriverProtection(FALSE
, CurrentProtection
);
2189 MiSetSystemCodeProtection(StartPte
, CurrentPte
, CurrentMask
);
2193 StartPte
= PointerPte
;
2194 CurrentAddress
= BaseAddress
+ Size
- 1;
2195 CurrentProtection
= SectionProtection
;
2202 /* Is there a leftover section to merge? */
2205 /* Compute and set the protection */
2206 CombinedMask
= MiComputeDriverProtection(FALSE
, CombinedProtection
);
2207 MiSetSystemCodeProtection(ComboPte
, ComboPte
, CombinedMask
);
2209 /* Handle overlap */
2210 if (ComboPte
== StartPte
) StartPte
++;
2213 /* Finally, handle the last section */
2214 CurrentPte
= MiAddressToPte(CurrentAddress
);
2215 if ((StartPte
< LastPte
) && (CurrentPte
>= StartPte
))
2217 /* Handle overlap */
2218 if (CurrentPte
>= LastPte
) CurrentPte
= LastPte
- 1;
2219 ASSERT(CurrentPte
>= StartPte
);
2221 /* Compute and set the protection */
2222 CurrentMask
= MiComputeDriverProtection(FALSE
, CurrentProtection
);
2223 MiSetSystemCodeProtection(StartPte
, CurrentPte
, CurrentMask
);
2229 MiSetPagingOfDriver(IN PMMPTE PointerPte
,
2233 PETHREAD CurrentThread
= PsGetCurrentThread();
2234 PFN_NUMBER PageCount
= 0, PageFrameIndex
;
2238 /* Get the driver's base address */
2239 ImageBase
= MiPteToAddress(PointerPte
);
2240 ASSERT(MI_IS_SESSION_IMAGE_ADDRESS(ImageBase
) == FALSE
);
2242 /* If this is a large page, it's stuck in physical memory */
2243 if (MI_IS_PHYSICAL_ADDRESS(ImageBase
)) return;
2245 /* Lock the working set */
2246 MiLockWorkingSet(CurrentThread
, &MmSystemCacheWs
);
2249 while (PointerPte
<= LastPte
)
2251 /* Check for valid PTE */
2252 if (PointerPte
->u
.Hard
.Valid
== 1)
2254 PageFrameIndex
= PFN_FROM_PTE(PointerPte
);
2255 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
2256 ASSERT(Pfn1
->u2
.ShareCount
== 1);
2258 /* No working sets in ReactOS yet */
2262 ImageBase
= (PVOID
)((ULONG_PTR
)ImageBase
+ PAGE_SIZE
);
2266 /* Release the working set */
2267 MiUnlockWorkingSet(CurrentThread
, &MmSystemCacheWs
);
2269 /* Do we have any driver pages? */
2272 /* Update counters */
2273 InterlockedExchangeAdd((PLONG
)&MmTotalSystemDriverPages
, PageCount
);
2279 MiEnablePagingOfDriver(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
2281 ULONG_PTR ImageBase
;
2282 PIMAGE_NT_HEADERS NtHeaders
;
2283 ULONG Sections
, Alignment
, Size
;
2284 PIMAGE_SECTION_HEADER Section
;
2285 PMMPTE PointerPte
= NULL
, LastPte
= NULL
;
2286 if (MmDisablePagingExecutive
) return;
2288 /* Get the driver base address and its NT header */
2289 ImageBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
2290 NtHeaders
= RtlImageNtHeader((PVOID
)ImageBase
);
2291 if (!NtHeaders
) return;
2293 /* Get the sections and their alignment */
2294 Sections
= NtHeaders
->FileHeader
.NumberOfSections
;
2295 Alignment
= NtHeaders
->OptionalHeader
.SectionAlignment
- 1;
2297 /* Loop each section */
2298 Section
= IMAGE_FIRST_SECTION(NtHeaders
);
2301 /* Find PAGE or .edata */
2302 if ((*(PULONG
)Section
->Name
== 'EGAP') ||
2303 (*(PULONG
)Section
->Name
== 'ade.'))
2305 /* Had we already done some work? */
2308 /* Nope, setup the first PTE address */
2309 PointerPte
= MiAddressToPte(ROUND_TO_PAGES(ImageBase
+
2314 /* Compute the size */
2315 Size
= max(Section
->SizeOfRawData
, Section
->Misc
.VirtualSize
);
2317 /* Find the last PTE that maps this section */
2318 LastPte
= MiAddressToPte(ImageBase
+
2319 Section
->VirtualAddress
+
2326 /* Had we found a section before? */
2329 /* Mark it as pageable */
2330 MiSetPagingOfDriver(PointerPte
, LastPte
);
2335 /* Keep searching */
2340 /* Handle the straggler */
2341 if (PointerPte
) MiSetPagingOfDriver(PointerPte
, LastPte
);
2346 MmVerifyImageIsOkForMpUse(IN PVOID BaseAddress
)
2348 PIMAGE_NT_HEADERS NtHeader
;
2351 /* Get NT Headers */
2352 NtHeader
= RtlImageNtHeader(BaseAddress
);
2355 /* Check if this image is only safe for UP while we have 2+ CPUs */
2356 if ((KeNumberProcessors
> 1) &&
2357 (NtHeader
->FileHeader
.Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
))
2364 /* Otherwise, it's safe */
2370 MmCheckSystemImage(IN HANDLE ImageHandle
,
2371 IN BOOLEAN PurgeSection
)
2374 HANDLE SectionHandle
;
2375 PVOID ViewBase
= NULL
;
2376 SIZE_T ViewSize
= 0;
2377 IO_STATUS_BLOCK IoStatusBlock
;
2378 FILE_STANDARD_INFORMATION FileStandardInfo
;
2379 KAPC_STATE ApcState
;
2380 PIMAGE_NT_HEADERS NtHeaders
;
2381 OBJECT_ATTRIBUTES ObjectAttributes
;
2384 /* Setup the object attributes */
2385 InitializeObjectAttributes(&ObjectAttributes
,
2387 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2391 /* Create a section for the DLL */
2392 Status
= ZwCreateSection(&SectionHandle
,
2393 SECTION_MAP_EXECUTE
,
2399 if (!NT_SUCCESS(Status
)) return Status
;
2401 /* Make sure we're in the system process */
2402 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
2405 Status
= ZwMapViewOfSection(SectionHandle
,
2415 if (!NT_SUCCESS(Status
))
2417 /* We failed, close the handle and return */
2418 KeUnstackDetachProcess(&ApcState
);
2419 ZwClose(SectionHandle
);
2423 /* Now query image information */
2424 Status
= ZwQueryInformationFile(ImageHandle
,
2427 sizeof(FileStandardInfo
),
2428 FileStandardInformation
);
2429 if (NT_SUCCESS(Status
))
2431 /* First, verify the checksum */
2432 if (!LdrVerifyMappedImageMatchesChecksum(ViewBase
,
2437 /* Set checksum failure */
2438 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
2442 /* Make sure it's a real image */
2443 NtHeaders
= RtlImageNtHeader(ViewBase
);
2446 /* Set checksum failure */
2447 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
2451 /* Make sure it's for the correct architecture */
2452 if ((NtHeaders
->FileHeader
.Machine
!= IMAGE_FILE_MACHINE_NATIVE
) ||
2453 (NtHeaders
->OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR_MAGIC
))
2455 /* Set protection failure */
2456 Status
= STATUS_INVALID_IMAGE_PROTECT
;
2460 /* Check that it's a valid SMP image if we have more then one CPU */
2461 if (!MmVerifyImageIsOkForMpUse(ViewBase
))
2463 /* Otherwise it's not the right image */
2464 Status
= STATUS_IMAGE_MP_UP_MISMATCH
;
2468 /* Unmap the section, close the handle, and return status */
2470 ZwUnmapViewOfSection(NtCurrentProcess(), ViewBase
);
2471 KeUnstackDetachProcess(&ApcState
);
2472 ZwClose(SectionHandle
);
2478 MmLoadSystemImage(IN PUNICODE_STRING FileName
,
2479 IN PUNICODE_STRING NamePrefix OPTIONAL
,
2480 IN PUNICODE_STRING LoadedName OPTIONAL
,
2482 OUT PVOID
*ModuleObject
,
2483 OUT PVOID
*ImageBaseAddress
)
2485 PVOID ModuleLoadBase
= NULL
;
2487 HANDLE FileHandle
= NULL
;
2488 OBJECT_ATTRIBUTES ObjectAttributes
;
2489 IO_STATUS_BLOCK IoStatusBlock
;
2490 PIMAGE_NT_HEADERS NtHeader
;
2491 UNICODE_STRING BaseName
, BaseDirectory
, PrefixName
, UnicodeTemp
;
2492 PLDR_DATA_TABLE_ENTRY LdrEntry
= NULL
;
2493 ULONG EntrySize
, DriverSize
;
2494 PLOAD_IMPORTS LoadedImports
= MM_SYSLDR_NO_IMPORTS
;
2495 PCHAR MissingApiName
, Buffer
;
2496 PWCHAR MissingDriverName
;
2497 HANDLE SectionHandle
;
2498 ACCESS_MASK DesiredAccess
;
2499 PVOID Section
= NULL
;
2500 BOOLEAN LockOwned
= FALSE
;
2501 PLIST_ENTRY NextEntry
;
2502 IMAGE_INFO ImageInfo
;
2506 /* Detect session-load */
2510 ASSERT(NamePrefix
== NULL
);
2511 ASSERT(LoadedName
== NULL
);
2513 /* Make sure the process is in session too */
2514 if (!PsGetCurrentProcess()->ProcessInSession
) return STATUS_NO_MEMORY
;
2517 /* Allocate a buffer we'll use for names */
2518 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, 'nLmM');
2519 if (!Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
2521 /* Check for a separator */
2522 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
2527 /* Loop the path until we get to the base name */
2528 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
2529 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
2531 /* Get the length */
2532 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
2533 BaseLength
*= sizeof(WCHAR
);
2535 /* Setup the string */
2536 BaseName
.Length
= (USHORT
)BaseLength
;
2537 BaseName
.Buffer
= p
;
2541 /* Otherwise, we already have a base name */
2542 BaseName
.Length
= FileName
->Length
;
2543 BaseName
.Buffer
= FileName
->Buffer
;
2546 /* Setup the maximum length */
2547 BaseName
.MaximumLength
= BaseName
.Length
;
2549 /* Now compute the base directory */
2550 BaseDirectory
= *FileName
;
2551 BaseDirectory
.Length
-= BaseName
.Length
;
2552 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
2554 /* And the prefix, which for now is just the name itself */
2555 PrefixName
= *FileName
;
2557 /* Check if we have a prefix */
2558 if (NamePrefix
) DPRINT1("Prefixed images are not yet supported!\n");
2560 /* Check if we already have a name, use it instead */
2561 if (LoadedName
) BaseName
= *LoadedName
;
2563 /* Check for loader snap debugging */
2564 if (NtGlobalFlag
& FLG_SHOW_LDR_SNAPS
)
2566 /* Print out standard string */
2567 DPRINT1("MM:SYSLDR Loading %wZ (%wZ) %s\n",
2568 &PrefixName
, &BaseName
, Flags
? "in session space" : "");
2571 /* Acquire the load lock */
2573 ASSERT(LockOwned
== FALSE
);
2575 KeEnterCriticalRegion();
2576 KeWaitForSingleObject(&MmSystemLoadLock
,
2582 /* Scan the module list */
2583 NextEntry
= PsLoadedModuleList
.Flink
;
2584 while (NextEntry
!= &PsLoadedModuleList
)
2586 /* Get the entry and compare the names */
2587 LdrEntry
= CONTAINING_RECORD(NextEntry
,
2588 LDR_DATA_TABLE_ENTRY
,
2590 if (RtlEqualUnicodeString(&PrefixName
, &LdrEntry
->FullDllName
, TRUE
))
2592 /* Found it, break out */
2597 NextEntry
= NextEntry
->Flink
;
2600 /* Check if we found the image */
2601 if (NextEntry
!= &PsLoadedModuleList
)
2603 /* Check if we had already mapped a section */
2606 /* Dereference and clear */
2607 ObDereferenceObject(Section
);
2611 /* Check if this was supposed to be a session load */
2614 /* It wasn't, so just return the data */
2615 *ModuleObject
= LdrEntry
;
2616 *ImageBaseAddress
= LdrEntry
->DllBase
;
2617 Status
= STATUS_IMAGE_ALREADY_LOADED
;
2621 /* We don't support session loading yet */
2622 DPRINT1("Unsupported Session-Load!\n");
2631 /* It wasn't loaded, and we didn't have a previous attempt */
2632 KeReleaseMutant(&MmSystemLoadLock
, 1, FALSE
, FALSE
);
2633 KeLeaveCriticalRegion();
2636 /* Check if KD is enabled */
2637 if ((KdDebuggerEnabled
) && !(KdDebuggerNotPresent
))
2639 /* FIXME: Attempt to get image from KD */
2642 /* We don't have a valid entry */
2645 /* Setup image attributes */
2646 InitializeObjectAttributes(&ObjectAttributes
,
2648 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2652 /* Open the image */
2653 Status
= ZwOpenFile(&FileHandle
,
2657 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2659 if (!NT_SUCCESS(Status
)) goto Quickie
;
2662 Status
= MmCheckSystemImage(FileHandle
, FALSE
);
2663 if ((Status
== STATUS_IMAGE_CHECKSUM_MISMATCH
) ||
2664 (Status
== STATUS_IMAGE_MP_UP_MISMATCH
) ||
2665 (Status
== STATUS_INVALID_IMAGE_PROTECT
))
2671 /* Check if this is a session-load */
2674 /* Then we only need read and execute */
2675 DesiredAccess
= SECTION_MAP_READ
| SECTION_MAP_EXECUTE
;
2679 /* Otherwise, we can allow write access */
2680 DesiredAccess
= SECTION_ALL_ACCESS
;
2683 /* Initialize the attributes for the section */
2684 InitializeObjectAttributes(&ObjectAttributes
,
2686 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2690 /* Create the section */
2691 Status
= ZwCreateSection(&SectionHandle
,
2698 if (!NT_SUCCESS(Status
)) goto Quickie
;
2700 /* Now get the section pointer */
2701 Status
= ObReferenceObjectByHandle(SectionHandle
,
2702 SECTION_MAP_EXECUTE
,
2703 MmSectionObjectType
,
2707 ZwClose(SectionHandle
);
2708 if (!NT_SUCCESS(Status
)) goto Quickie
;
2710 /* Check if this was supposed to be a session-load */
2713 /* We don't support session loading yet */
2714 DPRINT1("Unsupported Session-Load!\n");
2718 /* Check the loader list again, we should end up in the path below */
2723 /* We don't have a valid entry */
2727 /* Load the image */
2728 Status
= MiLoadImageSection(&Section
,
2733 ASSERT(Status
!= STATUS_ALREADY_COMMITTED
);
2735 /* Get the size of the driver */
2736 DriverSize
= ((PROS_SECTION_OBJECT
)Section
)->ImageSection
->ImageSize
;
2738 /* Make sure we're not being loaded into session space */
2741 /* Check for success */
2742 if (NT_SUCCESS(Status
))
2744 /* Support large pages for drivers */
2745 MiUseLargeDriverPage(DriverSize
/ PAGE_SIZE
,
2751 /* Dereference the section */
2752 ObDereferenceObject(Section
);
2756 /* Check for failure of the load earlier */
2757 if (!NT_SUCCESS(Status
)) goto Quickie
;
2759 /* Relocate the driver */
2760 Status
= LdrRelocateImageWithBias(ModuleLoadBase
,
2764 STATUS_CONFLICTING_ADDRESSES
,
2765 STATUS_INVALID_IMAGE_FORMAT
);
2766 if (!NT_SUCCESS(Status
)) goto Quickie
;
2769 /* Get the NT Header */
2770 NtHeader
= RtlImageNtHeader(ModuleLoadBase
);
2772 /* Calculate the size we'll need for the entry and allocate it */
2773 EntrySize
= sizeof(LDR_DATA_TABLE_ENTRY
) +
2775 sizeof(UNICODE_NULL
);
2777 /* Allocate the entry */
2778 LdrEntry
= ExAllocatePoolWithTag(NonPagedPool
, EntrySize
, TAG_MODULE_OBJECT
);
2782 Status
= STATUS_INSUFFICIENT_RESOURCES
;
2786 /* Setup the entry */
2787 LdrEntry
->Flags
= LDRP_LOAD_IN_PROGRESS
;
2788 LdrEntry
->LoadCount
= 1;
2789 LdrEntry
->LoadedImports
= LoadedImports
;
2790 LdrEntry
->PatchInformation
= NULL
;
2792 /* Check the version */
2793 if ((NtHeader
->OptionalHeader
.MajorOperatingSystemVersion
>= 5) &&
2794 (NtHeader
->OptionalHeader
.MajorImageVersion
>= 5))
2796 /* Mark this image as a native image */
2797 LdrEntry
->Flags
|= LDRP_ENTRY_NATIVE
;
2800 /* Setup the rest of the entry */
2801 LdrEntry
->DllBase
= ModuleLoadBase
;
2802 LdrEntry
->EntryPoint
= (PVOID
)((ULONG_PTR
)ModuleLoadBase
+
2803 NtHeader
->OptionalHeader
.AddressOfEntryPoint
);
2804 LdrEntry
->SizeOfImage
= DriverSize
;
2805 LdrEntry
->CheckSum
= NtHeader
->OptionalHeader
.CheckSum
;
2806 LdrEntry
->SectionPointer
= Section
;
2808 /* Now write the DLL name */
2809 LdrEntry
->BaseDllName
.Buffer
= (PVOID
)(LdrEntry
+ 1);
2810 LdrEntry
->BaseDllName
.Length
= BaseName
.Length
;
2811 LdrEntry
->BaseDllName
.MaximumLength
= BaseName
.Length
;
2813 /* Copy and null-terminate it */
2814 RtlCopyMemory(LdrEntry
->BaseDllName
.Buffer
,
2817 LdrEntry
->BaseDllName
.Buffer
[BaseName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
2819 /* Now allocate the full name */
2820 LdrEntry
->FullDllName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
2822 sizeof(UNICODE_NULL
),
2824 if (!LdrEntry
->FullDllName
.Buffer
)
2826 /* Don't fail, just set it to zero */
2827 LdrEntry
->FullDllName
.Length
= 0;
2828 LdrEntry
->FullDllName
.MaximumLength
= 0;
2833 LdrEntry
->FullDllName
.Length
= PrefixName
.Length
;
2834 LdrEntry
->FullDllName
.MaximumLength
= PrefixName
.Length
;
2836 /* Copy and null-terminate */
2837 RtlCopyMemory(LdrEntry
->FullDllName
.Buffer
,
2840 LdrEntry
->FullDllName
.Buffer
[PrefixName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
2844 MiProcessLoaderEntry(LdrEntry
, TRUE
);
2846 /* Resolve imports */
2847 MissingApiName
= Buffer
;
2848 Status
= MiResolveImageReferences(ModuleLoadBase
,
2854 if (!NT_SUCCESS(Status
))
2857 MiProcessLoaderEntry(LdrEntry
, FALSE
);
2859 /* Check if we need to free the name */
2860 if (LdrEntry
->FullDllName
.Buffer
)
2863 ExFreePool(LdrEntry
->FullDllName
.Buffer
);
2866 /* Free the entry itself */
2867 ExFreePoolWithTag(LdrEntry
, TAG_MODULE_OBJECT
);
2872 /* Update the loader entry */
2873 LdrEntry
->Flags
|= (LDRP_SYSTEM_MAPPED
|
2874 LDRP_ENTRY_PROCESSED
|
2876 LdrEntry
->Flags
&= ~LDRP_LOAD_IN_PROGRESS
;
2877 LdrEntry
->LoadedImports
= LoadedImports
;
2879 /* FIXME: Call driver verifier's loader function */
2881 /* Write-protect the system image */
2882 MiWriteProtectSystemImage(LdrEntry
->DllBase
);
2884 /* Check if notifications are enabled */
2885 if (PsImageNotifyEnabled
)
2887 /* Fill out the notification data */
2888 ImageInfo
.Properties
= 0;
2889 ImageInfo
.ImageAddressingMode
= IMAGE_ADDRESSING_MODE_32BIT
;
2890 ImageInfo
.SystemModeImage
= TRUE
;
2891 ImageInfo
.ImageSize
= LdrEntry
->SizeOfImage
;
2892 ImageInfo
.ImageBase
= LdrEntry
->DllBase
;
2893 ImageInfo
.ImageSectionNumber
= ImageInfo
.ImageSelector
= 0;
2895 /* Send the notification */
2896 PspRunLoadImageNotifyRoutines(FileName
, NULL
, &ImageInfo
);
2899 #if defined(KDBG) || defined(_WINKD_)
2900 /* MiCacheImageSymbols doesn't detect rossym */
2903 /* Check if there's symbols */
2904 if (MiCacheImageSymbols(LdrEntry
->DllBase
))
2907 /* Check if the system root is present */
2908 if ((PrefixName
.Length
> (11 * sizeof(WCHAR
))) &&
2909 !(_wcsnicmp(PrefixName
.Buffer
, L
"\\SystemRoot", 11)))
2911 /* Add the system root */
2912 UnicodeTemp
= PrefixName
;
2913 UnicodeTemp
.Buffer
+= 11;
2914 UnicodeTemp
.Length
-= (11 * sizeof(WCHAR
));
2917 &SharedUserData
->NtSystemRoot
[2],
2922 /* Build the name */
2923 sprintf_nt(Buffer
, "%wZ", &BaseName
);
2926 /* Setup the ansi string */
2927 RtlInitString(&AnsiTemp
, Buffer
);
2929 /* Notify the debugger */
2930 DbgLoadImageSymbols(&AnsiTemp
,
2932 (ULONG_PTR
)ZwCurrentProcess());
2933 LdrEntry
->Flags
|= LDRP_DEBUG_SYMBOLS_LOADED
;
2936 /* Page the driver */
2937 ASSERT(Section
== NULL
);
2938 MiEnablePagingOfDriver(LdrEntry
);
2940 /* Return pointers */
2941 *ModuleObject
= LdrEntry
;
2942 *ImageBaseAddress
= LdrEntry
->DllBase
;
2945 /* Check if we have the lock acquired */
2948 /* Release the lock */
2949 KeReleaseMutant(&MmSystemLoadLock
, 1, FALSE
, FALSE
);
2950 KeLeaveCriticalRegion();
2954 /* If we have a file handle, close it */
2955 if (FileHandle
) ZwClose(FileHandle
);
2957 /* Check if we had a prefix */
2958 if (NamePrefix
) ExFreePool(PrefixName
.Buffer
);
2960 /* Free the name buffer and return status */
2961 ExFreePoolWithTag(Buffer
, TAG_LDR_WSTR
);
2965 PLDR_DATA_TABLE_ENTRY
2967 MiLookupDataTableEntry(IN PVOID Address
)
2969 PLDR_DATA_TABLE_ENTRY LdrEntry
, FoundEntry
= NULL
;
2970 PLIST_ENTRY NextEntry
;
2974 NextEntry
= PsLoadedModuleList
.Flink
;
2977 /* Get the loader entry */
2978 LdrEntry
= CONTAINING_RECORD(NextEntry
,
2979 LDR_DATA_TABLE_ENTRY
,
2982 /* Check if the address matches */
2983 if ((Address
>= LdrEntry
->DllBase
) &&
2984 (Address
< (PVOID
)((ULONG_PTR
)LdrEntry
->DllBase
+
2985 LdrEntry
->SizeOfImage
)))
2988 FoundEntry
= LdrEntry
;
2993 NextEntry
= NextEntry
->Flink
;
2994 } while(NextEntry
!= &PsLoadedModuleList
);
2996 /* Return the entry */
3000 /* PUBLIC FUNCTIONS ***********************************************************/
3007 MmPageEntireDriver(IN PVOID AddressWithinSection
)
3009 PMMPTE StartPte
, EndPte
;
3010 PLDR_DATA_TABLE_ENTRY LdrEntry
;
3013 /* Get the loader entry */
3014 LdrEntry
= MiLookupDataTableEntry(AddressWithinSection
);
3015 if (!LdrEntry
) return NULL
;
3017 /* Check if paging of kernel mode is disabled or if the driver is mapped as an image */
3018 if ((MmDisablePagingExecutive
) || (LdrEntry
->SectionPointer
))
3020 /* Don't do anything, just return the base address */
3021 return LdrEntry
->DllBase
;
3024 /* Wait for active DPCs to finish before we page out the driver */
3025 KeFlushQueuedDpcs();
3027 /* Get the PTE range for the whole driver image */
3028 StartPte
= MiAddressToPte((ULONG_PTR
)LdrEntry
->DllBase
);
3029 EndPte
= MiAddressToPte((ULONG_PTR
)LdrEntry
->DllBase
+ LdrEntry
->SizeOfImage
);
3031 /* Enable paging for the PTE range */
3032 ASSERT(MI_IS_SESSION_IMAGE_ADDRESS(AddressWithinSection
) == FALSE
);
3033 MiSetPagingOfDriver(StartPte
, EndPte
);
3035 /* Return the base address */
3036 return LdrEntry
->DllBase
;
3044 MmResetDriverPaging(IN PVOID AddressWithinSection
)
3054 MmGetSystemRoutineAddress(IN PUNICODE_STRING SystemRoutineName
)
3056 PVOID ProcAddress
= NULL
;
3057 ANSI_STRING AnsiRoutineName
;
3059 PLIST_ENTRY NextEntry
;
3060 PLDR_DATA_TABLE_ENTRY LdrEntry
;
3061 BOOLEAN Found
= FALSE
;
3062 UNICODE_STRING KernelName
= RTL_CONSTANT_STRING(L
"ntoskrnl.exe");
3063 UNICODE_STRING HalName
= RTL_CONSTANT_STRING(L
"hal.dll");
3066 /* Convert routine to ansi name */
3067 Status
= RtlUnicodeStringToAnsiString(&AnsiRoutineName
,
3070 if (!NT_SUCCESS(Status
)) return NULL
;
3073 KeEnterCriticalRegion();
3074 ExAcquireResourceSharedLite(&PsLoadedModuleResource
, TRUE
);
3076 /* Loop the loaded module list */
3077 NextEntry
= PsLoadedModuleList
.Flink
;
3078 while (NextEntry
!= &PsLoadedModuleList
)
3081 LdrEntry
= CONTAINING_RECORD(NextEntry
,
3082 LDR_DATA_TABLE_ENTRY
,
3085 /* Check if it's the kernel or HAL */
3086 if (RtlEqualUnicodeString(&KernelName
, &LdrEntry
->BaseDllName
, TRUE
))
3092 else if (RtlEqualUnicodeString(&HalName
, &LdrEntry
->BaseDllName
, TRUE
))
3099 /* Check if we found a valid binary */
3102 /* Find the procedure name */
3103 ProcAddress
= MiFindExportedRoutineByName(LdrEntry
->DllBase
,
3106 /* Break out if we found it or if we already tried both modules */
3107 if (ProcAddress
) break;
3108 if (Modules
== 2) break;
3112 NextEntry
= NextEntry
->Flink
;
3115 /* Release the lock */
3116 ExReleaseResourceLite(&PsLoadedModuleResource
);
3117 KeLeaveCriticalRegion();
3119 /* Free the string and return */
3120 RtlFreeAnsiString(&AnsiRoutineName
);