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.
241 IopNormalizeImagePath(
242 IN OUT PUNICODE_STRING ImagePath
,
243 IN PUNICODE_STRING ServiceName
)
245 UNICODE_STRING InputImagePath
;
247 DPRINT("Normalizing image path '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
252 sizeof(UNICODE_STRING
));
254 if (InputImagePath
.Length
== 0)
256 ImagePath
->Length
= 0;
257 ImagePath
->MaximumLength
=
258 (33 * sizeof(WCHAR
)) + ServiceName
->Length
+ sizeof(UNICODE_NULL
);
259 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
260 if (ImagePath
->Buffer
== NULL
)
261 return STATUS_NO_MEMORY
;
263 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\system32\\drivers\\");
264 RtlAppendUnicodeStringToString(ImagePath
, ServiceName
);
265 RtlAppendUnicodeToString(ImagePath
, L
".sys");
267 if (InputImagePath
.Buffer
[0] != L
'\\')
269 ImagePath
->Length
= 0;
270 ImagePath
->MaximumLength
=
271 12 * sizeof(WCHAR
) + InputImagePath
.Length
+ sizeof(UNICODE_NULL
);
272 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
273 if (ImagePath
->Buffer
== NULL
)
274 return STATUS_NO_MEMORY
;
276 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\");
277 RtlAppendUnicodeStringToString(ImagePath
, &InputImagePath
);
279 /* Free caller's string */
280 ExFreePoolWithTag(InputImagePath
.Buffer
, TAG_RTLREGISTRY
);
283 DPRINT("Normalized image path is '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
285 return STATUS_SUCCESS
;
289 * IopLoadServiceModule
291 * Load a module specified by registry settings for service.
295 * Name of the service to load.
302 IopLoadServiceModule(
303 IN PUNICODE_STRING ServiceName
,
304 OUT PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
306 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
308 UNICODE_STRING ServiceImagePath
, CCSName
;
310 HANDLE CCSKey
, ServiceKey
;
313 DPRINT("IopLoadServiceModule(%wZ, 0x%p)\n", ServiceName
, ModuleObject
);
315 /* FIXME: This check may be removed once the bug is fixed */
316 if (ServiceName
->Buffer
== NULL
)
318 DPRINT1("If you see this, please report to Fireball or hpoussin!\n");
319 return STATUS_UNSUCCESSFUL
;
322 if (ExpInTextModeSetup
)
324 /* We have no registry, but luckily we know where all the drivers are */
326 /* ServiceStart < 4 is all that matters */
329 /* IopNormalizeImagePath will do all of the work for us if we give it an empty string */
330 ServiceImagePath
.Length
= ServiceImagePath
.MaximumLength
= 0;
331 ServiceImagePath
.Buffer
= NULL
;
335 /* Open CurrentControlSet */
336 RtlInitUnicodeString(&CCSName
,
337 L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services");
338 Status
= IopOpenRegistryKeyEx(&CCSKey
, NULL
, &CCSName
, KEY_READ
);
339 if (!NT_SUCCESS(Status
))
341 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
345 /* Open service key */
346 Status
= IopOpenRegistryKeyEx(&ServiceKey
, CCSKey
, ServiceName
, KEY_READ
);
347 if (!NT_SUCCESS(Status
))
349 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
355 * Get information about the service.
358 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
360 RtlInitUnicodeString(&ServiceImagePath
, NULL
);
362 QueryTable
[0].Name
= L
"Start";
363 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
364 QueryTable
[0].EntryContext
= &ServiceStart
;
366 QueryTable
[1].Name
= L
"ImagePath";
367 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
368 QueryTable
[1].EntryContext
= &ServiceImagePath
;
370 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
371 (PWSTR
)ServiceKey
, QueryTable
, NULL
, NULL
);
376 if (!NT_SUCCESS(Status
))
378 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
384 * Normalize the image path for all later processing.
387 Status
= IopNormalizeImagePath(&ServiceImagePath
, ServiceName
);
389 if (!NT_SUCCESS(Status
))
391 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
396 * Case for disabled drivers
399 if (ServiceStart
>= 4)
401 /* We can't load this */
402 Status
= STATUS_DRIVER_UNABLE_TO_LOAD
;
406 DPRINT("Loading module from %wZ\n", &ServiceImagePath
);
407 Status
= MmLoadSystemImage(&ServiceImagePath
, NULL
, NULL
, 0, (PVOID
)ModuleObject
, &BaseAddress
);
408 if (NT_SUCCESS(Status
))
410 IopDisplayLoadingMessage(ServiceName
);
414 ExFreePool(ServiceImagePath
.Buffer
);
417 * Now check if the module was loaded successfully.
420 if (!NT_SUCCESS(Status
))
422 DPRINT("Module loading failed (Status %x)\n", Status
);
425 DPRINT("Module loading (Status %x)\n", Status
);
432 MmFreeDriverInitialization(IN PLDR_DATA_TABLE_ENTRY LdrEntry
);
435 * IopInitializeDriverModule
437 * Initalize a loaded driver.
441 * Pointer to device node.
444 * Module object representing the driver. It can be retrieve by
445 * IopLoadServiceModule.
448 * Name of the service (as in registry).
451 * Set to TRUE for file system drivers.
454 * On successful return this contains the driver object representing
459 IopInitializeDriverModule(
460 IN PDEVICE_NODE DeviceNode
,
461 IN PLDR_DATA_TABLE_ENTRY ModuleObject
,
462 IN PUNICODE_STRING ServiceName
,
463 IN BOOLEAN FileSystemDriver
,
464 OUT PDRIVER_OBJECT
*DriverObject
)
466 const WCHAR ServicesKeyName
[] = L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";
467 WCHAR NameBuffer
[MAX_PATH
];
468 UNICODE_STRING DriverName
;
469 UNICODE_STRING RegistryKey
;
470 PDRIVER_INITIALIZE DriverEntry
;
471 PDRIVER_OBJECT Driver
;
474 DriverEntry
= ModuleObject
->EntryPoint
;
476 if (ServiceName
!= NULL
&& ServiceName
->Length
!= 0)
478 RegistryKey
.Length
= 0;
479 RegistryKey
.MaximumLength
= sizeof(ServicesKeyName
) + ServiceName
->Length
;
480 RegistryKey
.Buffer
= ExAllocatePool(PagedPool
, RegistryKey
.MaximumLength
);
481 if (RegistryKey
.Buffer
== NULL
)
483 return STATUS_INSUFFICIENT_RESOURCES
;
485 RtlAppendUnicodeToString(&RegistryKey
, ServicesKeyName
);
486 RtlAppendUnicodeStringToString(&RegistryKey
, ServiceName
);
490 RtlInitUnicodeString(&RegistryKey
, NULL
);
493 /* Create ModuleName string */
494 if (ServiceName
&& ServiceName
->Length
> 0)
496 if (FileSystemDriver
== TRUE
)
497 wcscpy(NameBuffer
, FILESYSTEM_ROOT_NAME
);
499 wcscpy(NameBuffer
, DRIVER_ROOT_NAME
);
501 RtlInitUnicodeString(&DriverName
, NameBuffer
);
502 DriverName
.MaximumLength
= sizeof(NameBuffer
);
504 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
506 DPRINT("Driver name: '%wZ'\n", &DriverName
);
509 DriverName
.Length
= 0;
511 Status
= IopCreateDriver(
512 DriverName
.Length
> 0 ? &DriverName
: NULL
,
517 RtlFreeUnicodeString(&RegistryKey
);
519 *DriverObject
= Driver
;
520 if (!NT_SUCCESS(Status
))
522 DPRINT("IopCreateDriver() failed (Status 0x%08lx)\n", Status
);
526 MmFreeDriverInitialization((PLDR_DATA_TABLE_ENTRY
)Driver
->DriverSection
);
528 /* Set the driver as initialized */
529 IopReadyDeviceObjects(Driver
);
531 if (PnpSystemInit
) IopReinitializeDrivers();
533 return STATUS_SUCCESS
;
537 * IopAttachFilterDriversCallback
539 * Internal routine used by IopAttachFilterDrivers.
543 IopAttachFilterDriversCallback(
551 PDEVICE_NODE DeviceNode
= Context
;
552 UNICODE_STRING ServiceName
;
554 PLDR_DATA_TABLE_ENTRY ModuleObject
;
555 PDRIVER_OBJECT DriverObject
;
558 for (Filters
= ValueData
;
559 ((ULONG_PTR
)Filters
- (ULONG_PTR
)ValueData
) < ValueLength
&&
561 Filters
+= (ServiceName
.Length
/ sizeof(WCHAR
)) + 1)
563 DPRINT("Filter Driver: %S (%wZ)\n", Filters
, &DeviceNode
->InstancePath
);
565 ServiceName
.Buffer
= Filters
;
566 ServiceName
.MaximumLength
=
567 ServiceName
.Length
= (USHORT
)wcslen(Filters
) * sizeof(WCHAR
);
569 Status
= IopGetDriverObject(&DriverObject
,
572 if (!NT_SUCCESS(Status
))
574 /* Load and initialize the filter driver */
575 Status
= IopLoadServiceModule(&ServiceName
, &ModuleObject
);
576 if (!NT_SUCCESS(Status
))
579 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
, &ServiceName
,
580 FALSE
, &DriverObject
);
581 if (!NT_SUCCESS(Status
))
585 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
587 /* Remove extra reference */
588 ObDereferenceObject(DriverObject
);
591 return STATUS_SUCCESS
;
595 * IopAttachFilterDrivers
597 * Load filter drivers for specified device node.
601 * Set to TRUE for loading lower level filters or FALSE for upper
606 IopAttachFilterDrivers(
607 PDEVICE_NODE DeviceNode
,
610 RTL_QUERY_REGISTRY_TABLE QueryTable
[2] = { { NULL
, 0, NULL
, NULL
, 0, NULL
, 0 }, };
611 UNICODE_STRING Class
;
612 WCHAR ClassBuffer
[40];
613 UNICODE_STRING EnumRoot
= RTL_CONSTANT_STRING(ENUM_ROOT
);
614 HANDLE EnumRootKey
, SubKey
;
617 /* Open enumeration root key */
618 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
619 &EnumRoot
, KEY_READ
);
620 if (!NT_SUCCESS(Status
))
622 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
627 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
628 &DeviceNode
->InstancePath
, KEY_READ
);
629 if (!NT_SUCCESS(Status
))
631 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
632 ZwClose(EnumRootKey
);
637 * First load the device filters
639 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
641 QueryTable
[0].Name
= L
"LowerFilters";
643 QueryTable
[0].Name
= L
"UpperFilters";
644 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
646 RtlQueryRegistryValues(
654 * Now get the class GUID
657 Class
.MaximumLength
= 40 * sizeof(WCHAR
);
658 Class
.Buffer
= ClassBuffer
;
659 QueryTable
[0].QueryRoutine
= NULL
;
660 QueryTable
[0].Name
= L
"ClassGUID";
661 QueryTable
[0].EntryContext
= &Class
;
662 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
| RTL_QUERY_REGISTRY_DIRECT
;
664 Status
= RtlQueryRegistryValues(
673 ZwClose(EnumRootKey
);
676 * Load the class filter driver
678 if (NT_SUCCESS(Status
))
680 UNICODE_STRING ControlClass
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class");
682 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
683 &ControlClass
, KEY_READ
);
684 if (!NT_SUCCESS(Status
))
686 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
691 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
693 if (!NT_SUCCESS(Status
))
695 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
696 ZwClose(EnumRootKey
);
700 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
702 QueryTable
[0].Name
= L
"LowerFilters";
704 QueryTable
[0].Name
= L
"UpperFilters";
705 QueryTable
[0].EntryContext
= NULL
;
706 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
708 RtlQueryRegistryValues(
717 ZwClose(EnumRootKey
);
720 return STATUS_SUCCESS
;
725 MiResolveImageReferences(IN PVOID ImageBase
,
726 IN PUNICODE_STRING ImageFileDirectory
,
727 IN PUNICODE_STRING NamePrefix OPTIONAL
,
728 OUT PCHAR
*MissingApi
,
729 OUT PWCHAR
*MissingDriver
,
730 OUT PLOAD_IMPORTS
*LoadImports
);
733 // Used for images already loaded (boot drivers)
738 LdrProcessDriverModule(PLDR_DATA_TABLE_ENTRY LdrEntry
,
739 PUNICODE_STRING FileName
,
740 PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
743 UNICODE_STRING BaseName
, BaseDirectory
;
744 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
745 PCHAR MissingApiName
, Buffer
;
746 PWCHAR MissingDriverName
;
747 PVOID DriverBase
= LdrEntry
->DllBase
;
749 /* Allocate a buffer we'll use for names */
750 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
754 return STATUS_INSUFFICIENT_RESOURCES
;
757 /* Check for a separator */
758 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
763 /* Loop the path until we get to the base name */
764 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
765 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
768 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
769 BaseLength
*= sizeof(WCHAR
);
771 /* Setup the string */
772 BaseName
.Length
= (USHORT
)BaseLength
;
777 /* Otherwise, we already have a base name */
778 BaseName
.Length
= FileName
->Length
;
779 BaseName
.Buffer
= FileName
->Buffer
;
782 /* Setup the maximum length */
783 BaseName
.MaximumLength
= BaseName
.Length
;
785 /* Now compute the base directory */
786 BaseDirectory
= *FileName
;
787 BaseDirectory
.Length
-= BaseName
.Length
;
788 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
790 /* Resolve imports */
791 MissingApiName
= Buffer
;
792 Status
= MiResolveImageReferences(DriverBase
,
799 /* Free the temporary buffer */
800 ExFreePoolWithTag(Buffer
, TAG_LDR_WSTR
);
802 /* Check the result of the imports resolution */
803 if (!NT_SUCCESS(Status
)) return Status
;
806 *ModuleObject
= LdrEntry
;
807 return STATUS_SUCCESS
;
811 * IopInitializeBuiltinDriver
813 * Initialize a driver that is already loaded in memory.
819 IopInitializeBuiltinDriver(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
821 PDEVICE_NODE DeviceNode
;
822 PDRIVER_OBJECT DriverObject
;
824 PWCHAR FileNameWithoutPath
;
825 LPWSTR FileExtension
;
826 PUNICODE_STRING ModuleName
= &LdrEntry
->BaseDllName
;
827 UNICODE_STRING ServiceName
;
830 * Display 'Loading XXX...' message
832 IopDisplayLoadingMessage(ModuleName
);
833 InbvIndicateProgress();
836 * Generate filename without path (not needed by freeldr)
838 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
839 if (FileNameWithoutPath
== NULL
)
841 FileNameWithoutPath
= ModuleName
->Buffer
;
845 FileNameWithoutPath
++;
849 * Strip the file extension from ServiceName
851 RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
852 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
853 if (FileExtension
!= NULL
)
855 ServiceName
.Length
-= (USHORT
)wcslen(FileExtension
) * sizeof(WCHAR
);
856 FileExtension
[0] = 0;
860 * Determine the right device object
862 /* Use IopRootDeviceNode for now */
863 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
864 if (!NT_SUCCESS(Status
))
866 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
871 * Initialize the driver
873 Status
= IopInitializeDriverModule(DeviceNode
, LdrEntry
,
874 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
876 if (!NT_SUCCESS(Status
))
878 IopFreeDeviceNode(DeviceNode
);
882 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
883 if (NT_SUCCESS(Status
))
885 Status
= IopStartDevice(DeviceNode
);
888 /* Remove extra reference from IopInitializeDriverModule */
889 ObDereferenceObject(DriverObject
);
895 * IopInitializeBootDrivers
897 * Initialize boot drivers and free memory for boot files.
908 IopInitializeBootDrivers(VOID
)
910 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
911 PLDR_DATA_TABLE_ENTRY LdrEntry
;
912 PDEVICE_NODE DeviceNode
;
913 PDRIVER_OBJECT DriverObject
;
914 LDR_DATA_TABLE_ENTRY ModuleObject
;
916 UNICODE_STRING DriverName
;
918 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
920 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
921 DPRINT("IopInitializeBootDrivers()\n");
923 /* Use IopRootDeviceNode for now */
924 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
925 if (!NT_SUCCESS(Status
)) return;
927 /* Setup the module object for the RAW FS Driver */
928 ModuleObject
.DllBase
= NULL
;
929 ModuleObject
.SizeOfImage
= 0;
930 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
931 RtlInitUnicodeString(&DriverName
, L
"RAW");
934 Status
= IopInitializeDriverModule(DeviceNode
,
939 if (!NT_SUCCESS(Status
))
942 IopFreeDeviceNode(DeviceNode
);
946 /* Now initialize the associated device */
947 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
948 if (!NT_SUCCESS(Status
))
951 IopFreeDeviceNode(DeviceNode
);
952 ObDereferenceObject(DriverObject
);
957 Status
= IopStartDevice(DeviceNode
);
958 if (!NT_SUCCESS(Status
))
961 IopFreeDeviceNode(DeviceNode
);
962 ObDereferenceObject(DriverObject
);
966 /* Get highest group order index */
967 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
968 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
970 /* Allocate the group table */
971 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
972 IopGroupIndex
* sizeof(LIST_ENTRY
),
974 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
976 /* Initialize the group table lists */
977 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
979 /* Loop the boot modules */
980 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
981 NextEntry
= ListHead
->Flink
;
982 while (ListHead
!= NextEntry
)
985 LdrEntry
= CONTAINING_RECORD(NextEntry
,
986 LDR_DATA_TABLE_ENTRY
,
989 /* Check if the DLL needs to be initialized */
990 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
992 /* Call its entrypoint */
993 MmCallDllInitialize(LdrEntry
, NULL
);
996 /* Go to the next driver */
997 NextEntry
= NextEntry
->Flink
;
1000 /* Loop the boot drivers */
1001 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
1002 NextEntry
= ListHead
->Flink
;
1003 while (ListHead
!= NextEntry
)
1006 BootEntry
= CONTAINING_RECORD(NextEntry
,
1007 BOOT_DRIVER_LIST_ENTRY
,
1010 /* Get the driver loader entry */
1011 LdrEntry
= BootEntry
->LdrEntry
;
1013 /* Allocate our internal accounting structure */
1014 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
1015 sizeof(DRIVER_INFORMATION
),
1019 /* Zero it and initialize it */
1020 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1021 InitializeListHead(&DriverInfo
->Link
);
1022 DriverInfo
->DataTableEntry
= BootEntry
;
1024 /* Open the registry key */
1025 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1027 &BootEntry
->RegistryPath
,
1029 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1030 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1032 /* Save the handle */
1033 DriverInfo
->ServiceHandle
= KeyHandle
;
1035 /* Get the group oder index */
1036 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1038 /* Get the tag position */
1039 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1041 /* Insert it into the list, at the right place */
1042 ASSERT(Index
< IopGroupIndex
);
1043 NextEntry2
= IopGroupTable
[Index
].Flink
;
1044 while (NextEntry2
!= &IopGroupTable
[Index
])
1046 /* Get the driver info */
1047 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1051 /* Check if we found the right tag position */
1052 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1059 NextEntry2
= NextEntry2
->Flink
;
1062 /* Insert us right before the next entry */
1063 NextEntry2
= NextEntry2
->Blink
;
1064 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1068 /* Go to the next driver */
1069 NextEntry
= NextEntry
->Flink
;
1072 /* Loop each group index */
1073 for (i
= 0; i
< IopGroupIndex
; i
++)
1075 /* Loop each group table */
1076 NextEntry
= IopGroupTable
[i
].Flink
;
1077 while (NextEntry
!= &IopGroupTable
[i
])
1080 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1084 /* Get the driver loader entry */
1085 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1088 IopInitializeBuiltinDriver(LdrEntry
);
1091 NextEntry
= NextEntry
->Flink
;
1095 /* In old ROS, the loader list became empty after this point. Simulate. */
1096 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1102 IopInitializeSystemDrivers(VOID
)
1104 PUNICODE_STRING
*DriverList
, *SavedList
;
1106 /* No system drivers on the boot cd */
1107 if (KeLoaderBlock
->SetupLdrBlock
) return;
1109 /* Get the driver list */
1110 SavedList
= DriverList
= CmGetSystemDriverList();
1116 /* Load the driver */
1117 ZwLoadDriver(*DriverList
);
1119 /* Free the entry */
1120 RtlFreeUnicodeString(*DriverList
);
1121 ExFreePool(*DriverList
);
1124 InbvIndicateProgress();
1129 ExFreePool(SavedList
);
1135 * Unloads a device driver.
1139 * Name of the service to unload (registry key).
1142 * Whether to unload Plug & Plug or only legacy drivers. If this
1143 * parameter is set to FALSE, the routine will unload only legacy
1150 * Guard the whole function by SEH.
1154 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1156 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1157 UNICODE_STRING ImagePath
;
1158 UNICODE_STRING ServiceName
;
1159 UNICODE_STRING ObjectName
;
1160 PDRIVER_OBJECT DriverObject
;
1161 PDEVICE_OBJECT DeviceObject
;
1162 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1163 LOAD_UNLOAD_PARAMS LoadParams
;
1166 BOOLEAN SafeToUnload
= TRUE
;
1168 DPRINT("IopUnloadDriver('%wZ', %d)\n", DriverServiceName
, UnloadPnpDrivers
);
1173 * Get the service name from the registry key name
1176 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1178 Start
= DriverServiceName
->Buffer
;
1182 RtlInitUnicodeString(&ServiceName
, Start
);
1185 * Construct the driver object name
1188 ObjectName
.Length
= ((USHORT
)wcslen(Start
) + 8) * sizeof(WCHAR
);
1189 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1190 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1191 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1192 wcscpy(ObjectName
.Buffer
, L
"\\Driver\\");
1193 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1194 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1197 * Find the driver object
1199 Status
= ObReferenceObjectByName(&ObjectName
,
1206 (PVOID
*)&DriverObject
);
1208 if (!NT_SUCCESS(Status
))
1210 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1211 ExFreePool(ObjectName
.Buffer
);
1216 * Free the buffer for driver object name
1218 ExFreePool(ObjectName
.Buffer
);
1220 /* Check that driver is not already unloading */
1221 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1223 DPRINT1("Driver deletion pending\n");
1224 ObDereferenceObject(DriverObject
);
1225 return STATUS_DELETE_PENDING
;
1229 * Get path of service...
1232 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1234 RtlInitUnicodeString(&ImagePath
, NULL
);
1236 QueryTable
[0].Name
= L
"ImagePath";
1237 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1238 QueryTable
[0].EntryContext
= &ImagePath
;
1240 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1241 DriverServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1243 if (!NT_SUCCESS(Status
))
1245 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1246 ObDereferenceObject(DriverObject
);
1251 * Normalize the image path for all later processing.
1254 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1256 if (!NT_SUCCESS(Status
))
1258 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1259 ObDereferenceObject(DriverObject
);
1264 * Free the service path
1267 ExFreePool(ImagePath
.Buffer
);
1270 * Unload the module and release the references to the device object
1273 /* Call the load/unload routine, depending on current process */
1274 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
&&
1275 (UnloadPnpDrivers
|| (DriverObject
->Flags
& DRVO_LEGACY_DRIVER
)))
1277 /* Loop through each device object of the driver
1278 and set DOE_UNLOAD_PENDING flag */
1279 DeviceObject
= DriverObject
->DeviceObject
;
1280 while (DeviceObject
)
1282 /* Set the unload pending flag for the device */
1283 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1284 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1286 /* Make sure there are no attached devices or no reference counts */
1287 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1289 /* Not safe to unload */
1290 DPRINT1("Drivers device object is referenced or has attached devices\n");
1292 SafeToUnload
= FALSE
;
1295 DeviceObject
= DeviceObject
->NextDevice
;
1298 /* If not safe to unload, then return success */
1301 ObDereferenceObject(DriverObject
);
1302 return STATUS_SUCCESS
;
1305 DPRINT1("Unloading driver '%wZ' (manual)\n", &DriverObject
->DriverName
);
1307 /* Set the unload invoked flag */
1308 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1310 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
1312 /* Just call right away */
1313 (*DriverObject
->DriverUnload
)(DriverObject
);
1317 /* Load/Unload must be called from system process */
1319 /* Prepare parameters block */
1320 LoadParams
.DriverObject
= DriverObject
;
1321 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1323 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1324 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
1325 (PVOID
)&LoadParams
);
1328 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1330 /* And wait when it completes */
1331 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
1335 /* Mark the driver object temporary, so it could be deleted later */
1336 ObMakeTemporaryObject(DriverObject
);
1338 /* Dereference it 2 times */
1339 ObDereferenceObject(DriverObject
);
1340 ObDereferenceObject(DriverObject
);
1342 return STATUS_SUCCESS
;
1346 DPRINT1("No DriverUnload function! '%wZ' will not be unloaded!\n", &DriverObject
->DriverName
);
1348 /* Dereference one time (refd inside this function) */
1349 ObDereferenceObject(DriverObject
);
1351 /* Return unloading failure */
1352 return STATUS_INVALID_DEVICE_REQUEST
;
1358 IopReinitializeDrivers(VOID
)
1360 PDRIVER_REINIT_ITEM ReinitItem
;
1363 /* Get the first entry and start looping */
1364 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1365 &DriverReinitListLock
);
1369 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1371 /* Increment reinitialization counter */
1372 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1374 /* Remove the device object flag */
1375 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1377 /* Call the routine */
1378 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1379 ReinitItem
->Context
,
1380 ReinitItem
->DriverObject
->
1381 DriverExtension
->Count
);
1383 /* Free the entry */
1386 /* Move to the next one */
1387 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1388 &DriverReinitListLock
);
1394 IopReinitializeBootDrivers(VOID
)
1396 PDRIVER_REINIT_ITEM ReinitItem
;
1399 /* Get the first entry and start looping */
1400 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1401 &DriverBootReinitListLock
);
1405 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1407 /* Increment reinitialization counter */
1408 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1410 /* Remove the device object flag */
1411 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1413 /* Call the routine */
1414 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1415 ReinitItem
->Context
,
1416 ReinitItem
->DriverObject
->
1417 DriverExtension
->Count
);
1419 /* Free the entry */
1422 /* Move to the next one */
1423 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1424 &DriverBootReinitListLock
);
1430 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1431 IN PDRIVER_INITIALIZE InitializationFunction
,
1432 IN PUNICODE_STRING RegistryPath
,
1433 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1434 OUT PDRIVER_OBJECT
*pDriverObject
)
1436 WCHAR NameBuffer
[100];
1438 UNICODE_STRING LocalDriverName
;
1440 OBJECT_ATTRIBUTES ObjectAttributes
;
1442 PDRIVER_OBJECT DriverObject
;
1443 UNICODE_STRING ServiceKeyName
;
1445 ULONG i
, RetryCount
= 0;
1448 /* First, create a unique name for the driver if we don't have one */
1451 /* Create a random name and set up the string*/
1452 NameLength
= (USHORT
)swprintf(NameBuffer
,
1455 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1456 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1457 LocalDriverName
.Buffer
= NameBuffer
;
1461 /* So we can avoid another code path, use a local var */
1462 LocalDriverName
= *DriverName
;
1465 /* Initialize the Attributes */
1466 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1467 InitializeObjectAttributes(&ObjectAttributes
,
1469 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
,
1473 /* Create the Object */
1474 Status
= ObCreateObject(KernelMode
,
1482 (PVOID
*)&DriverObject
);
1483 if (!NT_SUCCESS(Status
)) return Status
;
1485 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1487 /* Set up the Object */
1488 RtlZeroMemory(DriverObject
, ObjectSize
);
1489 DriverObject
->Type
= IO_TYPE_DRIVER
;
1490 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1491 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;
1492 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1493 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1494 DriverObject
->DriverInit
= InitializationFunction
;
1495 DriverObject
->DriverSection
= ModuleObject
;
1496 /* Loop all Major Functions */
1497 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1499 /* Invalidate each function */
1500 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1503 /* Set up the service key name buffer */
1504 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1505 LocalDriverName
.Length
+
1508 if (!ServiceKeyName
.Buffer
)
1511 ObMakeTemporaryObject(DriverObject
);
1512 ObDereferenceObject(DriverObject
);
1513 return STATUS_INSUFFICIENT_RESOURCES
;
1516 /* Fill out the key data and copy the buffer */
1517 ServiceKeyName
.Length
= LocalDriverName
.Length
;
1518 ServiceKeyName
.MaximumLength
= LocalDriverName
.MaximumLength
;
1519 RtlCopyMemory(ServiceKeyName
.Buffer
,
1520 LocalDriverName
.Buffer
,
1521 LocalDriverName
.Length
);
1523 /* Null-terminate it and set it */
1524 ServiceKeyName
.Buffer
[ServiceKeyName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1525 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1527 /* Also store it in the Driver Object. This is a bit of a hack. */
1528 RtlCopyMemory(&DriverObject
->DriverName
,
1530 sizeof(UNICODE_STRING
));
1532 /* Add the Object and get its handle */
1533 Status
= ObInsertObject(DriverObject
,
1540 /* Eliminate small possibility when this function is called more than
1541 once in a row, and KeTickCount doesn't get enough time to change */
1542 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1548 if (!NT_SUCCESS(Status
)) return Status
;
1550 /* Now reference it */
1551 Status
= ObReferenceObjectByHandle(hDriver
,
1555 (PVOID
*)&DriverObject
,
1558 /* Close the extra handle */
1561 if (!NT_SUCCESS(Status
))
1564 ObMakeTemporaryObject(DriverObject
);
1565 ObDereferenceObject(DriverObject
);
1569 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1570 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1571 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1573 /* Finally, call its init function */
1574 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1575 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1576 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1577 if (!NT_SUCCESS(Status
))
1579 /* If it didn't work, then kill the object */
1580 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1581 DriverObject
->DriverSection
= NULL
;
1582 ObMakeTemporaryObject(DriverObject
);
1583 ObDereferenceObject(DriverObject
);
1588 /* Returns to caller the object */
1589 *pDriverObject
= DriverObject
;
1592 /* We're going to say if we don't have any DOs from DriverEntry, then we're not legacy.
1593 * Other parts of the I/O manager depend on this behavior */
1594 if (!DriverObject
->DeviceObject
) DriverObject
->Flags
&= ~DRVO_LEGACY_DRIVER
;
1596 /* Loop all Major Functions */
1597 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1600 * Make sure the driver didn't set any dispatch entry point to NULL!
1601 * Doing so is illegal; drivers shouldn't touch entry points they
1605 /* Check if it did so anyway */
1606 if (!DriverObject
->MajorFunction
[i
])
1608 /* Print a warning in the debug log */
1609 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%d] to NULL!\n",
1610 &DriverObject
->DriverName
, i
);
1613 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1617 /* Return the Status */
1621 /* PUBLIC FUNCTIONS ***********************************************************/
1628 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1629 IN PDRIVER_INITIALIZE InitializationFunction
)
1631 PDRIVER_OBJECT DriverObject
;
1632 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, NULL
, &DriverObject
);
1640 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1642 /* Simply dereference the Object */
1643 ObDereferenceObject(DriverObject
);
1651 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1652 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1655 PDRIVER_REINIT_ITEM ReinitItem
;
1657 /* Allocate the entry */
1658 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1659 sizeof(DRIVER_REINIT_ITEM
),
1661 if (!ReinitItem
) return;
1664 ReinitItem
->DriverObject
= DriverObject
;
1665 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1666 ReinitItem
->Context
= Context
;
1668 /* Set the Driver Object flag and insert the entry into the list */
1669 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1670 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1671 &ReinitItem
->ItemEntry
,
1672 &DriverBootReinitListLock
);
1680 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1681 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1684 PDRIVER_REINIT_ITEM ReinitItem
;
1686 /* Allocate the entry */
1687 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1688 sizeof(DRIVER_REINIT_ITEM
),
1690 if (!ReinitItem
) return;
1693 ReinitItem
->DriverObject
= DriverObject
;
1694 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1695 ReinitItem
->Context
= Context
;
1697 /* Set the Driver Object flag and insert the entry into the list */
1698 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1699 ExInterlockedInsertTailList(&DriverReinitListHead
,
1700 &ReinitItem
->ItemEntry
,
1701 &DriverReinitListLock
);
1709 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1710 IN PVOID ClientIdentificationAddress
,
1711 IN ULONG DriverObjectExtensionSize
,
1712 OUT PVOID
*DriverObjectExtension
)
1715 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1716 BOOLEAN Inserted
= FALSE
;
1718 /* Assume failure */
1719 *DriverObjectExtension
= NULL
;
1721 /* Allocate the extension */
1722 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1723 sizeof(IO_CLIENT_EXTENSION
) +
1724 DriverObjectExtensionSize
,
1725 TAG_DRIVER_EXTENSION
);
1726 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1728 /* Clear the extension for teh caller */
1729 RtlZeroMemory(NewDriverExtension
,
1730 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1733 OldIrql
= KeRaiseIrqlToDpcLevel();
1735 /* Fill out the extension */
1736 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1738 /* Loop the current extensions */
1739 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1740 ClientDriverExtension
;
1741 while (DriverExtensions
)
1743 /* Check if the identifier matches */
1744 if (DriverExtensions
->ClientIdentificationAddress
==
1745 ClientIdentificationAddress
)
1747 /* We have a collision, break out */
1751 /* Go to the next one */
1752 DriverExtensions
= DriverExtensions
->NextExtension
;
1755 /* Check if we didn't collide */
1756 if (!DriverExtensions
)
1758 /* Link this one in */
1759 NewDriverExtension
->NextExtension
=
1760 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1761 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1766 /* Release the lock */
1767 KeLowerIrql(OldIrql
);
1769 /* Check if insertion failed */
1772 /* Free the entry and fail */
1773 ExFreePoolWithTag(NewDriverExtension
, TAG_DRIVER_EXTENSION
);
1774 return STATUS_OBJECT_NAME_COLLISION
;
1777 /* Otherwise, return the pointer */
1778 *DriverObjectExtension
= NewDriverExtension
+ 1;
1779 return STATUS_SUCCESS
;
1787 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1788 IN PVOID ClientIdentificationAddress
)
1791 PIO_CLIENT_EXTENSION DriverExtensions
;
1794 OldIrql
= KeRaiseIrqlToDpcLevel();
1796 /* Loop the list until we find the right one */
1797 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1798 while (DriverExtensions
)
1800 /* Check for a match */
1801 if (DriverExtensions
->ClientIdentificationAddress
==
1802 ClientIdentificationAddress
)
1809 DriverExtensions
= DriverExtensions
->NextExtension
;
1813 KeLowerIrql(OldIrql
);
1815 /* Return nothing or the extension */
1816 if (!DriverExtensions
) return NULL
;
1817 return DriverExtensions
+ 1;
1821 IopLoadUnloadDriver(PLOAD_UNLOAD_PARAMS LoadParams
)
1823 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1824 UNICODE_STRING ImagePath
;
1825 UNICODE_STRING ServiceName
;
1828 PDEVICE_NODE DeviceNode
;
1829 PDRIVER_OBJECT DriverObject
;
1830 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1834 /* Check if it's an unload request */
1835 if (LoadParams
->DriverObject
)
1837 (*LoadParams
->DriverObject
->DriverUnload
)(LoadParams
->DriverObject
);
1839 /* Return success and signal the event */
1840 LoadParams
->Status
= STATUS_SUCCESS
;
1841 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1845 RtlInitUnicodeString(&ImagePath
, NULL
);
1848 * Get the service name from the registry key name.
1850 ASSERT(LoadParams
->ServiceName
->Length
>= sizeof(WCHAR
));
1852 ServiceName
= *LoadParams
->ServiceName
;
1853 cur
= LoadParams
->ServiceName
->Buffer
+
1854 (LoadParams
->ServiceName
->Length
/ sizeof(WCHAR
)) - 1;
1855 while (LoadParams
->ServiceName
->Buffer
!= cur
)
1859 ServiceName
.Buffer
= cur
+ 1;
1860 ServiceName
.Length
= LoadParams
->ServiceName
->Length
-
1861 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1862 (ULONG_PTR
)LoadParams
->ServiceName
->Buffer
);
1872 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1874 RtlInitUnicodeString(&ImagePath
, NULL
);
1876 QueryTable
[0].Name
= L
"Type";
1877 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1878 QueryTable
[0].EntryContext
= &Type
;
1880 QueryTable
[1].Name
= L
"ImagePath";
1881 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1882 QueryTable
[1].EntryContext
= &ImagePath
;
1884 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1885 LoadParams
->ServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1887 if (!NT_SUCCESS(Status
))
1889 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1890 if (ImagePath
.Buffer
)
1891 ExFreePool(ImagePath
.Buffer
);
1892 LoadParams
->Status
= Status
;
1893 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1898 * Normalize the image path for all later processing.
1901 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1903 if (!NT_SUCCESS(Status
))
1905 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1906 LoadParams
->Status
= Status
;
1907 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1911 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1912 DPRINT("Type: %lx\n", Type
);
1914 /* Get existing DriverObject pointer (in case the driver has
1915 already been loaded and initialized) */
1916 Status
= IopGetDriverObject(
1919 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1920 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
1922 if (!NT_SUCCESS(Status
))
1925 * Load the driver module
1928 DPRINT("Loading module from %wZ\n", &ImagePath
);
1929 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
1931 if (!NT_SUCCESS(Status
))
1933 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
1934 LoadParams
->Status
= Status
;
1935 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1940 * Initialize the driver module if it's loaded for the first time
1942 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
1943 if (!NT_SUCCESS(Status
))
1945 DPRINT1("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
1946 MmUnloadSystemImage(ModuleObject
);
1947 LoadParams
->Status
= Status
;
1948 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1952 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
1954 Status
= IopInitializeDriverModule(DeviceNode
,
1956 &DeviceNode
->ServiceName
,
1957 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1958 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
1960 if (!NT_SUCCESS(Status
))
1962 DPRINT1("IopInitializeDriver() failed (Status %lx)\n", Status
);
1963 MmUnloadSystemImage(ModuleObject
);
1964 IopFreeDeviceNode(DeviceNode
);
1965 LoadParams
->Status
= Status
;
1966 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1970 /* Initialize and start device */
1971 IopInitializeDevice(DeviceNode
, DriverObject
);
1972 Status
= IopStartDevice(DeviceNode
);
1976 DPRINT("DriverObject already exist in ObjectManager\n");
1977 Status
= STATUS_IMAGE_ALREADY_LOADED
;
1979 /* IopGetDriverObject references the DriverObject, so dereference it */
1980 ObDereferenceObject(DriverObject
);
1983 /* Pass status to the caller and signal the event */
1984 LoadParams
->Status
= Status
;
1985 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1991 * Loads a device driver.
1995 * Name of the service to load (registry key).
2004 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
2006 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
2007 KPROCESSOR_MODE PreviousMode
;
2008 LOAD_UNLOAD_PARAMS LoadParams
;
2013 PreviousMode
= KeGetPreviousMode();
2016 * Check security privileges
2019 /* FIXME: Uncomment when privileges will be correctly implemented. */
2021 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
2023 DPRINT("Privilege not held\n");
2024 return STATUS_PRIVILEGE_NOT_HELD
;
2028 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2031 if (!NT_SUCCESS(Status
))
2036 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2038 LoadParams
.ServiceName
= &CapturedDriverServiceName
;
2039 LoadParams
.DriverObject
= NULL
;
2040 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
2042 /* Call the load/unload routine, depending on current process */
2043 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
2045 /* Just call right away */
2046 IopLoadUnloadDriver(&LoadParams
);
2050 /* Load/Unload must be called from system process */
2051 ExInitializeWorkItem(&LoadParams
.WorkItem
,
2052 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
2053 (PVOID
)&LoadParams
);
2056 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
2058 /* And wait when it completes */
2059 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
2063 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2066 return LoadParams
.Status
;
2072 * Unloads a legacy device driver.
2076 * Name of the service to unload (registry key).
2086 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2088 return IopUnloadDriver(DriverServiceName
, FALSE
);