2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/mm/sysldr.c
5 * PURPOSE: Contains the Kernel Loader (SYSLDR) for loading PE files.
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
9 /* INCLUDES ******************************************************************/
15 /* GCC's incompetence strikes again */
18 sprintf_nt(IN PCHAR Buffer
,
24 vsprintf(Buffer
, Format
, ap
);
28 /* GLOBALS *******************************************************************/
30 LIST_ENTRY PsLoadedModuleList
;
31 KSPIN_LOCK PsLoadedModuleSpinLock
;
32 ULONG PsNtosImageBase
;
33 KMUTANT MmSystemLoadLock
;
34 extern ULONG NtGlobalFlag
;
36 /* FUNCTIONS *****************************************************************/
40 MiCacheImageSymbols(IN PVOID BaseAddress
)
43 PVOID DebugDirectory
= NULL
;
46 /* Make sure it's safe to access the image */
49 /* Get the debug directory */
50 DebugDirectory
= RtlImageDirectoryEntryToData(BaseAddress
,
52 IMAGE_DIRECTORY_ENTRY_DEBUG
,
61 /* Return the directory */
62 return DebugDirectory
;
67 MiFreeBootDriverMemory(PVOID BaseAddress
,
73 for (i
= 0; i
< PAGE_ROUND_UP(Length
) / PAGE_SIZE
; i
++)
76 MmDeleteVirtualMapping(NULL
,
77 (PVOID
)((ULONG_PTR
)BaseAddress
+ i
* PAGE_SIZE
),
86 MiLoadImageSection(IN OUT PVOID
*SectionPtr
,
88 IN PUNICODE_STRING FileName
,
89 IN BOOLEAN SessionLoad
,
90 IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
92 PROS_SECTION_OBJECT Section
= *SectionPtr
;
98 LARGE_INTEGER SectionOffset
= {{0}};
99 BOOLEAN LoadSymbols
= FALSE
;
104 /* Detect session load */
108 DPRINT1("Session loading not yet supported!\n");
112 /* Not session load, shouldn't have an entry */
113 ASSERT(LdrEntry
== NULL
);
115 /* Attach to the system process */
116 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
118 /* Check if we need to load symbols */
119 if (NtGlobalFlag
& FLG_ENABLE_KDEBUG_SYMBOL_LOAD
)
123 NtGlobalFlag
&= ~FLG_ENABLE_KDEBUG_SYMBOL_LOAD
;
127 Process
= PsGetCurrentProcess();
128 Status
= MmMapViewOfSection(Section
,
139 /* Re-enable the flag */
140 if (LoadSymbols
) NtGlobalFlag
|= FLG_ENABLE_KDEBUG_SYMBOL_LOAD
;
142 /* Check if we failed with distinguished status code */
143 if (Status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
)
145 /* Change it to something more generic */
146 Status
= STATUS_INVALID_IMAGE_FORMAT
;
149 /* Now check if we failed */
150 if (!NT_SUCCESS(Status
))
152 /* Detach and return */
153 KeUnstackDetachProcess(&ApcState
);
157 /* Get the driver size */
158 DriverSize
= Section
->ImageSection
->ImageSize
;
160 /* Allocate a virtual section for the module */
161 DriverBase
= MmAllocateSection(DriverSize
, NULL
);
162 *ImageBase
= DriverBase
;
165 RtlCopyMemory(DriverBase
, Base
, DriverSize
);
167 /* Now unmap the view */
168 Status
= MmUnmapViewOfSection(Process
, Base
);
169 ASSERT(NT_SUCCESS(Status
));
171 /* Detach and return status */
172 KeUnstackDetachProcess(&ApcState
);
178 MiDereferenceImports(IN PLOAD_IMPORTS ImportList
)
182 /* Check if there's no imports or if we're a boot driver */
183 if ((ImportList
== (PVOID
)-1) ||
184 (ImportList
== (PVOID
)-2) ||
185 (ImportList
->Count
== 0))
187 /* Then there's nothing to do */
188 return STATUS_SUCCESS
;
191 /* Otherwise, FIXME */
192 DPRINT1("%u imports not dereferenced!\n", ImportList
->Count
);
193 for (i
= 0; i
< ImportList
->Count
; i
++)
195 DPRINT1("%wZ <%wZ>\n", &ImportList
->Entry
[i
]->FullDllName
, &ImportList
->Entry
[i
]->BaseDllName
);
197 return STATUS_UNSUCCESSFUL
;
202 MiClearImports(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
206 /* Check if there's no imports or we're a boot driver or only one entry */
207 if ((LdrEntry
->LoadedImports
== (PVOID
)-1) ||
208 (LdrEntry
->LoadedImports
== (PVOID
)-2) ||
209 ((ULONG_PTR
)LdrEntry
->LoadedImports
& 1))
215 /* Otherwise, free the import list */
216 ExFreePool(LdrEntry
->LoadedImports
);
221 MiFindExportedRoutineByName(IN PVOID DllBase
,
222 IN PANSI_STRING ExportName
)
225 PUSHORT OrdinalTable
;
226 PIMAGE_EXPORT_DIRECTORY ExportDirectory
;
227 LONG Low
= 0, Mid
= 0, High
, Ret
;
234 /* Get the export directory */
235 ExportDirectory
= RtlImageDirectoryEntryToData(DllBase
,
237 IMAGE_DIRECTORY_ENTRY_EXPORT
,
239 if (!ExportDirectory
) return NULL
;
241 /* Setup name tables */
242 NameTable
= (PULONG
)((ULONG_PTR
)DllBase
+
243 ExportDirectory
->AddressOfNames
);
244 OrdinalTable
= (PUSHORT
)((ULONG_PTR
)DllBase
+
245 ExportDirectory
->AddressOfNameOrdinals
);
247 /* Do a binary search */
248 High
= ExportDirectory
->NumberOfNames
- 1;
251 /* Get new middle value */
252 Mid
= (Low
+ High
) >> 1;
255 Ret
= strcmp(ExportName
->Buffer
, (PCHAR
)DllBase
+ NameTable
[Mid
]);
273 /* Check if we couldn't find it */
274 if (High
< Low
) return NULL
;
276 /* Otherwise, this is the ordinal */
277 Ordinal
= OrdinalTable
[Mid
];
279 /* Resolve the address and write it */
280 ExportTable
= (PULONG
)((ULONG_PTR
)DllBase
+
281 ExportDirectory
->AddressOfFunctions
);
282 Function
= (PVOID
)((ULONG_PTR
)DllBase
+ ExportTable
[Ordinal
]);
285 ASSERT((Function
> (PVOID
)ExportDirectory
) &&
286 (Function
< (PVOID
)((ULONG_PTR
)ExportDirectory
+ ExportSize
)));
292 MiLocateExportName(IN PVOID DllBase
,
296 PUSHORT OrdinalTable
;
297 PIMAGE_EXPORT_DIRECTORY ExportDirectory
;
298 LONG Low
= 0, Mid
= 0, High
, Ret
;
305 /* Get the export directory */
306 ExportDirectory
= RtlImageDirectoryEntryToData(DllBase
,
308 IMAGE_DIRECTORY_ENTRY_EXPORT
,
310 if (!ExportDirectory
) return NULL
;
312 /* Setup name tables */
313 NameTable
= (PULONG
)((ULONG_PTR
)DllBase
+
314 ExportDirectory
->AddressOfNames
);
315 OrdinalTable
= (PUSHORT
)((ULONG_PTR
)DllBase
+
316 ExportDirectory
->AddressOfNameOrdinals
);
318 /* Do a binary search */
319 High
= ExportDirectory
->NumberOfNames
- 1;
322 /* Get new middle value */
323 Mid
= (Low
+ High
) >> 1;
326 Ret
= strcmp(ExportName
, (PCHAR
)DllBase
+ NameTable
[Mid
]);
344 /* Check if we couldn't find it */
345 if (High
< Low
) return NULL
;
347 /* Otherwise, this is the ordinal */
348 Ordinal
= OrdinalTable
[Mid
];
350 /* Resolve the address and write it */
351 ExportTable
= (PULONG
)((ULONG_PTR
)DllBase
+
352 ExportDirectory
->AddressOfFunctions
);
353 Function
= (PVOID
)((ULONG_PTR
)DllBase
+ ExportTable
[Ordinal
]);
355 /* Check if the function is actually a forwarder */
356 if (((ULONG_PTR
)Function
> (ULONG_PTR
)ExportDirectory
) &&
357 ((ULONG_PTR
)Function
< ((ULONG_PTR
)ExportDirectory
+ ExportSize
)))
369 MmCallDllInitialize(IN PLDR_DATA_TABLE_ENTRY LdrEntry
,
370 IN PLIST_ENTRY ListHead
)
372 PMM_DLL_INITIALIZE DllInit
;
374 /* Try to see if the image exports a DllInitialize routine */
375 DllInit
= (PMM_DLL_INITIALIZE
)MiLocateExportName(LdrEntry
->DllBase
,
377 if (!DllInit
) return STATUS_SUCCESS
;
380 DPRINT1("DllInitialize not called!\n");
381 return STATUS_UNSUCCESSFUL
;
386 MiProcessLoaderEntry(IN PLDR_DATA_TABLE_ENTRY LdrEntry
,
391 /* Acquire the lock */
392 KeAcquireSpinLock(&PsLoadedModuleSpinLock
, &OldIrql
);
394 /* Insert or remove from the list */
395 Insert
? InsertTailList(&PsLoadedModuleList
, &LdrEntry
->InLoadOrderLinks
) :
396 RemoveEntryList(&LdrEntry
->InLoadOrderLinks
);
398 /* Release the lock */
399 KeReleaseSpinLock(&PsLoadedModuleSpinLock
, OldIrql
);
404 MiUpdateThunks(IN PLOADER_PARAMETER_BLOCK LoaderBlock
,
409 ULONG_PTR OldBaseTop
, Delta
;
410 PLDR_DATA_TABLE_ENTRY LdrEntry
;
411 PLIST_ENTRY NextEntry
;
413 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
;
416 /* Calculate the top and delta */
417 OldBaseTop
= (ULONG_PTR
)OldBase
+ Size
- 1;
418 Delta
= (ULONG_PTR
)NewBase
- (ULONG_PTR
)OldBase
;
420 /* Loop the loader block */
421 for (NextEntry
= LoaderBlock
->LoadOrderListHead
.Flink
;
422 NextEntry
!= &LoaderBlock
->LoadOrderListHead
;
423 NextEntry
= NextEntry
->Flink
)
425 /* Get the loader entry */
426 LdrEntry
= CONTAINING_RECORD(NextEntry
,
427 LDR_DATA_TABLE_ENTRY
,
430 /* Get the import table */
431 ImportDescriptor
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
433 IMAGE_DIRECTORY_ENTRY_IMPORT
,
435 if (!ImportDescriptor
) continue;
437 /* Make sure we have an IAT */
438 DPRINT("[Mm0]: Updating thunks in: %wZ\n", &LdrEntry
->BaseDllName
);
439 while ((ImportDescriptor
->Name
) &&
440 (ImportDescriptor
->OriginalFirstThunk
))
442 /* Get the image thunk */
443 ImageThunk
= (PVOID
)((ULONG_PTR
)LdrEntry
->DllBase
+
444 ImportDescriptor
->FirstThunk
);
447 /* Check if it's within this module */
448 if ((*ImageThunk
>= (ULONG_PTR
)OldBase
) && (*ImageThunk
<= OldBaseTop
))
451 DPRINT("[Mm0]: Updating IAT at: %p. Old Entry: %p. New Entry: %p.\n",
452 ImageThunk
, *ImageThunk
, *ImageThunk
+ Delta
);
453 *ImageThunk
+= Delta
;
456 /* Go to the next thunk */
460 /* Go to the next import */
468 MiSnapThunk(IN PVOID DllBase
,
470 IN PIMAGE_THUNK_DATA Name
,
471 IN PIMAGE_THUNK_DATA Address
,
472 IN PIMAGE_EXPORT_DIRECTORY ExportDirectory
,
474 IN BOOLEAN SnapForwarder
,
475 OUT PCHAR
*MissingApi
)
480 PUSHORT OrdinalTable
;
481 PIMAGE_IMPORT_BY_NAME NameImport
;
483 ULONG Low
= 0, Mid
= 0, High
;
486 PCHAR MissingForwarder
;
487 CHAR NameBuffer
[MAXIMUM_FILENAME_LENGTH
];
490 UNICODE_STRING ForwarderName
;
491 PLIST_ENTRY NextEntry
;
492 PLDR_DATA_TABLE_ENTRY LdrEntry
;
493 ULONG ForwardExportSize
;
494 PIMAGE_EXPORT_DIRECTORY ForwardExportDirectory
;
495 PIMAGE_IMPORT_BY_NAME ForwardName
;
497 IMAGE_THUNK_DATA ForwardThunk
;
500 /* Check if this is an ordinal */
501 IsOrdinal
= IMAGE_SNAP_BY_ORDINAL(Name
->u1
.Ordinal
);
502 if ((IsOrdinal
) && !(SnapForwarder
))
504 /* Get the ordinal number and set it as missing */
505 Ordinal
= (USHORT
)(IMAGE_ORDINAL(Name
->u1
.Ordinal
) -
506 ExportDirectory
->Base
);
507 *MissingApi
= (PCHAR
)(ULONG_PTR
)Ordinal
;
511 /* Get the VA if we don't have to snap */
512 if (!SnapForwarder
) Name
->u1
.AddressOfData
+= (ULONG_PTR
)ImageBase
;
513 NameImport
= (PIMAGE_IMPORT_BY_NAME
)Name
->u1
.AddressOfData
;
515 /* Copy the procedure name */
517 (PCHAR
)&NameImport
->Name
[0],
518 MAXIMUM_FILENAME_LENGTH
- 1);
520 /* Setup name tables */
521 DPRINT("Import name: %s\n", NameImport
->Name
);
522 NameTable
= (PULONG
)((ULONG_PTR
)DllBase
+
523 ExportDirectory
->AddressOfNames
);
524 OrdinalTable
= (PUSHORT
)((ULONG_PTR
)DllBase
+
525 ExportDirectory
->AddressOfNameOrdinals
);
527 /* Get the hint and check if it's valid */
528 Hint
= NameImport
->Hint
;
529 if ((Hint
< ExportDirectory
->NumberOfNames
) &&
530 !(strcmp((PCHAR
) NameImport
->Name
, (PCHAR
)DllBase
+ NameTable
[Hint
])))
532 /* We have a match, get the ordinal number from here */
533 Ordinal
= OrdinalTable
[Hint
];
537 /* Do a binary search */
538 High
= ExportDirectory
->NumberOfNames
- 1;
541 /* Get new middle value */
542 Mid
= (Low
+ High
) >> 1;
545 Ret
= strcmp((PCHAR
)NameImport
->Name
, (PCHAR
)DllBase
+ NameTable
[Mid
]);
563 /* Check if we couldn't find it */
564 if (High
< Low
) return STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
;
566 /* Otherwise, this is the ordinal */
567 Ordinal
= OrdinalTable
[Mid
];
571 /* Check if the ordinal is invalid */
572 if (Ordinal
>= ExportDirectory
->NumberOfFunctions
)
575 Status
= STATUS_DRIVER_ORDINAL_NOT_FOUND
;
579 /* In case the forwarder is missing */
580 MissingForwarder
= NameBuffer
;
582 /* Resolve the address and write it */
583 ExportTable
= (PULONG
)((ULONG_PTR
)DllBase
+
584 ExportDirectory
->AddressOfFunctions
);
585 Address
->u1
.Function
= (ULONG_PTR
)DllBase
+ ExportTable
[Ordinal
];
587 /* Assume success from now on */
588 Status
= STATUS_SUCCESS
;
590 /* Check if the function is actually a forwarder */
591 if ((Address
->u1
.Function
> (ULONG_PTR
)ExportDirectory
) &&
592 (Address
->u1
.Function
< ((ULONG_PTR
)ExportDirectory
+ ExportSize
)))
594 /* Now assume failure in case the forwarder doesn't exist */
595 Status
= STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
;
597 /* Build the forwarder name */
598 DllName
.Buffer
= (PCHAR
)Address
->u1
.Function
;
599 DllName
.Length
= strchr(DllName
.Buffer
, '.') -
602 DllName
.MaximumLength
= DllName
.Length
;
605 if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&ForwarderName
,
609 /* We failed, just return an error */
613 /* Loop the module list */
614 NextEntry
= PsLoadedModuleList
.Flink
;
615 while (NextEntry
!= &PsLoadedModuleList
)
617 /* Get the loader entry */
618 LdrEntry
= CONTAINING_RECORD(NextEntry
,
619 LDR_DATA_TABLE_ENTRY
,
622 /* Check if it matches */
623 if (RtlPrefixString((PSTRING
)&ForwarderName
,
624 (PSTRING
)&LdrEntry
->BaseDllName
,
627 /* Get the forwarder export directory */
628 ForwardExportDirectory
=
629 RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
631 IMAGE_DIRECTORY_ENTRY_EXPORT
,
633 if (!ForwardExportDirectory
) break;
635 /* Allocate a name entry */
636 ForwardLength
= strlen(DllName
.Buffer
+ DllName
.Length
) +
638 ForwardName
= ExAllocatePoolWithTag(PagedPool
,
639 sizeof(*ForwardName
) +
642 if (!ForwardName
) break;
645 RtlCopyMemory(&ForwardName
->Name
[0],
646 DllName
.Buffer
+ DllName
.Length
,
648 ForwardName
->Hint
= 0;
650 /* Set the new address */
651 *(PULONG
)&ForwardThunk
.u1
.AddressOfData
= (ULONG
)ForwardName
;
653 /* Snap the forwarder */
654 Status
= MiSnapThunk(LdrEntry
->DllBase
,
658 ForwardExportDirectory
,
663 /* Free the forwarder name and set the thunk */
664 ExFreePool(ForwardName
);
665 Address
->u1
= ForwardThunk
.u1
;
669 /* Go to the next entry */
670 NextEntry
= NextEntry
->Flink
;
674 RtlFreeUnicodeString(&ForwarderName
);
684 MmUnloadSystemImage(IN PVOID ImageHandle
)
686 PLDR_DATA_TABLE_ENTRY LdrEntry
= ImageHandle
;
687 PVOID BaseAddress
= LdrEntry
->DllBase
;
689 ANSI_STRING TempName
;
690 BOOLEAN HadEntry
= FALSE
;
692 /* Acquire the loader lock */
693 KeEnterCriticalRegion();
694 KeWaitForSingleObject(&MmSystemLoadLock
,
700 /* Check if this driver was loaded at boot and didn't get imports parsed */
701 if (LdrEntry
->LoadedImports
== (PVOID
)-1) goto Done
;
703 /* We should still be alive */
704 ASSERT(LdrEntry
->LoadCount
!= 0);
705 LdrEntry
->LoadCount
--;
707 /* Check if we're still loaded */
708 if (LdrEntry
->LoadCount
) goto Done
;
710 /* We should cleanup... are symbols loaded */
711 if (LdrEntry
->Flags
& LDRP_DEBUG_SYMBOLS_LOADED
)
713 /* Create the ANSI name */
714 Status
= RtlUnicodeStringToAnsiString(&TempName
,
715 &LdrEntry
->BaseDllName
,
717 if (NT_SUCCESS(Status
))
719 /* Unload the symbols */
720 DbgUnLoadImageSymbols(&TempName
, BaseAddress
, -1);
721 RtlFreeAnsiString(&TempName
);
725 /* FIXME: Free the driver */
726 //MmFreeSection(LdrEntry->DllBase);
728 /* Check if we're linked in */
729 if (LdrEntry
->InLoadOrderLinks
.Flink
)
732 MiProcessLoaderEntry(LdrEntry
, FALSE
);
736 /* Dereference and clear the imports */
737 MiDereferenceImports(LdrEntry
->LoadedImports
);
738 MiClearImports(LdrEntry
);
740 /* Check if the entry needs to go away */
743 /* Check if it had a name */
744 if (LdrEntry
->FullDllName
.Buffer
)
747 ExFreePool(LdrEntry
->FullDllName
.Buffer
);
750 /* Check if we had a section */
751 if (LdrEntry
->SectionPointer
)
754 ObDereferenceObject(LdrEntry
->SectionPointer
);
758 ExFreePool(LdrEntry
);
761 /* Release the system lock and return */
763 KeReleaseMutant(&MmSystemLoadLock
, 1, FALSE
, FALSE
);
764 KeLeaveCriticalRegion();
765 return STATUS_SUCCESS
;
770 MiResolveImageReferences(IN PVOID ImageBase
,
771 IN PUNICODE_STRING ImageFileDirectory
,
772 IN PUNICODE_STRING NamePrefix OPTIONAL
,
773 OUT PCHAR
*MissingApi
,
774 OUT PWCHAR
*MissingDriver
,
775 OUT PLOAD_IMPORTS
*LoadImports
)
777 PCHAR MissingApiBuffer
= *MissingApi
, ImportName
;
778 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
, CurrentImport
;
779 ULONG ImportSize
, ImportCount
= 0, LoadedImportsSize
, ExportSize
;
780 PLOAD_IMPORTS LoadedImports
, NewImports
;
781 ULONG GdiLink
, NormalLink
, i
;
782 BOOLEAN ReferenceNeeded
, Loaded
;
783 ANSI_STRING TempString
;
784 UNICODE_STRING NameString
, DllName
;
785 PLDR_DATA_TABLE_ENTRY LdrEntry
= NULL
, DllEntry
, ImportEntry
= NULL
;
786 PVOID ImportBase
, DllBase
;
787 PLIST_ENTRY NextEntry
;
788 PIMAGE_EXPORT_DIRECTORY ExportDirectory
;
790 PIMAGE_THUNK_DATA OrigThunk
, FirstThunk
;
792 DPRINT("%s - ImageBase: %p. ImageFileDirectory: %wZ\n",
793 __FUNCTION__
, ImageBase
, ImageFileDirectory
);
795 /* Assume no imports */
796 *LoadImports
= (PVOID
)-2;
798 /* Get the import descriptor */
799 ImportDescriptor
= RtlImageDirectoryEntryToData(ImageBase
,
801 IMAGE_DIRECTORY_ENTRY_IMPORT
,
803 if (!ImportDescriptor
) return STATUS_SUCCESS
;
805 /* Loop all imports to count them */
806 for (CurrentImport
= ImportDescriptor
;
807 (CurrentImport
->Name
) && (CurrentImport
->OriginalFirstThunk
);
814 /* Make sure we have non-zero imports */
817 /* Calculate and allocate the list we'll need */
818 LoadedImportsSize
= ImportCount
* sizeof(PVOID
) + sizeof(SIZE_T
);
819 LoadedImports
= ExAllocatePoolWithTag(PagedPool
,
825 RtlZeroMemory(LoadedImports
, LoadedImportsSize
);
831 LoadedImports
= NULL
;
834 /* Reset the import count and loop descriptors again */
835 ImportCount
= GdiLink
= NormalLink
= 0;
836 while ((ImportDescriptor
->Name
) && (ImportDescriptor
->OriginalFirstThunk
))
839 ImportName
= (PCHAR
)((ULONG_PTR
)ImageBase
+ ImportDescriptor
->Name
);
841 /* Check if this is a GDI driver */
843 !(_strnicmp(ImportName
, "win32k", sizeof("win32k") - 1));
845 /* We can also allow dxapi */
846 NormalLink
= NormalLink
|
847 ((_strnicmp(ImportName
, "win32k", sizeof("win32k") - 1)) &&
848 (_strnicmp(ImportName
, "dxapi", sizeof("dxapi") - 1)));
850 /* Check if this is a valid GDI driver */
851 if ((GdiLink
) && (NormalLink
))
853 /* It's not, it's importing stuff it shouldn't be! */
854 MiDereferenceImports(LoadedImports
);
855 if (LoadedImports
) ExFreePool(LoadedImports
);
856 return STATUS_PROCEDURE_NOT_FOUND
;
859 /* Check if this is a "core" import, which doesn't get referenced */
860 if (!(_strnicmp(ImportName
, "ntoskrnl", sizeof("ntoskrnl") - 1)) ||
861 !(_strnicmp(ImportName
, "win32k", sizeof("win32k") - 1)) ||
862 !(_strnicmp(ImportName
, "hal", sizeof("hal") - 1)))
864 /* Don't reference this */
865 ReferenceNeeded
= FALSE
;
869 /* Reference these modules */
870 ReferenceNeeded
= TRUE
;
873 /* Now setup a unicode string for the import */
874 RtlInitAnsiString(&TempString
, ImportName
);
875 Status
= RtlAnsiStringToUnicodeString(&NameString
, &TempString
, TRUE
);
876 if (!NT_SUCCESS(Status
))
879 MiDereferenceImports(LoadedImports
);
880 if (LoadedImports
) ExFreePool(LoadedImports
);
884 /* We don't support name prefixes yet */
885 if (NamePrefix
) DPRINT1("Name Prefix not yet supported!\n");
887 /* Remember that we haven't loaded the import at this point */
892 /* Loop the driver list */
893 NextEntry
= PsLoadedModuleList
.Flink
;
894 while (NextEntry
!= &PsLoadedModuleList
)
896 /* Get the loader entry and compare the name */
897 LdrEntry
= CONTAINING_RECORD(NextEntry
,
898 LDR_DATA_TABLE_ENTRY
,
900 if (RtlEqualUnicodeString(&NameString
,
901 &LdrEntry
->BaseDllName
,
904 /* Get the base address */
905 ImportBase
= LdrEntry
->DllBase
;
907 /* Check if we haven't loaded yet, and we need references */
908 if (!(Loaded
) && (ReferenceNeeded
))
910 /* Make sure we're not already loading */
911 if (!(LdrEntry
->Flags
& LDRP_LOAD_IN_PROGRESS
))
913 /* Increase the load count */
914 LdrEntry
->LoadCount
++;
918 /* Done, break out */
922 /* Go to the next entry */
923 NextEntry
= NextEntry
->Flink
;
926 /* Check if we haven't loaded the import yet */
929 /* Setup the import DLL name */
930 DllName
.MaximumLength
= NameString
.Length
+
931 ImageFileDirectory
->Length
+
932 sizeof(UNICODE_NULL
);
933 DllName
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
934 DllName
.MaximumLength
,
938 /* Setup the base length and copy it */
939 DllName
.Length
= ImageFileDirectory
->Length
;
940 RtlCopyMemory(DllName
.Buffer
,
941 ImageFileDirectory
->Buffer
,
942 ImageFileDirectory
->Length
);
944 /* Now add the import name and null-terminate it */
945 RtlAppendStringToString((PSTRING
)&DllName
,
946 (PSTRING
)&NameString
);
947 DllName
.Buffer
[(DllName
.MaximumLength
- 1) / 2] = UNICODE_NULL
;
950 Status
= MmLoadSystemImage(&DllName
,
956 if (NT_SUCCESS(Status
))
958 /* We can free the DLL Name */
959 ExFreePool(DllName
.Buffer
);
963 /* Fill out the information for the error */
964 *MissingDriver
= DllName
.Buffer
;
965 *(PULONG
)MissingDriver
|= 1;
971 /* We're out of resources */
972 Status
= STATUS_INSUFFICIENT_RESOURCES
;
975 /* Check if we're OK until now */
976 if (NT_SUCCESS(Status
))
978 /* We're now loaded */
982 ASSERT(DllBase
= DllEntry
->DllBase
);
984 /* Call the initialization routines */
985 Status
= MmCallDllInitialize(DllEntry
, &PsLoadedModuleList
);
986 if (!NT_SUCCESS(Status
))
988 /* We failed, unload the image */
989 MmUnloadSystemImage(DllEntry
);
995 /* Check if we failed by here */
996 if (!NT_SUCCESS(Status
))
998 /* Cleanup and return */
999 RtlFreeUnicodeString(&NameString
);
1000 MiDereferenceImports(LoadedImports
);
1001 if (LoadedImports
) ExFreePool(LoadedImports
);
1005 /* Loop again to make sure that everything is OK */
1009 /* Check if we're support to reference this import */
1010 if ((ReferenceNeeded
) && (LoadedImports
))
1012 /* Make sure we're not already loading */
1013 if (!(LdrEntry
->Flags
& LDRP_LOAD_IN_PROGRESS
))
1016 LoadedImports
->Entry
[LoadedImports
->Count
] = LdrEntry
;
1017 LoadedImports
->Count
++;
1021 /* Free the import name */
1022 RtlFreeUnicodeString(&NameString
);
1024 /* Set the missing driver name and get the export directory */
1025 *MissingDriver
= LdrEntry
->BaseDllName
.Buffer
;
1026 ExportDirectory
= RtlImageDirectoryEntryToData(ImportBase
,
1028 IMAGE_DIRECTORY_ENTRY_EXPORT
,
1030 if (!ExportDirectory
)
1032 /* Cleanup and return */
1033 MiDereferenceImports(LoadedImports
);
1034 if (LoadedImports
) ExFreePool(LoadedImports
);
1035 return STATUS_DRIVER_ENTRYPOINT_NOT_FOUND
;
1038 /* Make sure we have an IAT */
1039 if (ImportDescriptor
->OriginalFirstThunk
)
1041 /* Get the first thunks */
1042 OrigThunk
= (PVOID
)((ULONG_PTR
)ImageBase
+
1043 ImportDescriptor
->OriginalFirstThunk
);
1044 FirstThunk
= (PVOID
)((ULONG_PTR
)ImageBase
+
1045 ImportDescriptor
->FirstThunk
);
1048 while (OrigThunk
->u1
.AddressOfData
)
1051 Status
= MiSnapThunk(ImportBase
,
1059 if (!NT_SUCCESS(Status
))
1061 /* Cleanup and return */
1062 MiDereferenceImports(LoadedImports
);
1063 if (LoadedImports
) ExFreePool(LoadedImports
);
1067 /* Reset the buffer */
1068 *MissingApi
= MissingApiBuffer
;
1072 /* Go to the next import */
1076 /* Check if we have an import list */
1079 /* Reset the count again, and loop entries*/
1081 for (i
= 0; i
< LoadedImports
->Count
; i
++)
1083 if (LoadedImports
->Entry
[i
])
1085 /* Got an entry, OR it with 1 in case it's the single entry */
1086 ImportEntry
= (PVOID
)((ULONG_PTR
)LoadedImports
->Entry
[i
] | 1);
1091 /* Check if we had no imports */
1094 /* Free the list and set it to no imports */
1095 ExFreePool(LoadedImports
);
1096 LoadedImports
= (PVOID
)-2;
1098 else if (ImportCount
== 1)
1100 /* Just one entry, we can free the table and only use our entry */
1101 ExFreePool(LoadedImports
);
1102 LoadedImports
= (PLOAD_IMPORTS
)ImportEntry
;
1104 else if (ImportCount
!= LoadedImports
->Count
)
1106 /* Allocate a new list */
1107 LoadedImportsSize
= ImportCount
* sizeof(PVOID
) + sizeof(SIZE_T
);
1108 NewImports
= ExAllocatePoolWithTag(PagedPool
,
1114 NewImports
->Count
= 0;
1116 /* Loop all the imports */
1117 for (i
= 0; i
< LoadedImports
->Count
; i
++)
1119 /* Make sure it's valid */
1120 if (LoadedImports
->Entry
[i
])
1123 NewImports
->Entry
[NewImports
->Count
] = LoadedImports
->Entry
[i
];
1124 NewImports
->Count
++;
1128 /* Free the old copy */
1129 ExFreePool(LoadedImports
);
1130 LoadedImports
= NewImports
;
1134 /* Return the list */
1135 *LoadImports
= LoadedImports
;
1138 /* Return success */
1139 return STATUS_SUCCESS
;
1144 MiReloadBootLoadedDrivers(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
1146 PLIST_ENTRY NextEntry
;
1148 PIMAGE_NT_HEADERS NtHeader
;
1149 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1150 PIMAGE_FILE_HEADER FileHeader
;
1151 BOOLEAN ValidRelocs
;
1152 PIMAGE_DATA_DIRECTORY DataDirectory
;
1153 PVOID DllBase
, NewImageAddress
;
1156 /* Loop driver list */
1157 for (NextEntry
= LoaderBlock
->LoadOrderListHead
.Flink
;
1158 NextEntry
!= &LoaderBlock
->LoadOrderListHead
;
1159 NextEntry
= NextEntry
->Flink
)
1161 /* Get the loader entry and NT header */
1162 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1163 LDR_DATA_TABLE_ENTRY
,
1165 NtHeader
= RtlImageNtHeader(LdrEntry
->DllBase
);
1168 DPRINT("[Mm0]: Driver at: %p ending at: %p for module: %wZ\n",
1170 (ULONG_PTR
)LdrEntry
->DllBase
+ LdrEntry
->SizeOfImage
,
1171 &LdrEntry
->FullDllName
);
1173 /* Skip kernel and HAL */
1174 /* ROS HACK: Skip BOOTVID/KDCOM too */
1176 if (i
<= 4) continue;
1178 /* Skip non-drivers */
1179 if (!NtHeader
) continue;
1181 /* Get the file header and make sure we can relocate */
1182 FileHeader
= &NtHeader
->FileHeader
;
1183 if (FileHeader
->Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
) continue;
1184 if (NtHeader
->OptionalHeader
.NumberOfRvaAndSizes
<
1185 IMAGE_DIRECTORY_ENTRY_BASERELOC
) continue;
1187 /* Everything made sense until now, check the relocation section too */
1188 DataDirectory
= &NtHeader
->OptionalHeader
.
1189 DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1190 if (!DataDirectory
->VirtualAddress
)
1192 /* We don't really have relocations */
1193 ValidRelocs
= FALSE
;
1197 /* Make sure the size is valid */
1198 if ((DataDirectory
->VirtualAddress
+ DataDirectory
->Size
) >
1199 LdrEntry
->SizeOfImage
)
1201 /* They're not, skip */
1205 /* We have relocations */
1209 /* Remember the original address */
1210 DllBase
= LdrEntry
->DllBase
;
1212 /* Allocate a virtual section for the module */
1213 NewImageAddress
= MmAllocateSection(LdrEntry
->SizeOfImage
, NULL
);
1214 if (!NewImageAddress
)
1216 /* Shouldn't happen */
1217 DPRINT1("[Mm0]: Couldn't allocate driver section!\n");
1222 DPRINT("[Mm0]: Copying from: %p to: %p\n", DllBase
, NewImageAddress
);
1223 ASSERT(ExpInitializationPhase
== 0);
1225 /* Now copy the entire driver over */
1226 RtlCopyMemory(NewImageAddress
, DllBase
, LdrEntry
->SizeOfImage
);
1229 ASSERT(*(PULONG
)NewImageAddress
== *(PULONG
)DllBase
);
1231 /* Set the image base to the address where the loader put it */
1232 NtHeader
->OptionalHeader
.ImageBase
= (ULONG_PTR
)DllBase
;
1233 NtHeader
= RtlImageNtHeader(NewImageAddress
);
1234 NtHeader
->OptionalHeader
.ImageBase
= (ULONG_PTR
)DllBase
;
1236 /* Check if we had relocations */
1239 /* Relocate the image */
1240 Status
= LdrRelocateImageWithBias(NewImageAddress
,
1244 STATUS_CONFLICTING_ADDRESSES
,
1245 STATUS_INVALID_IMAGE_FORMAT
);
1246 if (!NT_SUCCESS(Status
))
1248 /* This shouldn't happen */
1249 DPRINT1("Relocations failed!\n");
1254 /* Update the loader entry */
1255 LdrEntry
->DllBase
= NewImageAddress
;
1257 /* Update the thunks */
1258 DPRINT("[Mm0]: Updating thunks to: %wZ\n", &LdrEntry
->BaseDllName
);
1259 MiUpdateThunks(LoaderBlock
,
1262 LdrEntry
->SizeOfImage
);
1264 /* Update the loader entry */
1265 LdrEntry
->Flags
|= 0x01000000;
1266 LdrEntry
->EntryPoint
= (PVOID
)((ULONG_PTR
)NewImageAddress
+
1267 NtHeader
->OptionalHeader
.AddressOfEntryPoint
);
1268 LdrEntry
->SizeOfImage
= LdrEntry
->SizeOfImage
;
1270 /* Free the old copy */
1271 MiFreeBootDriverMemory(DllBase
, LdrEntry
->SizeOfImage
);
1277 MiInitializeLoadedModuleList(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
1279 PLDR_DATA_TABLE_ENTRY LdrEntry
, NewEntry
;
1280 PLIST_ENTRY ListHead
, NextEntry
;
1283 /* Setup the loaded module list and lock */
1284 KeInitializeSpinLock(&PsLoadedModuleSpinLock
);
1285 InitializeListHead(&PsLoadedModuleList
);
1287 /* Get loop variables and the kernel entry */
1288 ListHead
= &LoaderBlock
->LoadOrderListHead
;
1289 NextEntry
= ListHead
->Flink
;
1290 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1291 LDR_DATA_TABLE_ENTRY
,
1293 PsNtosImageBase
= (ULONG
)LdrEntry
->DllBase
;
1295 /* Loop the loader block */
1296 while (NextEntry
!= ListHead
)
1298 /* Get the loader entry */
1299 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1300 LDR_DATA_TABLE_ENTRY
,
1303 /* FIXME: ROS HACK. Make sure this is a driver */
1304 if (!RtlImageNtHeader(LdrEntry
->DllBase
))
1306 /* Skip this entry */
1307 NextEntry
= NextEntry
->Flink
;
1311 /* Calculate the size we'll need and allocate a copy */
1312 EntrySize
= sizeof(LDR_DATA_TABLE_ENTRY
) +
1313 LdrEntry
->BaseDllName
.MaximumLength
+
1314 sizeof(UNICODE_NULL
);
1315 NewEntry
= ExAllocatePoolWithTag(NonPagedPool
, EntrySize
, TAG_LDR_WSTR
);
1316 if (!NewEntry
) return FALSE
;
1318 /* Copy the entry over */
1319 *NewEntry
= *LdrEntry
;
1321 /* Allocate the name */
1322 NewEntry
->FullDllName
.Buffer
=
1323 ExAllocatePoolWithTag(PagedPool
,
1324 LdrEntry
->FullDllName
.MaximumLength
+
1325 sizeof(UNICODE_NULL
),
1327 if (!NewEntry
->FullDllName
.Buffer
) return FALSE
;
1329 /* Set the base name */
1330 NewEntry
->BaseDllName
.Buffer
= (PVOID
)(NewEntry
+ 1);
1332 /* Copy the full and base name */
1333 RtlCopyMemory(NewEntry
->FullDllName
.Buffer
,
1334 LdrEntry
->FullDllName
.Buffer
,
1335 LdrEntry
->FullDllName
.MaximumLength
);
1336 RtlCopyMemory(NewEntry
->BaseDllName
.Buffer
,
1337 LdrEntry
->BaseDllName
.Buffer
,
1338 LdrEntry
->BaseDllName
.MaximumLength
);
1340 /* Null-terminate the base name */
1341 NewEntry
->BaseDllName
.Buffer
[NewEntry
->BaseDllName
.Length
/
1342 sizeof(WCHAR
)] = UNICODE_NULL
;
1344 /* Insert the entry into the list */
1345 InsertTailList(&PsLoadedModuleList
, &NewEntry
->InLoadOrderLinks
);
1346 NextEntry
= NextEntry
->Flink
;
1349 /* Build the import lists for the boot drivers */
1350 //MiBuildImportsForBootDrivers();
1358 MmVerifyImageIsOkForMpUse(IN PVOID BaseAddress
)
1360 PIMAGE_NT_HEADERS NtHeader
;
1363 /* Get NT Headers */
1364 NtHeader
= RtlImageNtHeader(BaseAddress
);
1367 /* Check if this image is only safe for UP while we have 2+ CPUs */
1368 if ((KeNumberProcessors
> 1) &&
1369 (NtHeader
->FileHeader
.Characteristics
& IMAGE_FILE_UP_SYSTEM_ONLY
))
1376 /* Otherwise, it's safe */
1382 MmCheckSystemImage(IN HANDLE ImageHandle
,
1383 IN BOOLEAN PurgeSection
)
1386 HANDLE SectionHandle
;
1387 PVOID ViewBase
= NULL
;
1388 SIZE_T ViewSize
= 0;
1389 IO_STATUS_BLOCK IoStatusBlock
;
1390 FILE_STANDARD_INFORMATION FileStandardInfo
;
1391 KAPC_STATE ApcState
;
1394 /* Create a section for the DLL */
1395 Status
= ZwCreateSection(&SectionHandle
,
1396 SECTION_MAP_EXECUTE
,
1402 if (!NT_SUCCESS(Status
)) return Status
;
1404 /* Make sure we're in the system process */
1405 KeStackAttachProcess(&PsInitialSystemProcess
->Pcb
, &ApcState
);
1408 Status
= ZwMapViewOfSection(SectionHandle
,
1418 if (!NT_SUCCESS(Status
))
1420 /* We failed, close the handle and return */
1421 KeUnstackDetachProcess(&ApcState
);
1422 ZwClose(SectionHandle
);
1426 /* Now query image information */
1427 Status
= ZwQueryInformationFile(ImageHandle
,
1430 sizeof(FileStandardInfo
),
1431 FileStandardInformation
);
1432 if ( NT_SUCCESS(Status
) )
1434 /* First, verify the checksum */
1435 if (!LdrVerifyMappedImageMatchesChecksum(ViewBase
,
1441 /* Set checksum failure */
1442 Status
= STATUS_IMAGE_CHECKSUM_MISMATCH
;
1445 /* Check that it's a valid SMP image if we have more then one CPU */
1446 if (!MmVerifyImageIsOkForMpUse(ViewBase
))
1448 /* Otherwise it's not the right image */
1449 Status
= STATUS_IMAGE_MP_UP_MISMATCH
;
1453 /* Unmap the section, close the handle, and return status */
1454 ZwUnmapViewOfSection(NtCurrentProcess(), ViewBase
);
1455 KeUnstackDetachProcess(&ApcState
);
1456 ZwClose(SectionHandle
);
1462 MmLoadSystemImage(IN PUNICODE_STRING FileName
,
1463 IN PUNICODE_STRING NamePrefix OPTIONAL
,
1464 IN PUNICODE_STRING LoadedName OPTIONAL
,
1466 OUT PVOID
*ModuleObject
,
1467 OUT PVOID
*ImageBaseAddress
)
1469 PVOID ModuleLoadBase
= NULL
;
1471 HANDLE FileHandle
= NULL
;
1472 OBJECT_ATTRIBUTES ObjectAttributes
;
1473 IO_STATUS_BLOCK IoStatusBlock
;
1474 PIMAGE_NT_HEADERS NtHeader
;
1475 UNICODE_STRING BaseName
, BaseDirectory
, PrefixName
, UnicodeTemp
;
1476 PLDR_DATA_TABLE_ENTRY LdrEntry
= NULL
;
1477 ULONG EntrySize
, DriverSize
;
1478 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
1479 PCHAR MissingApiName
, Buffer
;
1480 PWCHAR MissingDriverName
;
1481 HANDLE SectionHandle
;
1482 ACCESS_MASK DesiredAccess
;
1483 PVOID Section
= NULL
;
1484 BOOLEAN LockOwned
= FALSE
;
1485 PLIST_ENTRY NextEntry
;
1486 IMAGE_INFO ImageInfo
;
1487 ANSI_STRING AnsiTemp
;
1490 /* Detect session-load */
1494 ASSERT(NamePrefix
== NULL
);
1495 ASSERT(LoadedName
== NULL
);
1497 /* Make sure the process is in session too */
1498 if (!PsGetCurrentProcess()->ProcessInSession
) return STATUS_NO_MEMORY
;
1501 if (ModuleObject
) *ModuleObject
= NULL
;
1502 if (ImageBaseAddress
) *ImageBaseAddress
= NULL
;
1504 /* Allocate a buffer we'll use for names */
1505 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
1506 if (!Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1508 /* Check for a separator */
1509 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
1514 /* Loop the path until we get to the base name */
1515 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
1516 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
1518 /* Get the length */
1519 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
1520 BaseLength
*= sizeof(WCHAR
);
1522 /* Setup the string */
1523 BaseName
.Length
= (USHORT
)BaseLength
;
1524 BaseName
.Buffer
= p
;
1528 /* Otherwise, we already have a base name */
1529 BaseName
.Length
= FileName
->Length
;
1530 BaseName
.Buffer
= FileName
->Buffer
;
1533 /* Setup the maximum length */
1534 BaseName
.MaximumLength
= BaseName
.Length
;
1536 /* Now compute the base directory */
1537 BaseDirectory
= *FileName
;
1538 BaseDirectory
.Length
-= BaseName
.Length
;
1539 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
1541 /* And the prefix, which for now is just the name itself */
1542 PrefixName
= *FileName
;
1544 /* Check if we have a prefix */
1545 if (NamePrefix
) DPRINT1("Prefixed images are not yet supported!\n");
1547 /* Check if we already have a name, use it instead */
1548 if (LoadedName
) BaseName
= *LoadedName
;
1550 /* Acquire the load lock */
1552 ASSERT(LockOwned
== FALSE
);
1554 KeEnterCriticalRegion();
1555 KeWaitForSingleObject(&MmSystemLoadLock
,
1561 /* Scan the module list */
1562 NextEntry
= PsLoadedModuleList
.Flink
;
1563 while (NextEntry
!= &PsLoadedModuleList
)
1565 /* Get the entry and compare the names */
1566 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1567 LDR_DATA_TABLE_ENTRY
,
1569 if (RtlEqualUnicodeString(&PrefixName
, &LdrEntry
->FullDllName
, TRUE
))
1571 /* Found it, break out */
1576 NextEntry
= NextEntry
->Flink
;
1579 /* Check if we found the image */
1580 if (NextEntry
!= &PsLoadedModuleList
)
1582 /* Check if we had already mapped a section */
1585 /* Dereference and clear */
1586 ObDereferenceObject(Section
);
1590 /* Check if this was supposed to be a session load */
1593 /* It wasn't, so just return the data */
1594 if (ModuleObject
) *ModuleObject
= LdrEntry
;
1595 if (ImageBaseAddress
) *ImageBaseAddress
= LdrEntry
->DllBase
;
1596 Status
= STATUS_IMAGE_ALREADY_LOADED
;
1600 /* We don't support session loading yet */
1601 DPRINT1("Unsupported Session-Load!\n");
1610 /* It wasn't loaded, and we didn't have a previous attempt */
1611 KeReleaseMutant(&MmSystemLoadLock
, 1, FALSE
, FALSE
);
1612 KeLeaveCriticalRegion();
1615 /* Check if KD is enabled */
1616 if ((KdDebuggerEnabled
) && !(KdDebuggerNotPresent
))
1618 /* FIXME: Attempt to get image from KD */
1621 /* We don't have a valid entry */
1624 /* Setup image attributes */
1625 InitializeObjectAttributes(&ObjectAttributes
,
1627 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1631 /* Open the image */
1632 Status
= ZwOpenFile(&FileHandle
,
1636 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
1638 if (!NT_SUCCESS(Status
)) goto Quickie
;
1641 Status
= MmCheckSystemImage(FileHandle
, FALSE
);
1642 if ((Status
== STATUS_IMAGE_CHECKSUM_MISMATCH
) ||
1643 (Status
== STATUS_IMAGE_MP_UP_MISMATCH
) ||
1644 (Status
== STATUS_INVALID_IMAGE_FORMAT
))
1650 /* Check if this is a session-load */
1653 /* Then we only need read and execute */
1654 DesiredAccess
= SECTION_MAP_READ
| SECTION_MAP_EXECUTE
;
1658 /* Otherwise, we can allow write access */
1659 DesiredAccess
= SECTION_ALL_ACCESS
;
1662 /* Initialize the attributes for the section */
1663 InitializeObjectAttributes(&ObjectAttributes
,
1665 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1669 /* Create the section */
1670 Status
= ZwCreateSection(&SectionHandle
,
1677 if (!NT_SUCCESS(Status
)) goto Quickie
;
1679 /* Now get the section pointer */
1680 Status
= ObReferenceObjectByHandle(SectionHandle
,
1681 SECTION_MAP_EXECUTE
,
1682 MmSectionObjectType
,
1686 ZwClose(SectionHandle
);
1687 if (!NT_SUCCESS(Status
)) goto Quickie
;
1689 /* Check if this was supposed to be a session-load */
1692 /* We don't support session loading yet */
1693 DPRINT1("Unsupported Session-Load!\n");
1697 /* Check the loader list again, we should end up in the path below */
1702 /* We don't have a valid entry */
1706 /* Load the image */
1707 Status
= MiLoadImageSection(&Section
,
1712 ASSERT(Status
!= STATUS_ALREADY_COMMITTED
);
1714 /* Get the size of the driver */
1715 DriverSize
= ((PROS_SECTION_OBJECT
)Section
)->ImageSection
->ImageSize
;
1717 /* Make sure we're not being loaded into session space */
1720 /* Check for success */
1721 if (NT_SUCCESS(Status
))
1723 /* FIXME: Support large pages for drivers */
1726 /* Dereference the section */
1727 ObDereferenceObject(Section
);
1731 /* Get the NT Header */
1732 NtHeader
= RtlImageNtHeader(ModuleLoadBase
);
1734 /* Relocate the driver */
1735 Status
= LdrRelocateImageWithBias(ModuleLoadBase
,
1739 STATUS_CONFLICTING_ADDRESSES
,
1740 STATUS_INVALID_IMAGE_FORMAT
);
1741 if (!NT_SUCCESS(Status
)) goto Quickie
;
1743 /* Calculate the size we'll need for the entry and allocate it */
1744 EntrySize
= sizeof(LDR_DATA_TABLE_ENTRY
) +
1746 sizeof(UNICODE_NULL
);
1748 /* Allocate the entry */
1749 LdrEntry
= ExAllocatePoolWithTag(NonPagedPool
, EntrySize
, TAG_MODULE_OBJECT
);
1753 Status
= STATUS_INSUFFICIENT_RESOURCES
;
1757 /* Setup the entry */
1758 LdrEntry
->Flags
= LDRP_LOAD_IN_PROGRESS
;
1759 LdrEntry
->LoadCount
= 1;
1760 LdrEntry
->LoadedImports
= LoadedImports
;
1761 LdrEntry
->PatchInformation
= NULL
;
1763 /* Check the version */
1764 if ((NtHeader
->OptionalHeader
.MajorOperatingSystemVersion
>= 5) &&
1765 (NtHeader
->OptionalHeader
.MajorImageVersion
>= 5))
1767 /* Mark this image as a native image */
1768 LdrEntry
->Flags
|= 0x80000000;
1771 /* Setup the rest of the entry */
1772 LdrEntry
->DllBase
= ModuleLoadBase
;
1773 LdrEntry
->EntryPoint
= (PVOID
)((ULONG_PTR
)ModuleLoadBase
+
1774 NtHeader
->OptionalHeader
.AddressOfEntryPoint
);
1775 LdrEntry
->SizeOfImage
= DriverSize
;
1776 LdrEntry
->CheckSum
= NtHeader
->OptionalHeader
.CheckSum
;
1777 LdrEntry
->SectionPointer
= Section
;
1779 /* Now write the DLL name */
1780 LdrEntry
->BaseDllName
.Buffer
= (PVOID
)(LdrEntry
+ 1);
1781 LdrEntry
->BaseDllName
.Length
= BaseName
.Length
;
1782 LdrEntry
->BaseDllName
.MaximumLength
= BaseName
.Length
;
1784 /* Copy and null-terminate it */
1785 RtlCopyMemory(LdrEntry
->BaseDllName
.Buffer
,
1788 LdrEntry
->BaseDllName
.Buffer
[BaseName
.Length
/ 2] = UNICODE_NULL
;
1790 /* Now allocate the full name */
1791 LdrEntry
->FullDllName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1793 sizeof(UNICODE_NULL
),
1795 if (!LdrEntry
->FullDllName
.Buffer
)
1797 /* Don't fail, just set it to zero */
1798 LdrEntry
->FullDllName
.Length
= 0;
1799 LdrEntry
->FullDllName
.MaximumLength
= 0;
1804 LdrEntry
->FullDllName
.Length
= PrefixName
.Length
;
1805 LdrEntry
->FullDllName
.MaximumLength
= PrefixName
.Length
;
1807 /* Copy and null-terminate */
1808 RtlCopyMemory(LdrEntry
->FullDllName
.Buffer
,
1811 LdrEntry
->FullDllName
.Buffer
[PrefixName
.Length
/ 2] = UNICODE_NULL
;
1815 MiProcessLoaderEntry(LdrEntry
, TRUE
);
1817 /* Resolve imports */
1818 MissingApiName
= Buffer
;
1819 Status
= MiResolveImageReferences(ModuleLoadBase
,
1825 if (!NT_SUCCESS(Status
))
1828 MiProcessLoaderEntry(LdrEntry
, FALSE
);
1830 /* Check if we need to free the name */
1831 if (LdrEntry
->FullDllName
.Buffer
)
1834 ExFreePool(LdrEntry
->FullDllName
.Buffer
);
1837 /* Free the entry itself */
1838 ExFreePool(LdrEntry
);
1843 /* Update the loader entry */
1844 LdrEntry
->Flags
|= (LDRP_SYSTEM_MAPPED
|
1845 LDRP_ENTRY_PROCESSED
|
1847 LdrEntry
->Flags
&= ~LDRP_LOAD_IN_PROGRESS
;
1848 LdrEntry
->LoadedImports
= LoadedImports
;
1850 /* FIXME: Apply driver verifier */
1852 /* FIXME: Write-protect the system image */
1854 /* Check if notifications are enabled */
1855 if (PsImageNotifyEnabled
)
1857 /* Fill out the notification data */
1858 ImageInfo
.Properties
= 0;
1859 ImageInfo
.ImageAddressingMode
= IMAGE_ADDRESSING_MODE_32BIT
;
1860 ImageInfo
.SystemModeImage
= TRUE
;
1861 ImageInfo
.ImageSize
= LdrEntry
->SizeOfImage
;
1862 ImageInfo
.ImageBase
= LdrEntry
->DllBase
;
1863 ImageInfo
.ImageSectionNumber
= ImageInfo
.ImageSelector
= 0;
1865 /* Send the notification */
1866 PspRunLoadImageNotifyRoutines(FileName
, NULL
, &ImageInfo
);
1869 /* Check if there's symbols */
1871 /* If KDBG is defined, then we always have symbols */
1874 if (MiCacheImageSymbols(LdrEntry
->DllBase
))
1877 /* Check if the system root is present */
1878 if ((PrefixName
.Length
> (11 * sizeof(WCHAR
))) &&
1879 !(_wcsnicmp(PrefixName
.Buffer
, L
"\\SystemRoot", 11)))
1881 /* Add the system root */
1882 UnicodeTemp
= PrefixName
;
1883 UnicodeTemp
.Buffer
+= 11;
1884 UnicodeTemp
.Length
-= (11 * sizeof(WCHAR
));
1887 &SharedUserData
->NtSystemRoot
[2],
1892 /* Build the name */
1893 sprintf_nt(Buffer
, "%wZ", &BaseName
);
1896 /* Setup the ansi string */
1897 RtlInitString(&AnsiTemp
, Buffer
);
1899 /* Notify the debugger */
1900 DbgLoadImageSymbols(&AnsiTemp
, LdrEntry
->DllBase
, -1);
1901 LdrEntry
->Flags
|= LDRP_DEBUG_SYMBOLS_LOADED
;
1904 /* FIXME: Page the driver */
1905 ASSERT(Section
== NULL
);
1907 /* Return pointers */
1908 if (ModuleObject
) *ModuleObject
= LdrEntry
;
1909 if (ImageBaseAddress
) *ImageBaseAddress
= LdrEntry
->DllBase
;
1912 /* If we have a file handle, close it */
1913 if (FileHandle
) ZwClose(FileHandle
);
1915 /* Check if we have the lock acquired */
1918 /* Release the lock */
1919 KeReleaseMutant(&MmSystemLoadLock
, 1, FALSE
, FALSE
);
1920 KeLeaveCriticalRegion();
1924 /* Check if we had a prefix */
1925 if (NamePrefix
) ExFreePool(PrefixName
.Buffer
);
1927 /* Free the name buffer and return status */
1937 MmGetSystemRoutineAddress(IN PUNICODE_STRING SystemRoutineName
)
1939 PVOID ProcAddress
= NULL
;
1940 ANSI_STRING AnsiRoutineName
;
1942 PLIST_ENTRY NextEntry
;
1943 extern LIST_ENTRY PsLoadedModuleList
;
1944 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1945 BOOLEAN Found
= FALSE
;
1946 UNICODE_STRING KernelName
= RTL_CONSTANT_STRING(L
"ntoskrnl.exe");
1947 UNICODE_STRING HalName
= RTL_CONSTANT_STRING(L
"hal.dll");
1950 /* Convert routine to ansi name */
1951 Status
= RtlUnicodeStringToAnsiString(&AnsiRoutineName
,
1954 if (!NT_SUCCESS(Status
)) return NULL
;
1957 KeEnterCriticalRegion();
1959 /* Loop the loaded module list */
1960 NextEntry
= PsLoadedModuleList
.Flink
;
1961 while (NextEntry
!= &PsLoadedModuleList
)
1964 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1965 LDR_DATA_TABLE_ENTRY
,
1968 /* Check if it's the kernel or HAL */
1969 if (RtlEqualUnicodeString(&KernelName
, &LdrEntry
->BaseDllName
, TRUE
))
1975 else if (RtlEqualUnicodeString(&HalName
, &LdrEntry
->BaseDllName
, TRUE
))
1982 /* Check if we found a valid binary */
1985 /* Find the procedure name */
1986 ProcAddress
= MiFindExportedRoutineByName(LdrEntry
->DllBase
,
1989 /* Break out if we found it or if we already tried both modules */
1990 if (ProcAddress
) break;
1991 if (Modules
== 2) break;
1995 NextEntry
= NextEntry
->Flink
;
1998 /* Release the lock */
1999 KeLeaveCriticalRegion();
2001 /* Free the string and return */
2002 RtlFreeAnsiString(&AnsiRoutineName
);