2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/iomgr/driver.c
5 * PURPOSE: Driver Object Management
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Filip Navara (navaraf@reactos.org)
8 * Hervé Poussineau (hpoussin@reactos.org)
11 /* INCLUDES *******************************************************************/
17 /* GLOBALS ********************************************************************/
19 LIST_ENTRY DriverReinitListHead
;
20 KSPIN_LOCK DriverReinitListLock
;
21 PLIST_ENTRY DriverReinitTailEntry
;
23 PLIST_ENTRY DriverBootReinitTailEntry
;
24 LIST_ENTRY DriverBootReinitListHead
;
25 KSPIN_LOCK DriverBootReinitListLock
;
27 UNICODE_STRING IopHardwareDatabaseKey
=
28 RTL_CONSTANT_STRING(L
"\\REGISTRY\\MACHINE\\HARDWARE\\DESCRIPTION\\SYSTEM");
30 POBJECT_TYPE IoDriverObjectType
= NULL
;
32 #define TAG_RTLREGISTRY 'vrqR'
34 extern BOOLEAN ExpInTextModeSetup
;
35 extern BOOLEAN PnpSystemInit
;
38 PLIST_ENTRY IopGroupTable
;
40 /* PRIVATE FUNCTIONS **********************************************************/
43 IopInvalidDeviceRequest(
44 PDEVICE_OBJECT DeviceObject
,
47 Irp
->IoStatus
.Status
= STATUS_INVALID_DEVICE_REQUEST
;
48 Irp
->IoStatus
.Information
= 0;
49 IoCompleteRequest(Irp
, IO_NO_INCREMENT
);
50 return STATUS_INVALID_DEVICE_REQUEST
;
55 IopDeleteDriver(IN PVOID ObjectBody
)
57 PDRIVER_OBJECT DriverObject
= ObjectBody
;
58 PIO_CLIENT_EXTENSION DriverExtension
, NextDriverExtension
;
61 DPRINT1("Deleting driver object '%wZ'\n", &DriverObject
->DriverName
);
63 /* There must be no device objects remaining at this point */
64 ASSERT(!DriverObject
->DeviceObject
);
66 /* Get the extension and loop them */
67 DriverExtension
= IoGetDrvObjExtension(DriverObject
)->
68 ClientDriverExtension
;
69 while (DriverExtension
)
71 /* Get the next one */
72 NextDriverExtension
= DriverExtension
->NextExtension
;
73 ExFreePoolWithTag(DriverExtension
, TAG_DRIVER_EXTENSION
);
76 DriverExtension
= NextDriverExtension
;
79 /* Check if the driver image is still loaded */
80 if (DriverObject
->DriverSection
)
83 MmUnloadSystemImage(DriverObject
->DriverSection
);
86 /* Check if it has a name */
87 if (DriverObject
->DriverName
.Buffer
)
90 ExFreePool(DriverObject
->DriverName
.Buffer
);
93 #if 0 /* See a bit of hack in IopCreateDriver */
94 /* Check if it has a service key name */
95 if (DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
)
98 ExFreePool(DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
);
105 PDRIVER_OBJECT
*DriverObject
,
106 PUNICODE_STRING ServiceName
,
109 PDRIVER_OBJECT Object
;
110 WCHAR NameBuffer
[MAX_PATH
];
111 UNICODE_STRING DriverName
;
114 DPRINT("IopGetDriverObject(%p '%wZ' %x)\n",
115 DriverObject
, ServiceName
, FileSystem
);
117 *DriverObject
= NULL
;
119 /* Create ModuleName string */
120 if (ServiceName
== NULL
|| ServiceName
->Buffer
== NULL
)
121 /* We don't know which DriverObject we have to open */
122 return STATUS_INVALID_PARAMETER_2
;
124 DriverName
.Buffer
= NameBuffer
;
125 DriverName
.Length
= 0;
126 DriverName
.MaximumLength
= sizeof(NameBuffer
);
128 if (FileSystem
== TRUE
)
129 RtlAppendUnicodeToString(&DriverName
, FILESYSTEM_ROOT_NAME
);
131 RtlAppendUnicodeToString(&DriverName
, DRIVER_ROOT_NAME
);
132 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
134 DPRINT("Driver name: '%wZ'\n", &DriverName
);
136 /* Open driver object */
137 Status
= ObReferenceObjectByName(
139 OBJ_OPENIF
| OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, /* Attributes */
140 NULL
, /* PassedAccessState */
141 0, /* DesiredAccess */
144 NULL
, /* ParseContext */
147 if (!NT_SUCCESS(Status
))
149 DPRINT("Failed to reference driver object, status=0x%08x\n", Status
);
153 *DriverObject
= Object
;
155 DPRINT("Driver Object: %p\n", Object
);
157 return STATUS_SUCCESS
;
162 * TRUE if String2 contains String1 as a suffix.
166 IopSuffixUnicodeString(
167 IN PCUNICODE_STRING String1
,
168 IN PCUNICODE_STRING String2
)
174 if (String2
->Length
< String1
->Length
)
177 Length
= String1
->Length
/ 2;
178 pc1
= String1
->Buffer
;
179 pc2
= &String2
->Buffer
[String2
->Length
/ sizeof(WCHAR
) - Length
];
185 if( *pc1
++ != *pc2
++ )
194 * IopDisplayLoadingMessage
196 * Display 'Loading XXX...' message.
202 IopDisplayLoadingMessage(PUNICODE_STRING ServiceName
)
204 CHAR TextBuffer
[256];
205 UNICODE_STRING DotSys
= RTL_CONSTANT_STRING(L
".SYS");
207 if (ExpInTextModeSetup
) return;
208 if (!KeLoaderBlock
) return;
209 RtlUpcaseUnicodeString(ServiceName
, ServiceName
, FALSE
);
210 snprintf(TextBuffer
, sizeof(TextBuffer
),
211 "%s%sSystem32\\Drivers\\%wZ%s\n",
212 KeLoaderBlock
->ArcBootDeviceName
,
213 KeLoaderBlock
->NtBootPathName
,
215 IopSuffixUnicodeString(&DotSys
, ServiceName
) ? "" : ".SYS");
216 HalDisplayString(TextBuffer
);
220 * IopNormalizeImagePath
222 * Normalize an image path to contain complete path.
226 * The input path and on exit the result path. ImagePath.Buffer
227 * must be allocated by ExAllocatePool on input. Caller is responsible
228 * for freeing the buffer when it's no longer needed.
231 * Name of the service that ImagePath belongs to.
237 * The input image path isn't freed on error.
242 IopNormalizeImagePath(
243 _Inout_
_When_(return>=0, _At_(ImagePath
->Buffer
, _Post_notnull_
__drv_allocatesMem(Mem
)))
244 PUNICODE_STRING ImagePath
,
245 _In_ PUNICODE_STRING ServiceName
)
247 UNICODE_STRING InputImagePath
;
249 DPRINT("Normalizing image path '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
254 sizeof(UNICODE_STRING
));
256 if (InputImagePath
.Length
== 0)
258 ImagePath
->Length
= 0;
259 ImagePath
->MaximumLength
=
260 (33 * sizeof(WCHAR
)) + ServiceName
->Length
+ sizeof(UNICODE_NULL
);
261 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
262 if (ImagePath
->Buffer
== NULL
)
263 return STATUS_NO_MEMORY
;
265 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\system32\\drivers\\");
266 RtlAppendUnicodeStringToString(ImagePath
, ServiceName
);
267 RtlAppendUnicodeToString(ImagePath
, L
".sys");
269 if (InputImagePath
.Buffer
[0] != L
'\\')
271 ImagePath
->Length
= 0;
272 ImagePath
->MaximumLength
=
273 12 * sizeof(WCHAR
) + InputImagePath
.Length
+ sizeof(UNICODE_NULL
);
274 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
275 if (ImagePath
->Buffer
== NULL
)
276 return STATUS_NO_MEMORY
;
278 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\");
279 RtlAppendUnicodeStringToString(ImagePath
, &InputImagePath
);
281 /* Free caller's string */
282 ExFreePoolWithTag(InputImagePath
.Buffer
, TAG_RTLREGISTRY
);
285 DPRINT("Normalized image path is '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
287 return STATUS_SUCCESS
;
291 * IopLoadServiceModule
293 * Load a module specified by registry settings for service.
297 * Name of the service to load.
304 IopLoadServiceModule(
305 IN PUNICODE_STRING ServiceName
,
306 OUT PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
308 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
310 UNICODE_STRING ServiceImagePath
, CCSName
;
312 HANDLE CCSKey
, ServiceKey
;
315 DPRINT("IopLoadServiceModule(%wZ, 0x%p)\n", ServiceName
, ModuleObject
);
317 /* FIXME: This check may be removed once the bug is fixed */
318 if (ServiceName
->Buffer
== NULL
)
320 DPRINT1("If you see this, please report to Fireball or hpoussin!\n");
321 return STATUS_UNSUCCESSFUL
;
324 if (ExpInTextModeSetup
)
326 /* We have no registry, but luckily we know where all the drivers are */
328 /* ServiceStart < 4 is all that matters */
331 /* IopNormalizeImagePath will do all of the work for us if we give it an empty string */
332 ServiceImagePath
.Length
= ServiceImagePath
.MaximumLength
= 0;
333 ServiceImagePath
.Buffer
= NULL
;
337 /* Open CurrentControlSet */
338 RtlInitUnicodeString(&CCSName
,
339 L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services");
340 Status
= IopOpenRegistryKeyEx(&CCSKey
, NULL
, &CCSName
, KEY_READ
);
341 if (!NT_SUCCESS(Status
))
343 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
347 /* Open service key */
348 Status
= IopOpenRegistryKeyEx(&ServiceKey
, CCSKey
, ServiceName
, KEY_READ
);
349 if (!NT_SUCCESS(Status
))
351 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
357 * Get information about the service.
360 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
362 RtlInitUnicodeString(&ServiceImagePath
, NULL
);
364 QueryTable
[0].Name
= L
"Start";
365 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
366 QueryTable
[0].EntryContext
= &ServiceStart
;
368 QueryTable
[1].Name
= L
"ImagePath";
369 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
370 QueryTable
[1].EntryContext
= &ServiceImagePath
;
372 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
373 (PWSTR
)ServiceKey
, QueryTable
, NULL
, NULL
);
378 if (!NT_SUCCESS(Status
))
380 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
386 * Normalize the image path for all later processing.
389 Status
= IopNormalizeImagePath(&ServiceImagePath
, ServiceName
);
391 if (!NT_SUCCESS(Status
))
393 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
398 * Case for disabled drivers
401 if (ServiceStart
>= 4)
403 /* We can't load this */
404 Status
= STATUS_DRIVER_UNABLE_TO_LOAD
;
408 DPRINT("Loading module from %wZ\n", &ServiceImagePath
);
409 Status
= MmLoadSystemImage(&ServiceImagePath
, NULL
, NULL
, 0, (PVOID
)ModuleObject
, &BaseAddress
);
410 if (NT_SUCCESS(Status
))
412 IopDisplayLoadingMessage(ServiceName
);
416 ExFreePool(ServiceImagePath
.Buffer
);
419 * Now check if the module was loaded successfully.
422 if (!NT_SUCCESS(Status
))
424 DPRINT("Module loading failed (Status %x)\n", Status
);
427 DPRINT("Module loading (Status %x)\n", Status
);
434 MmFreeDriverInitialization(IN PLDR_DATA_TABLE_ENTRY LdrEntry
);
437 * IopInitializeDriverModule
439 * Initialize a loaded driver.
443 * Pointer to device node.
446 * Module object representing the driver. It can be retrieve by
447 * IopLoadServiceModule.
450 * Name of the service (as in registry).
453 * Set to TRUE for file system drivers.
456 * On successful return this contains the driver object representing
461 IopInitializeDriverModule(
462 IN PDEVICE_NODE DeviceNode
,
463 IN PLDR_DATA_TABLE_ENTRY ModuleObject
,
464 IN PUNICODE_STRING ServiceName
,
465 IN BOOLEAN FileSystemDriver
,
466 OUT PDRIVER_OBJECT
*DriverObject
)
468 const WCHAR ServicesKeyName
[] = L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";
469 WCHAR NameBuffer
[MAX_PATH
];
470 UNICODE_STRING DriverName
;
471 UNICODE_STRING RegistryKey
;
472 PDRIVER_INITIALIZE DriverEntry
;
473 PDRIVER_OBJECT Driver
;
476 DriverEntry
= ModuleObject
->EntryPoint
;
478 if (ServiceName
!= NULL
&& ServiceName
->Length
!= 0)
480 RegistryKey
.Length
= 0;
481 RegistryKey
.MaximumLength
= sizeof(ServicesKeyName
) + ServiceName
->Length
;
482 RegistryKey
.Buffer
= ExAllocatePool(PagedPool
, RegistryKey
.MaximumLength
);
483 if (RegistryKey
.Buffer
== NULL
)
485 return STATUS_INSUFFICIENT_RESOURCES
;
487 RtlAppendUnicodeToString(&RegistryKey
, ServicesKeyName
);
488 RtlAppendUnicodeStringToString(&RegistryKey
, ServiceName
);
492 RtlInitUnicodeString(&RegistryKey
, NULL
);
495 /* Create ModuleName string */
496 if (ServiceName
&& ServiceName
->Length
> 0)
498 if (FileSystemDriver
== TRUE
)
499 wcscpy(NameBuffer
, FILESYSTEM_ROOT_NAME
);
501 wcscpy(NameBuffer
, DRIVER_ROOT_NAME
);
503 RtlInitUnicodeString(&DriverName
, NameBuffer
);
504 DriverName
.MaximumLength
= sizeof(NameBuffer
);
506 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
508 DPRINT("Driver name: '%wZ'\n", &DriverName
);
511 DriverName
.Length
= 0;
513 Status
= IopCreateDriver(
514 DriverName
.Length
> 0 ? &DriverName
: NULL
,
519 RtlFreeUnicodeString(&RegistryKey
);
521 *DriverObject
= Driver
;
522 if (!NT_SUCCESS(Status
))
524 DPRINT("IopCreateDriver() failed (Status 0x%08lx)\n", Status
);
528 MmFreeDriverInitialization((PLDR_DATA_TABLE_ENTRY
)Driver
->DriverSection
);
530 /* Set the driver as initialized */
531 IopReadyDeviceObjects(Driver
);
533 if (PnpSystemInit
) IopReinitializeDrivers();
535 return STATUS_SUCCESS
;
539 * IopAttachFilterDriversCallback
541 * Internal routine used by IopAttachFilterDrivers.
545 IopAttachFilterDriversCallback(
553 PDEVICE_NODE DeviceNode
= Context
;
554 UNICODE_STRING ServiceName
;
556 PLDR_DATA_TABLE_ENTRY ModuleObject
;
557 PDRIVER_OBJECT DriverObject
;
560 for (Filters
= ValueData
;
561 ((ULONG_PTR
)Filters
- (ULONG_PTR
)ValueData
) < ValueLength
&&
563 Filters
+= (ServiceName
.Length
/ sizeof(WCHAR
)) + 1)
565 DPRINT("Filter Driver: %S (%wZ)\n", Filters
, &DeviceNode
->InstancePath
);
567 ServiceName
.Buffer
= Filters
;
568 ServiceName
.MaximumLength
=
569 ServiceName
.Length
= (USHORT
)wcslen(Filters
) * sizeof(WCHAR
);
571 Status
= IopGetDriverObject(&DriverObject
,
574 if (!NT_SUCCESS(Status
))
576 /* Load and initialize the filter driver */
577 Status
= IopLoadServiceModule(&ServiceName
, &ModuleObject
);
578 if (!NT_SUCCESS(Status
))
581 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
, &ServiceName
,
582 FALSE
, &DriverObject
);
583 if (!NT_SUCCESS(Status
))
587 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
589 /* Remove extra reference */
590 ObDereferenceObject(DriverObject
);
593 return STATUS_SUCCESS
;
597 * IopAttachFilterDrivers
599 * Load filter drivers for specified device node.
603 * Set to TRUE for loading lower level filters or FALSE for upper
608 IopAttachFilterDrivers(
609 PDEVICE_NODE DeviceNode
,
612 RTL_QUERY_REGISTRY_TABLE QueryTable
[2] = { { NULL
, 0, NULL
, NULL
, 0, NULL
, 0 }, };
613 UNICODE_STRING Class
;
614 WCHAR ClassBuffer
[40];
615 UNICODE_STRING EnumRoot
= RTL_CONSTANT_STRING(ENUM_ROOT
);
616 HANDLE EnumRootKey
, SubKey
;
619 /* Open enumeration root key */
620 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
621 &EnumRoot
, KEY_READ
);
622 if (!NT_SUCCESS(Status
))
624 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
629 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
630 &DeviceNode
->InstancePath
, KEY_READ
);
631 if (!NT_SUCCESS(Status
))
633 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
634 ZwClose(EnumRootKey
);
639 * First load the device filters
641 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
643 QueryTable
[0].Name
= L
"LowerFilters";
645 QueryTable
[0].Name
= L
"UpperFilters";
646 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
648 RtlQueryRegistryValues(
656 * Now get the class GUID
659 Class
.MaximumLength
= 40 * sizeof(WCHAR
);
660 Class
.Buffer
= ClassBuffer
;
661 QueryTable
[0].QueryRoutine
= NULL
;
662 QueryTable
[0].Name
= L
"ClassGUID";
663 QueryTable
[0].EntryContext
= &Class
;
664 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
| RTL_QUERY_REGISTRY_DIRECT
;
666 Status
= RtlQueryRegistryValues(
675 ZwClose(EnumRootKey
);
678 * Load the class filter driver
680 if (NT_SUCCESS(Status
))
682 UNICODE_STRING ControlClass
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class");
684 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
685 &ControlClass
, KEY_READ
);
686 if (!NT_SUCCESS(Status
))
688 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
693 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
695 if (!NT_SUCCESS(Status
))
697 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
698 ZwClose(EnumRootKey
);
702 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
704 QueryTable
[0].Name
= L
"LowerFilters";
706 QueryTable
[0].Name
= L
"UpperFilters";
707 QueryTable
[0].EntryContext
= NULL
;
708 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
710 RtlQueryRegistryValues(
719 ZwClose(EnumRootKey
);
722 return STATUS_SUCCESS
;
727 MiResolveImageReferences(IN PVOID ImageBase
,
728 IN PUNICODE_STRING ImageFileDirectory
,
729 IN PUNICODE_STRING NamePrefix OPTIONAL
,
730 OUT PCHAR
*MissingApi
,
731 OUT PWCHAR
*MissingDriver
,
732 OUT PLOAD_IMPORTS
*LoadImports
);
735 // Used for images already loaded (boot drivers)
740 LdrProcessDriverModule(PLDR_DATA_TABLE_ENTRY LdrEntry
,
741 PUNICODE_STRING FileName
,
742 PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
745 UNICODE_STRING BaseName
, BaseDirectory
;
746 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
747 PCHAR MissingApiName
, Buffer
;
748 PWCHAR MissingDriverName
;
749 PVOID DriverBase
= LdrEntry
->DllBase
;
751 /* Allocate a buffer we'll use for names */
752 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
756 return STATUS_INSUFFICIENT_RESOURCES
;
759 /* Check for a separator */
760 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
765 /* Loop the path until we get to the base name */
766 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
767 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
770 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
771 BaseLength
*= sizeof(WCHAR
);
773 /* Setup the string */
774 BaseName
.Length
= (USHORT
)BaseLength
;
779 /* Otherwise, we already have a base name */
780 BaseName
.Length
= FileName
->Length
;
781 BaseName
.Buffer
= FileName
->Buffer
;
784 /* Setup the maximum length */
785 BaseName
.MaximumLength
= BaseName
.Length
;
787 /* Now compute the base directory */
788 BaseDirectory
= *FileName
;
789 BaseDirectory
.Length
-= BaseName
.Length
;
790 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
792 /* Resolve imports */
793 MissingApiName
= Buffer
;
794 Status
= MiResolveImageReferences(DriverBase
,
801 /* Free the temporary buffer */
802 ExFreePoolWithTag(Buffer
, TAG_LDR_WSTR
);
804 /* Check the result of the imports resolution */
805 if (!NT_SUCCESS(Status
)) return Status
;
808 *ModuleObject
= LdrEntry
;
809 return STATUS_SUCCESS
;
813 * IopInitializeBuiltinDriver
815 * Initialize a driver that is already loaded in memory.
821 IopInitializeBuiltinDriver(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
823 PDEVICE_NODE DeviceNode
;
824 PDRIVER_OBJECT DriverObject
;
826 PWCHAR FileNameWithoutPath
;
827 LPWSTR FileExtension
;
828 PUNICODE_STRING ModuleName
= &LdrEntry
->BaseDllName
;
829 UNICODE_STRING ServiceName
;
832 * Display 'Loading XXX...' message
834 IopDisplayLoadingMessage(ModuleName
);
835 InbvIndicateProgress();
838 * Generate filename without path (not needed by freeldr)
840 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
841 if (FileNameWithoutPath
== NULL
)
843 FileNameWithoutPath
= ModuleName
->Buffer
;
847 FileNameWithoutPath
++;
851 * Strip the file extension from ServiceName
853 RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
854 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
855 if (FileExtension
!= NULL
)
857 ServiceName
.Length
-= (USHORT
)wcslen(FileExtension
) * sizeof(WCHAR
);
858 FileExtension
[0] = 0;
862 * Determine the right device object
864 /* Use IopRootDeviceNode for now */
865 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
866 if (!NT_SUCCESS(Status
))
868 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
873 * Initialize the driver
875 Status
= IopInitializeDriverModule(DeviceNode
, LdrEntry
,
876 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
878 if (!NT_SUCCESS(Status
))
880 IopFreeDeviceNode(DeviceNode
);
884 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
885 if (NT_SUCCESS(Status
))
887 Status
= IopStartDevice(DeviceNode
);
890 /* Remove extra reference from IopInitializeDriverModule */
891 ObDereferenceObject(DriverObject
);
897 * IopInitializeBootDrivers
899 * Initialize boot drivers and free memory for boot files.
910 IopInitializeBootDrivers(VOID
)
912 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
913 PLDR_DATA_TABLE_ENTRY LdrEntry
;
914 PDEVICE_NODE DeviceNode
;
915 PDRIVER_OBJECT DriverObject
;
916 LDR_DATA_TABLE_ENTRY ModuleObject
;
918 UNICODE_STRING DriverName
;
920 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
922 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
923 DPRINT("IopInitializeBootDrivers()\n");
925 /* Use IopRootDeviceNode for now */
926 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
927 if (!NT_SUCCESS(Status
)) return;
929 /* Setup the module object for the RAW FS Driver */
930 ModuleObject
.DllBase
= NULL
;
931 ModuleObject
.SizeOfImage
= 0;
932 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
933 RtlInitUnicodeString(&DriverName
, L
"RAW");
936 Status
= IopInitializeDriverModule(DeviceNode
,
941 if (!NT_SUCCESS(Status
))
944 IopFreeDeviceNode(DeviceNode
);
948 /* Now initialize the associated device */
949 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
950 if (!NT_SUCCESS(Status
))
953 IopFreeDeviceNode(DeviceNode
);
954 ObDereferenceObject(DriverObject
);
959 Status
= IopStartDevice(DeviceNode
);
960 if (!NT_SUCCESS(Status
))
963 IopFreeDeviceNode(DeviceNode
);
964 ObDereferenceObject(DriverObject
);
968 /* Get highest group order index */
969 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
970 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
972 /* Allocate the group table */
973 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
974 IopGroupIndex
* sizeof(LIST_ENTRY
),
976 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
978 /* Initialize the group table lists */
979 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
981 /* Loop the boot modules */
982 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
983 NextEntry
= ListHead
->Flink
;
984 while (ListHead
!= NextEntry
)
987 LdrEntry
= CONTAINING_RECORD(NextEntry
,
988 LDR_DATA_TABLE_ENTRY
,
991 /* Check if the DLL needs to be initialized */
992 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
994 /* Call its entrypoint */
995 MmCallDllInitialize(LdrEntry
, NULL
);
998 /* Go to the next driver */
999 NextEntry
= NextEntry
->Flink
;
1002 /* Loop the boot drivers */
1003 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
1004 NextEntry
= ListHead
->Flink
;
1005 while (ListHead
!= NextEntry
)
1008 BootEntry
= CONTAINING_RECORD(NextEntry
,
1009 BOOT_DRIVER_LIST_ENTRY
,
1012 /* Get the driver loader entry */
1013 LdrEntry
= BootEntry
->LdrEntry
;
1015 /* Allocate our internal accounting structure */
1016 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
1017 sizeof(DRIVER_INFORMATION
),
1021 /* Zero it and initialize it */
1022 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1023 InitializeListHead(&DriverInfo
->Link
);
1024 DriverInfo
->DataTableEntry
= BootEntry
;
1026 /* Open the registry key */
1027 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1029 &BootEntry
->RegistryPath
,
1031 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1032 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1034 /* Save the handle */
1035 DriverInfo
->ServiceHandle
= KeyHandle
;
1037 /* Get the group oder index */
1038 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1040 /* Get the tag position */
1041 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1043 /* Insert it into the list, at the right place */
1044 ASSERT(Index
< IopGroupIndex
);
1045 NextEntry2
= IopGroupTable
[Index
].Flink
;
1046 while (NextEntry2
!= &IopGroupTable
[Index
])
1048 /* Get the driver info */
1049 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1053 /* Check if we found the right tag position */
1054 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1061 NextEntry2
= NextEntry2
->Flink
;
1064 /* Insert us right before the next entry */
1065 NextEntry2
= NextEntry2
->Blink
;
1066 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1070 /* Go to the next driver */
1071 NextEntry
= NextEntry
->Flink
;
1074 /* Loop each group index */
1075 for (i
= 0; i
< IopGroupIndex
; i
++)
1077 /* Loop each group table */
1078 NextEntry
= IopGroupTable
[i
].Flink
;
1079 while (NextEntry
!= &IopGroupTable
[i
])
1082 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1086 /* Get the driver loader entry */
1087 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1090 IopInitializeBuiltinDriver(LdrEntry
);
1093 NextEntry
= NextEntry
->Flink
;
1097 /* In old ROS, the loader list became empty after this point. Simulate. */
1098 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1104 IopInitializeSystemDrivers(VOID
)
1106 PUNICODE_STRING
*DriverList
, *SavedList
;
1108 /* No system drivers on the boot cd */
1109 if (KeLoaderBlock
->SetupLdrBlock
) return;
1111 /* Get the driver list */
1112 SavedList
= DriverList
= CmGetSystemDriverList();
1118 /* Load the driver */
1119 ZwLoadDriver(*DriverList
);
1121 /* Free the entry */
1122 RtlFreeUnicodeString(*DriverList
);
1123 ExFreePool(*DriverList
);
1126 InbvIndicateProgress();
1131 ExFreePool(SavedList
);
1137 * Unloads a device driver.
1141 * Name of the service to unload (registry key).
1144 * Whether to unload Plug & Plug or only legacy drivers. If this
1145 * parameter is set to FALSE, the routine will unload only legacy
1152 * Guard the whole function by SEH.
1156 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1158 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1159 UNICODE_STRING ImagePath
;
1160 UNICODE_STRING ServiceName
;
1161 UNICODE_STRING ObjectName
;
1162 PDRIVER_OBJECT DriverObject
;
1163 PDEVICE_OBJECT DeviceObject
;
1164 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1165 LOAD_UNLOAD_PARAMS LoadParams
;
1168 BOOLEAN SafeToUnload
= TRUE
;
1170 DPRINT("IopUnloadDriver('%wZ', %d)\n", DriverServiceName
, UnloadPnpDrivers
);
1175 * Get the service name from the registry key name
1178 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1180 Start
= DriverServiceName
->Buffer
;
1184 RtlInitUnicodeString(&ServiceName
, Start
);
1187 * Construct the driver object name
1190 ObjectName
.Length
= ((USHORT
)wcslen(Start
) + 8) * sizeof(WCHAR
);
1191 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1192 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1193 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1194 wcscpy(ObjectName
.Buffer
, L
"\\Driver\\");
1195 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1196 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1199 * Find the driver object
1201 Status
= ObReferenceObjectByName(&ObjectName
,
1208 (PVOID
*)&DriverObject
);
1210 if (!NT_SUCCESS(Status
))
1212 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1213 ExFreePool(ObjectName
.Buffer
);
1218 * Free the buffer for driver object name
1220 ExFreePool(ObjectName
.Buffer
);
1222 /* Check that driver is not already unloading */
1223 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1225 DPRINT1("Driver deletion pending\n");
1226 ObDereferenceObject(DriverObject
);
1227 return STATUS_DELETE_PENDING
;
1231 * Get path of service...
1234 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1236 RtlInitUnicodeString(&ImagePath
, NULL
);
1238 QueryTable
[0].Name
= L
"ImagePath";
1239 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1240 QueryTable
[0].EntryContext
= &ImagePath
;
1242 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1243 DriverServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1245 if (!NT_SUCCESS(Status
))
1247 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1248 ObDereferenceObject(DriverObject
);
1253 * Normalize the image path for all later processing.
1256 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1258 if (!NT_SUCCESS(Status
))
1260 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1261 ObDereferenceObject(DriverObject
);
1266 * Free the service path
1269 ExFreePool(ImagePath
.Buffer
);
1272 * Unload the module and release the references to the device object
1275 /* Call the load/unload routine, depending on current process */
1276 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
&&
1277 (UnloadPnpDrivers
|| (DriverObject
->Flags
& DRVO_LEGACY_DRIVER
)))
1279 /* Loop through each device object of the driver
1280 and set DOE_UNLOAD_PENDING flag */
1281 DeviceObject
= DriverObject
->DeviceObject
;
1282 while (DeviceObject
)
1284 /* Set the unload pending flag for the device */
1285 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1286 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1288 /* Make sure there are no attached devices or no reference counts */
1289 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1291 /* Not safe to unload */
1292 DPRINT1("Drivers device object is referenced or has attached devices\n");
1294 SafeToUnload
= FALSE
;
1297 DeviceObject
= DeviceObject
->NextDevice
;
1300 /* If not safe to unload, then return success */
1303 ObDereferenceObject(DriverObject
);
1304 return STATUS_SUCCESS
;
1307 DPRINT1("Unloading driver '%wZ' (manual)\n", &DriverObject
->DriverName
);
1309 /* Set the unload invoked flag */
1310 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1312 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
1314 /* Just call right away */
1315 (*DriverObject
->DriverUnload
)(DriverObject
);
1319 /* Load/Unload must be called from system process */
1321 /* Prepare parameters block */
1322 LoadParams
.DriverObject
= DriverObject
;
1323 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1325 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1326 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
1327 (PVOID
)&LoadParams
);
1330 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1332 /* And wait when it completes */
1333 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
1337 /* Mark the driver object temporary, so it could be deleted later */
1338 ObMakeTemporaryObject(DriverObject
);
1340 /* Dereference it 2 times */
1341 ObDereferenceObject(DriverObject
);
1342 ObDereferenceObject(DriverObject
);
1344 return STATUS_SUCCESS
;
1348 DPRINT1("No DriverUnload function! '%wZ' will not be unloaded!\n", &DriverObject
->DriverName
);
1350 /* Dereference one time (refd inside this function) */
1351 ObDereferenceObject(DriverObject
);
1353 /* Return unloading failure */
1354 return STATUS_INVALID_DEVICE_REQUEST
;
1360 IopReinitializeDrivers(VOID
)
1362 PDRIVER_REINIT_ITEM ReinitItem
;
1365 /* Get the first entry and start looping */
1366 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1367 &DriverReinitListLock
);
1371 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1373 /* Increment reinitialization counter */
1374 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1376 /* Remove the device object flag */
1377 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1379 /* Call the routine */
1380 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1381 ReinitItem
->Context
,
1382 ReinitItem
->DriverObject
->
1383 DriverExtension
->Count
);
1385 /* Free the entry */
1388 /* Move to the next one */
1389 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1390 &DriverReinitListLock
);
1396 IopReinitializeBootDrivers(VOID
)
1398 PDRIVER_REINIT_ITEM ReinitItem
;
1401 /* Get the first entry and start looping */
1402 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1403 &DriverBootReinitListLock
);
1407 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1409 /* Increment reinitialization counter */
1410 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1412 /* Remove the device object flag */
1413 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1415 /* Call the routine */
1416 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1417 ReinitItem
->Context
,
1418 ReinitItem
->DriverObject
->
1419 DriverExtension
->Count
);
1421 /* Free the entry */
1424 /* Move to the next one */
1425 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1426 &DriverBootReinitListLock
);
1432 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1433 IN PDRIVER_INITIALIZE InitializationFunction
,
1434 IN PUNICODE_STRING RegistryPath
,
1435 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1436 OUT PDRIVER_OBJECT
*pDriverObject
)
1438 WCHAR NameBuffer
[100];
1440 UNICODE_STRING LocalDriverName
;
1442 OBJECT_ATTRIBUTES ObjectAttributes
;
1444 PDRIVER_OBJECT DriverObject
;
1445 UNICODE_STRING ServiceKeyName
;
1447 ULONG i
, RetryCount
= 0;
1450 /* First, create a unique name for the driver if we don't have one */
1453 /* Create a random name and set up the string*/
1454 NameLength
= (USHORT
)swprintf(NameBuffer
,
1457 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1458 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1459 LocalDriverName
.Buffer
= NameBuffer
;
1463 /* So we can avoid another code path, use a local var */
1464 LocalDriverName
= *DriverName
;
1467 /* Initialize the Attributes */
1468 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1469 InitializeObjectAttributes(&ObjectAttributes
,
1471 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
,
1475 /* Create the Object */
1476 Status
= ObCreateObject(KernelMode
,
1484 (PVOID
*)&DriverObject
);
1485 if (!NT_SUCCESS(Status
)) return Status
;
1487 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1489 /* Set up the Object */
1490 RtlZeroMemory(DriverObject
, ObjectSize
);
1491 DriverObject
->Type
= IO_TYPE_DRIVER
;
1492 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1493 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;
1494 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1495 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1496 DriverObject
->DriverInit
= InitializationFunction
;
1497 DriverObject
->DriverSection
= ModuleObject
;
1498 /* Loop all Major Functions */
1499 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1501 /* Invalidate each function */
1502 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1505 /* Set up the service key name buffer */
1506 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1507 LocalDriverName
.Length
+
1510 if (!ServiceKeyName
.Buffer
)
1513 ObMakeTemporaryObject(DriverObject
);
1514 ObDereferenceObject(DriverObject
);
1515 return STATUS_INSUFFICIENT_RESOURCES
;
1518 /* Fill out the key data and copy the buffer */
1519 ServiceKeyName
.Length
= LocalDriverName
.Length
;
1520 ServiceKeyName
.MaximumLength
= LocalDriverName
.MaximumLength
;
1521 RtlCopyMemory(ServiceKeyName
.Buffer
,
1522 LocalDriverName
.Buffer
,
1523 LocalDriverName
.Length
);
1525 /* Null-terminate it and set it */
1526 ServiceKeyName
.Buffer
[ServiceKeyName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1527 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1529 /* Also store it in the Driver Object. This is a bit of a hack. */
1530 RtlCopyMemory(&DriverObject
->DriverName
,
1532 sizeof(UNICODE_STRING
));
1534 /* Add the Object and get its handle */
1535 Status
= ObInsertObject(DriverObject
,
1542 /* Eliminate small possibility when this function is called more than
1543 once in a row, and KeTickCount doesn't get enough time to change */
1544 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1550 if (!NT_SUCCESS(Status
)) return Status
;
1552 /* Now reference it */
1553 Status
= ObReferenceObjectByHandle(hDriver
,
1557 (PVOID
*)&DriverObject
,
1560 /* Close the extra handle */
1563 if (!NT_SUCCESS(Status
))
1566 ObMakeTemporaryObject(DriverObject
);
1567 ObDereferenceObject(DriverObject
);
1571 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1572 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1573 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1575 /* Finally, call its init function */
1576 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1577 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1578 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1579 if (!NT_SUCCESS(Status
))
1581 /* If it didn't work, then kill the object */
1582 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1583 DriverObject
->DriverSection
= NULL
;
1584 ObMakeTemporaryObject(DriverObject
);
1585 ObDereferenceObject(DriverObject
);
1590 /* Returns to caller the object */
1591 *pDriverObject
= DriverObject
;
1594 /* We're going to say if we don't have any DOs from DriverEntry, then we're not legacy.
1595 * Other parts of the I/O manager depend on this behavior */
1596 if (!DriverObject
->DeviceObject
) DriverObject
->Flags
&= ~DRVO_LEGACY_DRIVER
;
1598 /* Loop all Major Functions */
1599 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1602 * Make sure the driver didn't set any dispatch entry point to NULL!
1603 * Doing so is illegal; drivers shouldn't touch entry points they
1607 /* Check if it did so anyway */
1608 if (!DriverObject
->MajorFunction
[i
])
1610 /* Print a warning in the debug log */
1611 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%d] to NULL!\n",
1612 &DriverObject
->DriverName
, i
);
1615 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1619 /* Return the Status */
1623 /* PUBLIC FUNCTIONS ***********************************************************/
1630 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1631 IN PDRIVER_INITIALIZE InitializationFunction
)
1633 PDRIVER_OBJECT DriverObject
;
1634 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, NULL
, &DriverObject
);
1642 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1644 /* Simply dereference the Object */
1645 ObDereferenceObject(DriverObject
);
1653 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1654 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1657 PDRIVER_REINIT_ITEM ReinitItem
;
1659 /* Allocate the entry */
1660 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1661 sizeof(DRIVER_REINIT_ITEM
),
1663 if (!ReinitItem
) return;
1666 ReinitItem
->DriverObject
= DriverObject
;
1667 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1668 ReinitItem
->Context
= Context
;
1670 /* Set the Driver Object flag and insert the entry into the list */
1671 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1672 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1673 &ReinitItem
->ItemEntry
,
1674 &DriverBootReinitListLock
);
1682 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1683 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1686 PDRIVER_REINIT_ITEM ReinitItem
;
1688 /* Allocate the entry */
1689 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1690 sizeof(DRIVER_REINIT_ITEM
),
1692 if (!ReinitItem
) return;
1695 ReinitItem
->DriverObject
= DriverObject
;
1696 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1697 ReinitItem
->Context
= Context
;
1699 /* Set the Driver Object flag and insert the entry into the list */
1700 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1701 ExInterlockedInsertTailList(&DriverReinitListHead
,
1702 &ReinitItem
->ItemEntry
,
1703 &DriverReinitListLock
);
1711 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1712 IN PVOID ClientIdentificationAddress
,
1713 IN ULONG DriverObjectExtensionSize
,
1714 OUT PVOID
*DriverObjectExtension
)
1717 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1718 BOOLEAN Inserted
= FALSE
;
1720 /* Assume failure */
1721 *DriverObjectExtension
= NULL
;
1723 /* Allocate the extension */
1724 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1725 sizeof(IO_CLIENT_EXTENSION
) +
1726 DriverObjectExtensionSize
,
1727 TAG_DRIVER_EXTENSION
);
1728 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1730 /* Clear the extension for teh caller */
1731 RtlZeroMemory(NewDriverExtension
,
1732 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1735 OldIrql
= KeRaiseIrqlToDpcLevel();
1737 /* Fill out the extension */
1738 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1740 /* Loop the current extensions */
1741 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1742 ClientDriverExtension
;
1743 while (DriverExtensions
)
1745 /* Check if the identifier matches */
1746 if (DriverExtensions
->ClientIdentificationAddress
==
1747 ClientIdentificationAddress
)
1749 /* We have a collision, break out */
1753 /* Go to the next one */
1754 DriverExtensions
= DriverExtensions
->NextExtension
;
1757 /* Check if we didn't collide */
1758 if (!DriverExtensions
)
1760 /* Link this one in */
1761 NewDriverExtension
->NextExtension
=
1762 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1763 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1768 /* Release the lock */
1769 KeLowerIrql(OldIrql
);
1771 /* Check if insertion failed */
1774 /* Free the entry and fail */
1775 ExFreePoolWithTag(NewDriverExtension
, TAG_DRIVER_EXTENSION
);
1776 return STATUS_OBJECT_NAME_COLLISION
;
1779 /* Otherwise, return the pointer */
1780 *DriverObjectExtension
= NewDriverExtension
+ 1;
1781 return STATUS_SUCCESS
;
1789 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1790 IN PVOID ClientIdentificationAddress
)
1793 PIO_CLIENT_EXTENSION DriverExtensions
;
1796 OldIrql
= KeRaiseIrqlToDpcLevel();
1798 /* Loop the list until we find the right one */
1799 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1800 while (DriverExtensions
)
1802 /* Check for a match */
1803 if (DriverExtensions
->ClientIdentificationAddress
==
1804 ClientIdentificationAddress
)
1811 DriverExtensions
= DriverExtensions
->NextExtension
;
1815 KeLowerIrql(OldIrql
);
1817 /* Return nothing or the extension */
1818 if (!DriverExtensions
) return NULL
;
1819 return DriverExtensions
+ 1;
1823 IopLoadUnloadDriver(PLOAD_UNLOAD_PARAMS LoadParams
)
1825 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1826 UNICODE_STRING ImagePath
;
1827 UNICODE_STRING ServiceName
;
1830 PDEVICE_NODE DeviceNode
;
1831 PDRIVER_OBJECT DriverObject
;
1832 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1836 /* Check if it's an unload request */
1837 if (LoadParams
->DriverObject
)
1839 (*LoadParams
->DriverObject
->DriverUnload
)(LoadParams
->DriverObject
);
1841 /* Return success and signal the event */
1842 LoadParams
->Status
= STATUS_SUCCESS
;
1843 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1847 RtlInitUnicodeString(&ImagePath
, NULL
);
1850 * Get the service name from the registry key name.
1852 ASSERT(LoadParams
->ServiceName
->Length
>= sizeof(WCHAR
));
1854 ServiceName
= *LoadParams
->ServiceName
;
1855 cur
= LoadParams
->ServiceName
->Buffer
+
1856 (LoadParams
->ServiceName
->Length
/ sizeof(WCHAR
)) - 1;
1857 while (LoadParams
->ServiceName
->Buffer
!= cur
)
1861 ServiceName
.Buffer
= cur
+ 1;
1862 ServiceName
.Length
= LoadParams
->ServiceName
->Length
-
1863 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1864 (ULONG_PTR
)LoadParams
->ServiceName
->Buffer
);
1874 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1876 RtlInitUnicodeString(&ImagePath
, NULL
);
1878 QueryTable
[0].Name
= L
"Type";
1879 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1880 QueryTable
[0].EntryContext
= &Type
;
1882 QueryTable
[1].Name
= L
"ImagePath";
1883 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1884 QueryTable
[1].EntryContext
= &ImagePath
;
1886 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1887 LoadParams
->ServiceName
->Buffer
,
1888 QueryTable
, NULL
, NULL
);
1890 if (!NT_SUCCESS(Status
))
1892 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1893 if (ImagePath
.Buffer
) ExFreePool(ImagePath
.Buffer
);
1894 LoadParams
->Status
= Status
;
1895 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1900 * Normalize the image path for all later processing.
1903 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1905 if (!NT_SUCCESS(Status
))
1907 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1908 LoadParams
->Status
= Status
;
1909 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1913 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1914 DPRINT("Type: %lx\n", Type
);
1916 /* Get existing DriverObject pointer (in case the driver has
1917 already been loaded and initialized) */
1918 Status
= IopGetDriverObject(
1921 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1922 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
1924 if (!NT_SUCCESS(Status
))
1927 * Load the driver module
1930 DPRINT("Loading module from %wZ\n", &ImagePath
);
1931 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
1933 if (!NT_SUCCESS(Status
))
1935 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
1936 LoadParams
->Status
= Status
;
1937 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1942 * Initialize the driver module if it's loaded for the first time
1944 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
1945 if (!NT_SUCCESS(Status
))
1947 DPRINT1("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
1948 MmUnloadSystemImage(ModuleObject
);
1949 LoadParams
->Status
= Status
;
1950 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1954 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
1956 Status
= IopInitializeDriverModule(DeviceNode
,
1958 &DeviceNode
->ServiceName
,
1959 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1960 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
1962 if (!NT_SUCCESS(Status
))
1964 DPRINT1("IopInitializeDriverModule() failed (Status %lx)\n", Status
);
1965 MmUnloadSystemImage(ModuleObject
);
1966 IopFreeDeviceNode(DeviceNode
);
1967 LoadParams
->Status
= Status
;
1968 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1972 /* Initialize and start device */
1973 IopInitializeDevice(DeviceNode
, DriverObject
);
1974 Status
= IopStartDevice(DeviceNode
);
1978 DPRINT("DriverObject already exist in ObjectManager\n");
1979 Status
= STATUS_IMAGE_ALREADY_LOADED
;
1981 /* IopGetDriverObject references the DriverObject, so dereference it */
1982 ObDereferenceObject(DriverObject
);
1985 /* Pass status to the caller and signal the event */
1986 LoadParams
->Status
= Status
;
1987 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1993 * Loads a device driver.
1997 * Name of the service to load (registry key).
2006 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
2008 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
2009 KPROCESSOR_MODE PreviousMode
;
2010 LOAD_UNLOAD_PARAMS LoadParams
;
2015 PreviousMode
= KeGetPreviousMode();
2018 * Check security privileges
2021 /* FIXME: Uncomment when privileges will be correctly implemented. */
2023 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
2025 DPRINT("Privilege not held\n");
2026 return STATUS_PRIVILEGE_NOT_HELD
;
2030 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2033 if (!NT_SUCCESS(Status
))
2038 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2040 LoadParams
.ServiceName
= &CapturedDriverServiceName
;
2041 LoadParams
.DriverObject
= NULL
;
2042 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
2044 /* Call the load/unload routine, depending on current process */
2045 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
2047 /* Just call right away */
2048 IopLoadUnloadDriver(&LoadParams
);
2052 /* Load/Unload must be called from system process */
2053 ExInitializeWorkItem(&LoadParams
.WorkItem
,
2054 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
2055 (PVOID
)&LoadParams
);
2058 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
2060 /* And wait when it completes */
2061 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
2065 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2068 return LoadParams
.Status
;
2074 * Unloads a legacy device driver.
2078 * Name of the service to unload (registry key).
2088 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2090 return IopUnloadDriver(DriverServiceName
, FALSE
);