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 /* Get the extension and loop them */
62 DriverExtension
= IoGetDrvObjExtension(DriverObject
)->
63 ClientDriverExtension
;
64 while (DriverExtension
)
66 /* Get the next one */
67 NextDriverExtension
= DriverExtension
->NextExtension
;
68 ExFreePoolWithTag(DriverExtension
, TAG_DRIVER_EXTENSION
);
71 DriverExtension
= NextDriverExtension
;
74 /* Check if the driver image is still loaded */
75 if (DriverObject
->DriverSection
)
78 MmUnloadSystemImage(DriverObject
->DriverSection
);
81 /* Check if it has a name */
82 if (DriverObject
->DriverName
.Buffer
)
85 ExFreePool(DriverObject
->DriverName
.Buffer
);
88 #if 0 /* See a bit of hack in IopCreateDriver */
89 /* Check if it has a service key name */
90 if (DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
)
93 ExFreePool(DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
);
100 PDRIVER_OBJECT
*DriverObject
,
101 PUNICODE_STRING ServiceName
,
104 PDRIVER_OBJECT Object
;
105 WCHAR NameBuffer
[MAX_PATH
];
106 UNICODE_STRING DriverName
;
109 DPRINT("IopGetDriverObject(%p '%wZ' %x)\n",
110 DriverObject
, ServiceName
, FileSystem
);
112 *DriverObject
= NULL
;
114 /* Create ModuleName string */
115 if (ServiceName
== NULL
|| ServiceName
->Buffer
== NULL
)
116 /* We don't know which DriverObject we have to open */
117 return STATUS_INVALID_PARAMETER_2
;
119 DriverName
.Buffer
= NameBuffer
;
120 DriverName
.Length
= 0;
121 DriverName
.MaximumLength
= sizeof(NameBuffer
);
123 if (FileSystem
== TRUE
)
124 RtlAppendUnicodeToString(&DriverName
, FILESYSTEM_ROOT_NAME
);
126 RtlAppendUnicodeToString(&DriverName
, DRIVER_ROOT_NAME
);
127 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
129 DPRINT("Driver name: '%wZ'\n", &DriverName
);
131 /* Open driver object */
132 Status
= ObReferenceObjectByName(
134 OBJ_OPENIF
| OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, /* Attributes */
135 NULL
, /* PassedAccessState */
136 0, /* DesiredAccess */
139 NULL
, /* ParseContext */
142 if (!NT_SUCCESS(Status
))
144 DPRINT("Failed to reference driver object, status=0x%08x\n", Status
);
148 *DriverObject
= Object
;
150 DPRINT("Driver Object: %p\n", Object
);
152 return STATUS_SUCCESS
;
157 * TRUE if String2 contains String1 as a suffix.
161 IopSuffixUnicodeString(
162 IN PCUNICODE_STRING String1
,
163 IN PCUNICODE_STRING String2
)
169 if (String2
->Length
< String1
->Length
)
172 Length
= String1
->Length
/ 2;
173 pc1
= String1
->Buffer
;
174 pc2
= &String2
->Buffer
[String2
->Length
/ sizeof(WCHAR
) - Length
];
180 if( *pc1
++ != *pc2
++ )
189 * IopDisplayLoadingMessage
191 * Display 'Loading XXX...' message.
197 IopDisplayLoadingMessage(PUNICODE_STRING ServiceName
)
199 CHAR TextBuffer
[256];
200 UNICODE_STRING DotSys
= RTL_CONSTANT_STRING(L
".SYS");
202 if (ExpInTextModeSetup
) return;
203 if (!KeLoaderBlock
) return;
204 RtlUpcaseUnicodeString(ServiceName
, ServiceName
, FALSE
);
205 snprintf(TextBuffer
, sizeof(TextBuffer
),
206 "%s%sSystem32\\Drivers\\%wZ%s\n",
207 KeLoaderBlock
->ArcBootDeviceName
,
208 KeLoaderBlock
->NtBootPathName
,
210 IopSuffixUnicodeString(&DotSys
, ServiceName
) ? "" : ".SYS");
211 HalDisplayString(TextBuffer
);
215 * IopNormalizeImagePath
217 * Normalize an image path to contain complete path.
221 * The input path and on exit the result path. ImagePath.Buffer
222 * must be allocated by ExAllocatePool on input. Caller is responsible
223 * for freeing the buffer when it's no longer needed.
226 * Name of the service that ImagePath belongs to.
232 * The input image path isn't freed on error.
236 IopNormalizeImagePath(
237 IN OUT PUNICODE_STRING ImagePath
,
238 IN PUNICODE_STRING ServiceName
)
240 UNICODE_STRING InputImagePath
;
245 sizeof(UNICODE_STRING
));
247 if (InputImagePath
.Length
== 0)
249 ImagePath
->Length
= 0;
250 ImagePath
->MaximumLength
=
251 (33 * sizeof(WCHAR
)) + ServiceName
->Length
+ sizeof(UNICODE_NULL
);
252 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
253 if (ImagePath
->Buffer
== NULL
)
254 return STATUS_NO_MEMORY
;
256 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\system32\\drivers\\");
257 RtlAppendUnicodeStringToString(ImagePath
, ServiceName
);
258 RtlAppendUnicodeToString(ImagePath
, L
".sys");
260 if (InputImagePath
.Buffer
[0] != L
'\\')
262 ImagePath
->Length
= 0;
263 ImagePath
->MaximumLength
=
264 12 * sizeof(WCHAR
) + InputImagePath
.Length
+ sizeof(UNICODE_NULL
);
265 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
266 if (ImagePath
->Buffer
== NULL
)
267 return STATUS_NO_MEMORY
;
269 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\");
270 RtlAppendUnicodeStringToString(ImagePath
, &InputImagePath
);
272 /* Free caller's string */
273 ExFreePoolWithTag(InputImagePath
.Buffer
, TAG_RTLREGISTRY
);
276 return STATUS_SUCCESS
;
280 * IopLoadServiceModule
282 * Load a module specified by registry settings for service.
286 * Name of the service to load.
293 IopLoadServiceModule(
294 IN PUNICODE_STRING ServiceName
,
295 OUT PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
297 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
299 UNICODE_STRING ServiceImagePath
, CCSName
;
301 HANDLE CCSKey
, ServiceKey
;
304 DPRINT("IopLoadServiceModule(%wZ, 0x%p)\n", ServiceName
, ModuleObject
);
306 /* FIXME: This check may be removed once the bug is fixed */
307 if (ServiceName
->Buffer
== NULL
)
309 DPRINT1("If you see this, please report to Fireball or hpoussin!\n");
310 return STATUS_UNSUCCESSFUL
;
313 /* Open CurrentControlSet */
314 RtlInitUnicodeString(&CCSName
,
315 L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services");
316 Status
= IopOpenRegistryKeyEx(&CCSKey
, NULL
, &CCSName
, KEY_READ
);
317 if (!NT_SUCCESS(Status
))
319 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
323 /* Open service key */
324 Status
= IopOpenRegistryKeyEx(&ServiceKey
, CCSKey
, ServiceName
, KEY_READ
);
325 if (!NT_SUCCESS(Status
))
327 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
333 * Get information about the service.
336 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
338 RtlInitUnicodeString(&ServiceImagePath
, NULL
);
340 QueryTable
[0].Name
= L
"Start";
341 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
342 QueryTable
[0].EntryContext
= &ServiceStart
;
344 QueryTable
[1].Name
= L
"ImagePath";
345 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
346 QueryTable
[1].EntryContext
= &ServiceImagePath
;
348 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
349 (PWSTR
)ServiceKey
, QueryTable
, NULL
, NULL
);
354 if (!NT_SUCCESS(Status
))
356 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
361 * Normalize the image path for all later processing.
364 Status
= IopNormalizeImagePath(&ServiceImagePath
, ServiceName
);
366 if (!NT_SUCCESS(Status
))
368 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
373 * Case for disabled drivers
376 if (ServiceStart
>= 4)
378 /* FIXME: Check if it is the right status code */
379 Status
= STATUS_PLUGPLAY_NO_DEVICE
;
383 DPRINT("Loading module\n");
384 Status
= MmLoadSystemImage(&ServiceImagePath
, NULL
, NULL
, 0, (PVOID
)ModuleObject
, &BaseAddress
);
387 ExFreePool(ServiceImagePath
.Buffer
);
390 * Now check if the module was loaded successfully.
393 if (!NT_SUCCESS(Status
))
395 DPRINT("Module loading failed (Status %x)\n", Status
);
398 DPRINT("Module loading (Status %x)\n", Status
);
404 * IopInitializeDriverModule
406 * Initalize a loaded driver.
410 * Pointer to device node.
413 * Module object representing the driver. It can be retrieve by
414 * IopLoadServiceModule.
417 * Name of the service (as in registry).
420 * Set to TRUE for file system drivers.
423 * On successful return this contains the driver object representing
428 IopInitializeDriverModule(
429 IN PDEVICE_NODE DeviceNode
,
430 IN PLDR_DATA_TABLE_ENTRY ModuleObject
,
431 IN PUNICODE_STRING ServiceName
,
432 IN BOOLEAN FileSystemDriver
,
433 OUT PDRIVER_OBJECT
*DriverObject
)
435 const WCHAR ServicesKeyName
[] = L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";
436 WCHAR NameBuffer
[MAX_PATH
];
437 UNICODE_STRING DriverName
;
438 UNICODE_STRING RegistryKey
;
439 PDRIVER_INITIALIZE DriverEntry
;
440 PDRIVER_OBJECT Driver
;
443 DriverEntry
= ModuleObject
->EntryPoint
;
445 if (ServiceName
!= NULL
&& ServiceName
->Length
!= 0)
447 RegistryKey
.Length
= 0;
448 RegistryKey
.MaximumLength
= sizeof(ServicesKeyName
) + ServiceName
->Length
;
449 RegistryKey
.Buffer
= ExAllocatePool(PagedPool
, RegistryKey
.MaximumLength
);
450 if (RegistryKey
.Buffer
== NULL
)
452 return STATUS_INSUFFICIENT_RESOURCES
;
454 RtlAppendUnicodeToString(&RegistryKey
, ServicesKeyName
);
455 RtlAppendUnicodeStringToString(&RegistryKey
, ServiceName
);
459 RtlInitUnicodeString(&RegistryKey
, NULL
);
462 /* Create ModuleName string */
463 if (ServiceName
&& ServiceName
->Length
> 0)
465 if (FileSystemDriver
== TRUE
)
466 wcscpy(NameBuffer
, FILESYSTEM_ROOT_NAME
);
468 wcscpy(NameBuffer
, DRIVER_ROOT_NAME
);
470 RtlInitUnicodeString(&DriverName
, NameBuffer
);
471 DriverName
.MaximumLength
= sizeof(NameBuffer
);
473 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
475 DPRINT("Driver name: '%wZ'\n", &DriverName
);
478 DriverName
.Length
= 0;
480 Status
= IopCreateDriver(
481 DriverName
.Length
> 0 ? &DriverName
: NULL
,
486 RtlFreeUnicodeString(&RegistryKey
);
488 *DriverObject
= Driver
;
489 if (!NT_SUCCESS(Status
))
491 DPRINT("IopCreateDriver() failed (Status 0x%08lx)\n", Status
);
495 /* Set the driver as initialized */
496 IopReadyDeviceObjects(Driver
);
498 if (PnpSystemInit
) IopReinitializeDrivers();
500 return STATUS_SUCCESS
;
504 * IopAttachFilterDriversCallback
506 * Internal routine used by IopAttachFilterDrivers.
510 IopAttachFilterDriversCallback(
518 PDEVICE_NODE DeviceNode
= Context
;
519 UNICODE_STRING ServiceName
;
521 PLDR_DATA_TABLE_ENTRY ModuleObject
;
522 PDRIVER_OBJECT DriverObject
;
525 for (Filters
= ValueData
;
526 ((ULONG_PTR
)Filters
- (ULONG_PTR
)ValueData
) < ValueLength
&&
528 Filters
+= (ServiceName
.Length
/ sizeof(WCHAR
)) + 1)
530 DPRINT("Filter Driver: %S (%wZ)\n", Filters
, &DeviceNode
->InstancePath
);
531 ServiceName
.Buffer
= Filters
;
532 ServiceName
.MaximumLength
=
533 ServiceName
.Length
= wcslen(Filters
) * sizeof(WCHAR
);
535 /* Load and initialize the filter driver */
536 Status
= IopLoadServiceModule(&ServiceName
, &ModuleObject
);
537 if (Status
!= STATUS_IMAGE_ALREADY_LOADED
)
539 if (!NT_SUCCESS(Status
))
542 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
, &ServiceName
,
543 FALSE
, &DriverObject
);
544 if (!NT_SUCCESS(Status
))
549 /* get existing DriverObject pointer */
550 Status
= IopGetDriverObject(
554 if (!NT_SUCCESS(Status
))
556 DPRINT1("IopGetDriverObject() returned status 0x%08x!\n", Status
);
561 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
562 if (!NT_SUCCESS(Status
))
566 return STATUS_SUCCESS
;
570 * IopAttachFilterDrivers
572 * Load filter drivers for specified device node.
576 * Set to TRUE for loading lower level filters or FALSE for upper
581 IopAttachFilterDrivers(
582 PDEVICE_NODE DeviceNode
,
585 RTL_QUERY_REGISTRY_TABLE QueryTable
[2] = { { NULL
, 0, NULL
, NULL
, 0, NULL
, 0 }, };
586 UNICODE_STRING Class
;
587 WCHAR ClassBuffer
[40];
588 UNICODE_STRING EnumRoot
= RTL_CONSTANT_STRING(ENUM_ROOT
);
589 HANDLE EnumRootKey
, SubKey
;
592 /* Open enumeration root key */
593 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
594 &EnumRoot
, KEY_READ
);
595 if (!NT_SUCCESS(Status
))
597 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
602 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
603 &DeviceNode
->InstancePath
, KEY_READ
);
604 if (!NT_SUCCESS(Status
))
606 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
607 ZwClose(EnumRootKey
);
612 * First load the device filters
614 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
616 QueryTable
[0].Name
= L
"LowerFilters";
618 QueryTable
[0].Name
= L
"UpperFilters";
619 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
621 RtlQueryRegistryValues(
629 * Now get the class GUID
632 Class
.MaximumLength
= 40 * sizeof(WCHAR
);
633 Class
.Buffer
= ClassBuffer
;
634 QueryTable
[0].QueryRoutine
= NULL
;
635 QueryTable
[0].Name
= L
"ClassGUID";
636 QueryTable
[0].EntryContext
= &Class
;
637 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
| RTL_QUERY_REGISTRY_DIRECT
;
639 Status
= RtlQueryRegistryValues(
648 ZwClose(EnumRootKey
);
651 * Load the class filter driver
653 if (NT_SUCCESS(Status
))
655 UNICODE_STRING ControlClass
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class");
657 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
658 &ControlClass
, KEY_READ
);
659 if (!NT_SUCCESS(Status
))
661 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
666 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
668 if (!NT_SUCCESS(Status
))
670 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
671 ZwClose(EnumRootKey
);
675 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
677 QueryTable
[0].Name
= L
"LowerFilters";
679 QueryTable
[0].Name
= L
"UpperFilters";
680 QueryTable
[0].EntryContext
= NULL
;
681 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
683 RtlQueryRegistryValues(
692 ZwClose(EnumRootKey
);
695 return STATUS_SUCCESS
;
700 MiResolveImageReferences(IN PVOID ImageBase
,
701 IN PUNICODE_STRING ImageFileDirectory
,
702 IN PUNICODE_STRING NamePrefix OPTIONAL
,
703 OUT PCHAR
*MissingApi
,
704 OUT PWCHAR
*MissingDriver
,
705 OUT PLOAD_IMPORTS
*LoadImports
);
708 // Used for images already loaded (boot drivers)
713 LdrProcessDriverModule(PLDR_DATA_TABLE_ENTRY LdrEntry
,
714 PUNICODE_STRING FileName
,
715 PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
718 UNICODE_STRING BaseName
, BaseDirectory
;
719 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
720 PCHAR MissingApiName
, Buffer
;
721 PWCHAR MissingDriverName
;
722 PVOID DriverBase
= LdrEntry
->DllBase
;
724 /* Allocate a buffer we'll use for names */
725 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
729 return STATUS_INSUFFICIENT_RESOURCES
;
732 /* Check for a separator */
733 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
738 /* Loop the path until we get to the base name */
739 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
740 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
743 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
744 BaseLength
*= sizeof(WCHAR
);
746 /* Setup the string */
747 BaseName
.Length
= (USHORT
)BaseLength
;
752 /* Otherwise, we already have a base name */
753 BaseName
.Length
= FileName
->Length
;
754 BaseName
.Buffer
= FileName
->Buffer
;
757 /* Setup the maximum length */
758 BaseName
.MaximumLength
= BaseName
.Length
;
760 /* Now compute the base directory */
761 BaseDirectory
= *FileName
;
762 BaseDirectory
.Length
-= BaseName
.Length
;
763 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
765 /* Resolve imports */
766 MissingApiName
= Buffer
;
767 Status
= MiResolveImageReferences(DriverBase
,
773 if (!NT_SUCCESS(Status
)) return Status
;
776 *ModuleObject
= LdrEntry
;
777 return STATUS_SUCCESS
;
781 * IopInitializeBuiltinDriver
783 * Initialize a driver that is already loaded in memory.
789 IopInitializeBuiltinDriver(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
791 PDEVICE_NODE DeviceNode
;
792 PDRIVER_OBJECT DriverObject
;
794 PWCHAR FileNameWithoutPath
;
795 LPWSTR FileExtension
;
796 PUNICODE_STRING ModuleName
= &LdrEntry
->BaseDllName
;
797 UNICODE_STRING ServiceName
;
800 * Display 'Loading XXX...' message
802 IopDisplayLoadingMessage(ModuleName
);
803 InbvIndicateProgress();
806 * Generate filename without path (not needed by freeldr)
808 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
809 if (FileNameWithoutPath
== NULL
)
811 FileNameWithoutPath
= ModuleName
->Buffer
;
815 FileNameWithoutPath
++;
819 * Strip the file extension from ServiceName
821 RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
822 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
823 if (FileExtension
!= NULL
)
825 ServiceName
.Length
-= wcslen(FileExtension
) * sizeof(WCHAR
);
826 FileExtension
[0] = 0;
830 * Determine the right device object
832 /* Use IopRootDeviceNode for now */
833 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
834 if (!NT_SUCCESS(Status
))
836 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
839 DeviceNode
->ServiceName
= ServiceName
;
842 * Initialize the driver
844 Status
= IopInitializeDriverModule(DeviceNode
, LdrEntry
,
845 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
847 if (!NT_SUCCESS(Status
))
849 IopFreeDeviceNode(DeviceNode
);
853 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
854 if (NT_SUCCESS(Status
))
856 Status
= IopStartDevice(DeviceNode
);
863 * IopInitializeBootDrivers
865 * Initialize boot drivers and free memory for boot files.
876 IopInitializeBootDrivers(VOID
)
878 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
879 PLDR_DATA_TABLE_ENTRY LdrEntry
;
880 PDEVICE_NODE DeviceNode
;
881 PDRIVER_OBJECT DriverObject
;
882 LDR_DATA_TABLE_ENTRY ModuleObject
;
884 UNICODE_STRING DriverName
;
886 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
888 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
889 DPRINT("IopInitializeBootDrivers()\n");
891 /* Use IopRootDeviceNode for now */
892 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
893 if (!NT_SUCCESS(Status
)) return;
895 /* Setup the module object for the RAW FS Driver */
896 ModuleObject
.DllBase
= NULL
;
897 ModuleObject
.SizeOfImage
= 0;
898 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
899 RtlInitUnicodeString(&DriverName
, L
"RAW");
902 Status
= IopInitializeDriverModule(DeviceNode
,
907 if (!NT_SUCCESS(Status
))
910 IopFreeDeviceNode(DeviceNode
);
914 /* Now initialize the associated device */
915 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
916 if (!NT_SUCCESS(Status
))
919 IopFreeDeviceNode(DeviceNode
);
924 Status
= IopStartDevice(DeviceNode
);
925 if (!NT_SUCCESS(Status
))
928 IopFreeDeviceNode(DeviceNode
);
932 /* Get highest group order index */
933 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
934 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
936 /* Allocate the group table */
937 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
938 IopGroupIndex
* sizeof(LIST_ENTRY
),
940 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
942 /* Initialize the group table lists */
943 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
945 /* Loop the boot modules */
946 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
947 NextEntry
= ListHead
->Flink
;
948 while (ListHead
!= NextEntry
)
951 LdrEntry
= CONTAINING_RECORD(NextEntry
,
952 LDR_DATA_TABLE_ENTRY
,
955 /* Check if the DLL needs to be initialized */
956 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
958 /* Call its entrypoint */
959 MmCallDllInitialize(LdrEntry
, NULL
);
962 /* Go to the next driver */
963 NextEntry
= NextEntry
->Flink
;
966 /* Loop the boot drivers */
967 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
968 NextEntry
= ListHead
->Flink
;
969 while (ListHead
!= NextEntry
)
972 BootEntry
= CONTAINING_RECORD(NextEntry
,
973 BOOT_DRIVER_LIST_ENTRY
,
976 /* Get the driver loader entry */
977 LdrEntry
= BootEntry
->LdrEntry
;
979 /* Allocate our internal accounting structure */
980 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
981 sizeof(DRIVER_INFORMATION
),
985 /* Zero it and initialize it */
986 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
987 InitializeListHead(&DriverInfo
->Link
);
988 DriverInfo
->DataTableEntry
= BootEntry
;
990 /* Open the registry key */
991 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
993 &BootEntry
->RegistryPath
,
995 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
996 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1))))
998 /* Save the handle */
999 DriverInfo
->ServiceHandle
= KeyHandle
;
1001 /* Get the group oder index */
1002 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1004 /* Get the tag position */
1005 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1007 /* Insert it into the list, at the right place */
1008 ASSERT(Index
< IopGroupIndex
);
1009 NextEntry2
= IopGroupTable
[Index
].Flink
;
1010 while (NextEntry2
!= &IopGroupTable
[Index
])
1012 /* Get the driver info */
1013 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1017 /* Check if we found the right tag position */
1018 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1025 NextEntry2
= NextEntry2
->Flink
;
1028 /* Insert us right before the next entry */
1029 NextEntry2
= NextEntry2
->Blink
;
1030 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1034 /* Go to the next driver */
1035 NextEntry
= NextEntry
->Flink
;
1038 /* Loop each group index */
1039 for (i
= 0; i
< IopGroupIndex
; i
++)
1041 /* Loop each group table */
1042 NextEntry
= IopGroupTable
[i
].Flink
;
1043 while (NextEntry
!= &IopGroupTable
[i
])
1046 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1050 /* Get the driver loader entry */
1051 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1054 IopInitializeBuiltinDriver(LdrEntry
);
1057 NextEntry
= NextEntry
->Flink
;
1061 /* In old ROS, the loader list became empty after this point. Simulate. */
1062 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1068 IopInitializeSystemDrivers(VOID
)
1070 PUNICODE_STRING
*DriverList
, *SavedList
;
1072 /* No system drivers on the boot cd */
1073 if (KeLoaderBlock
->SetupLdrBlock
) return;
1075 /* Get the driver list */
1076 SavedList
= DriverList
= CmGetSystemDriverList();
1082 /* Load the driver */
1083 ZwLoadDriver(*DriverList
);
1085 /* Free the entry */
1086 RtlFreeUnicodeString(*DriverList
);
1087 ExFreePool(*DriverList
);
1090 InbvIndicateProgress();
1095 ExFreePool(SavedList
);
1101 * Unloads a device driver.
1105 * Name of the service to unload (registry key).
1108 * Whether to unload Plug & Plug or only legacy drivers. If this
1109 * parameter is set to FALSE, the routine will unload only legacy
1116 * Guard the whole function by SEH.
1120 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1122 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1123 UNICODE_STRING ImagePath
;
1124 UNICODE_STRING ServiceName
;
1125 UNICODE_STRING ObjectName
;
1126 PDRIVER_OBJECT DriverObject
;
1127 PDEVICE_OBJECT DeviceObject
;
1128 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1129 LOAD_UNLOAD_PARAMS LoadParams
;
1132 BOOLEAN SafeToUnload
= TRUE
;
1134 DPRINT("IopUnloadDriver('%wZ', %d)\n", DriverServiceName
, UnloadPnpDrivers
);
1139 * Get the service name from the registry key name
1142 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1144 Start
= DriverServiceName
->Buffer
;
1148 RtlInitUnicodeString(&ServiceName
, Start
);
1151 * Construct the driver object name
1154 ObjectName
.Length
= (wcslen(Start
) + 8) * sizeof(WCHAR
);
1155 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1156 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1157 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1158 wcscpy(ObjectName
.Buffer
, L
"\\Driver\\");
1159 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1160 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1163 * Find the driver object
1165 Status
= ObReferenceObjectByName(&ObjectName
,
1172 (PVOID
*)&DriverObject
);
1174 if (!NT_SUCCESS(Status
))
1176 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1177 ExFreePool(ObjectName
.Buffer
);
1182 * Free the buffer for driver object name
1184 ExFreePool(ObjectName
.Buffer
);
1186 /* Check that driver is not already unloading */
1187 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1189 DPRINT1("Driver deletion pending\n");
1190 ObDereferenceObject(DriverObject
);
1191 return STATUS_DELETE_PENDING
;
1195 * Get path of service...
1198 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1200 RtlInitUnicodeString(&ImagePath
, NULL
);
1202 QueryTable
[0].Name
= L
"ImagePath";
1203 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1204 QueryTable
[0].EntryContext
= &ImagePath
;
1206 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1207 DriverServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1209 if (!NT_SUCCESS(Status
))
1211 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1212 ObDereferenceObject(DriverObject
);
1217 * Normalize the image path for all later processing.
1220 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1222 if (!NT_SUCCESS(Status
))
1224 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1225 ObDereferenceObject(DriverObject
);
1230 * Free the service path
1233 ExFreePool(ImagePath
.Buffer
);
1236 * Unload the module and release the references to the device object
1239 /* Call the load/unload routine, depending on current process */
1240 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
)
1242 /* Loop through each device object of the driver
1243 and set DOE_UNLOAD_PENDING flag */
1244 DeviceObject
= DriverObject
->DeviceObject
;
1245 while (DeviceObject
)
1247 /* Set the unload pending flag for the device */
1248 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1249 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1251 /* Make sure there are no attached devices or no reference counts */
1252 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1254 /* Not safe to unload */
1255 DPRINT1("Drivers device object is referenced or has attached devices\n");
1257 SafeToUnload
= FALSE
;
1260 DeviceObject
= DeviceObject
->NextDevice
;
1263 /* If not safe to unload, then return success */
1266 ObDereferenceObject(DriverObject
);
1267 return STATUS_SUCCESS
;
1270 /* Set the unload invoked flag */
1271 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1273 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
1275 /* Just call right away */
1276 (*DriverObject
->DriverUnload
)(DriverObject
);
1280 /* Load/Unload must be called from system process */
1282 /* Prepare parameters block */
1283 LoadParams
.DriverObject
= DriverObject
;
1284 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1286 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1287 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
1288 (PVOID
)&LoadParams
);
1291 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1293 /* And wait when it completes */
1294 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
1298 /* Mark the driver object temporary, so it could be deleted later */
1299 ObMakeTemporaryObject(DriverObject
);
1301 /* Dereference it 2 times */
1302 ObDereferenceObject(DriverObject
);
1303 ObDereferenceObject(DriverObject
);
1305 return STATUS_SUCCESS
;
1309 /* Dereference one time (refd inside this function) */
1310 ObDereferenceObject(DriverObject
);
1312 /* Return unloading failure */
1313 return STATUS_INVALID_DEVICE_REQUEST
;
1319 IopReinitializeDrivers(VOID
)
1321 PDRIVER_REINIT_ITEM ReinitItem
;
1324 /* Get the first entry and start looping */
1325 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1326 &DriverReinitListLock
);
1330 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1332 /* Increment reinitialization counter */
1333 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1335 /* Remove the device object flag */
1336 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1338 /* Call the routine */
1339 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1340 ReinitItem
->Context
,
1341 ReinitItem
->DriverObject
->
1342 DriverExtension
->Count
);
1344 /* Free the entry */
1347 /* Move to the next one */
1348 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1349 &DriverReinitListLock
);
1355 IopReinitializeBootDrivers(VOID
)
1357 PDRIVER_REINIT_ITEM ReinitItem
;
1360 /* Get the first entry and start looping */
1361 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1362 &DriverBootReinitListLock
);
1366 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1368 /* Increment reinitialization counter */
1369 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1371 /* Remove the device object flag */
1372 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1374 /* Call the routine */
1375 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1376 ReinitItem
->Context
,
1377 ReinitItem
->DriverObject
->
1378 DriverExtension
->Count
);
1380 /* Free the entry */
1383 /* Move to the next one */
1384 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1385 &DriverBootReinitListLock
);
1391 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1392 IN PDRIVER_INITIALIZE InitializationFunction
,
1393 IN PUNICODE_STRING RegistryPath
,
1394 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1395 OUT PDRIVER_OBJECT
*pDriverObject
)
1397 WCHAR NameBuffer
[100];
1399 UNICODE_STRING LocalDriverName
;
1401 OBJECT_ATTRIBUTES ObjectAttributes
;
1403 PDRIVER_OBJECT DriverObject
;
1404 UNICODE_STRING ServiceKeyName
;
1406 ULONG i
, RetryCount
= 0;
1409 /* First, create a unique name for the driver if we don't have one */
1412 /* Create a random name and set up the string*/
1413 NameLength
= (USHORT
)swprintf(NameBuffer
,
1416 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1417 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1418 LocalDriverName
.Buffer
= NameBuffer
;
1422 /* So we can avoid another code path, use a local var */
1423 LocalDriverName
= *DriverName
;
1426 /* Initialize the Attributes */
1427 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1428 InitializeObjectAttributes(&ObjectAttributes
,
1430 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
,
1434 /* Create the Object */
1435 Status
= ObCreateObject(KernelMode
,
1443 (PVOID
*)&DriverObject
);
1444 if (!NT_SUCCESS(Status
)) return Status
;
1446 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1448 /* Set up the Object */
1449 RtlZeroMemory(DriverObject
, ObjectSize
);
1450 DriverObject
->Type
= IO_TYPE_DRIVER
;
1451 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1452 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;//DRVO_BUILTIN_DRIVER;
1453 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1454 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1455 DriverObject
->DriverInit
= InitializationFunction
;
1456 DriverObject
->DriverSection
= ModuleObject
;
1457 /* Loop all Major Functions */
1458 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1460 /* Invalidate each function */
1461 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1464 /* Set up the service key name buffer */
1465 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1466 LocalDriverName
.Length
+
1469 if (!ServiceKeyName
.Buffer
)
1472 ObMakeTemporaryObject(DriverObject
);
1473 ObDereferenceObject(DriverObject
);
1474 return STATUS_INSUFFICIENT_RESOURCES
;
1477 /* Fill out the key data and copy the buffer */
1478 ServiceKeyName
.Length
= LocalDriverName
.Length
;
1479 ServiceKeyName
.MaximumLength
= LocalDriverName
.MaximumLength
;
1480 RtlCopyMemory(ServiceKeyName
.Buffer
,
1481 LocalDriverName
.Buffer
,
1482 LocalDriverName
.Length
);
1484 /* Null-terminate it and set it */
1485 ServiceKeyName
.Buffer
[ServiceKeyName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1486 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1488 /* Also store it in the Driver Object. This is a bit of a hack. */
1489 RtlCopyMemory(&DriverObject
->DriverName
,
1491 sizeof(UNICODE_STRING
));
1493 /* Add the Object and get its handle */
1494 Status
= ObInsertObject(DriverObject
,
1501 /* Eliminate small possibility when this function is called more than
1502 once in a row, and KeTickCount doesn't get enough time to change */
1503 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1509 if (!NT_SUCCESS(Status
)) return Status
;
1511 /* Now reference it */
1512 Status
= ObReferenceObjectByHandle(hDriver
,
1516 (PVOID
*)&DriverObject
,
1518 if (!NT_SUCCESS(Status
))
1521 ObMakeTemporaryObject(DriverObject
);
1522 ObDereferenceObject(DriverObject
);
1526 /* Close the extra handle */
1529 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1530 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1531 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1533 /* Finally, call its init function */
1534 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1535 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1536 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1537 if (!NT_SUCCESS(Status
))
1539 /* If it didn't work, then kill the object */
1540 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1541 DriverObject
->DriverSection
= NULL
;
1542 ObMakeTemporaryObject(DriverObject
);
1543 ObDereferenceObject(DriverObject
);
1547 /* Returns to caller the object */
1548 *pDriverObject
= DriverObject
;
1551 /* Loop all Major Functions */
1552 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1555 * Make sure the driver didn't set any dispatch entry point to NULL!
1556 * Doing so is illegal; drivers shouldn't touch entry points they
1560 /* Check if it did so anyway */
1561 if (!DriverObject
->MajorFunction
[i
])
1563 /* Print a warning in the debug log */
1564 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%d] to NULL!\n",
1565 &DriverObject
->DriverName
, i
);
1568 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1572 /* Return the Status */
1576 /* PUBLIC FUNCTIONS ***********************************************************/
1583 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1584 IN PDRIVER_INITIALIZE InitializationFunction
)
1586 PDRIVER_OBJECT DriverObject
;
1587 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, NULL
, &DriverObject
);
1595 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1597 /* Simply dereference the Object */
1598 ObDereferenceObject(DriverObject
);
1606 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1607 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1610 PDRIVER_REINIT_ITEM ReinitItem
;
1612 /* Allocate the entry */
1613 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1614 sizeof(DRIVER_REINIT_ITEM
),
1616 if (!ReinitItem
) return;
1619 ReinitItem
->DriverObject
= DriverObject
;
1620 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1621 ReinitItem
->Context
= Context
;
1623 /* Set the Driver Object flag and insert the entry into the list */
1624 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1625 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1626 &ReinitItem
->ItemEntry
,
1627 &DriverBootReinitListLock
);
1635 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1636 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1639 PDRIVER_REINIT_ITEM ReinitItem
;
1641 /* Allocate the entry */
1642 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1643 sizeof(DRIVER_REINIT_ITEM
),
1645 if (!ReinitItem
) return;
1648 ReinitItem
->DriverObject
= DriverObject
;
1649 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1650 ReinitItem
->Context
= Context
;
1652 /* Set the Driver Object flag and insert the entry into the list */
1653 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1654 ExInterlockedInsertTailList(&DriverReinitListHead
,
1655 &ReinitItem
->ItemEntry
,
1656 &DriverReinitListLock
);
1664 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1665 IN PVOID ClientIdentificationAddress
,
1666 IN ULONG DriverObjectExtensionSize
,
1667 OUT PVOID
*DriverObjectExtension
)
1670 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1671 BOOLEAN Inserted
= FALSE
;
1673 /* Assume failure */
1674 *DriverObjectExtension
= NULL
;
1676 /* Allocate the extension */
1677 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1678 sizeof(IO_CLIENT_EXTENSION
) +
1679 DriverObjectExtensionSize
,
1680 TAG_DRIVER_EXTENSION
);
1681 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1683 /* Clear the extension for teh caller */
1684 RtlZeroMemory(NewDriverExtension
,
1685 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1688 OldIrql
= KeRaiseIrqlToDpcLevel();
1690 /* Fill out the extension */
1691 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1693 /* Loop the current extensions */
1694 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1695 ClientDriverExtension
;
1696 while (DriverExtensions
)
1698 /* Check if the identifier matches */
1699 if (DriverExtensions
->ClientIdentificationAddress
==
1700 ClientIdentificationAddress
)
1702 /* We have a collision, break out */
1706 /* Go to the next one */
1707 DriverExtensions
= DriverExtensions
->NextExtension
;
1710 /* Check if we didn't collide */
1711 if (!DriverExtensions
)
1713 /* Link this one in */
1714 NewDriverExtension
->NextExtension
=
1715 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1716 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1721 /* Release the lock */
1722 KeLowerIrql(OldIrql
);
1724 /* Check if insertion failed */
1727 /* Free the entry and fail */
1728 ExFreePool(NewDriverExtension
);
1729 return STATUS_OBJECT_NAME_COLLISION
;
1732 /* Otherwise, return the pointer */
1733 *DriverObjectExtension
= NewDriverExtension
+ 1;
1734 return STATUS_SUCCESS
;
1742 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1743 IN PVOID ClientIdentificationAddress
)
1746 PIO_CLIENT_EXTENSION DriverExtensions
;
1749 OldIrql
= KeRaiseIrqlToDpcLevel();
1751 /* Loop the list until we find the right one */
1752 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1753 while (DriverExtensions
)
1755 /* Check for a match */
1756 if (DriverExtensions
->ClientIdentificationAddress
==
1757 ClientIdentificationAddress
)
1764 DriverExtensions
= DriverExtensions
->NextExtension
;
1768 KeLowerIrql(OldIrql
);
1770 /* Return nothing or the extension */
1771 if (!DriverExtensions
) return NULL
;
1772 return DriverExtensions
+ 1;
1776 IopLoadUnloadDriver(PLOAD_UNLOAD_PARAMS LoadParams
)
1778 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1779 UNICODE_STRING ImagePath
;
1780 UNICODE_STRING ServiceName
;
1783 PDEVICE_NODE DeviceNode
;
1784 PDRIVER_OBJECT DriverObject
;
1785 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1789 /* Check if it's an unload request */
1790 if (LoadParams
->DriverObject
)
1792 (*LoadParams
->DriverObject
->DriverUnload
)(LoadParams
->DriverObject
);
1794 /* Return success and signal the event */
1795 LoadParams
->Status
= STATUS_SUCCESS
;
1796 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1800 RtlInitUnicodeString(&ImagePath
, NULL
);
1803 * Get the service name from the registry key name.
1805 ASSERT(LoadParams
->ServiceName
->Length
>= sizeof(WCHAR
));
1807 ServiceName
= *LoadParams
->ServiceName
;
1808 cur
= LoadParams
->ServiceName
->Buffer
+
1809 (LoadParams
->ServiceName
->Length
/ sizeof(WCHAR
)) - 1;
1810 while (LoadParams
->ServiceName
->Buffer
!= cur
)
1814 ServiceName
.Buffer
= cur
+ 1;
1815 ServiceName
.Length
= LoadParams
->ServiceName
->Length
-
1816 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1817 (ULONG_PTR
)LoadParams
->ServiceName
->Buffer
);
1823 IopDisplayLoadingMessage(&ServiceName
);
1829 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1831 RtlInitUnicodeString(&ImagePath
, NULL
);
1833 QueryTable
[0].Name
= L
"Type";
1834 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1835 QueryTable
[0].EntryContext
= &Type
;
1837 QueryTable
[1].Name
= L
"ImagePath";
1838 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1839 QueryTable
[1].EntryContext
= &ImagePath
;
1841 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1842 LoadParams
->ServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1844 if (!NT_SUCCESS(Status
))
1846 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1847 if (ImagePath
.Buffer
)
1848 ExFreePool(ImagePath
.Buffer
);
1849 LoadParams
->Status
= Status
;
1850 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1855 * Normalize the image path for all later processing.
1858 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1860 if (!NT_SUCCESS(Status
))
1862 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1863 LoadParams
->Status
= Status
;
1864 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1868 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1869 DPRINT("Type: %lx\n", Type
);
1872 * Create device node
1875 /* Use IopRootDeviceNode for now */
1876 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
1878 if (!NT_SUCCESS(Status
))
1880 DPRINT("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
1881 LoadParams
->Status
= Status
;
1882 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1886 /* Get existing DriverObject pointer (in case the driver has
1887 already been loaded and initialized) */
1888 Status
= IopGetDriverObject(
1891 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1892 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
1894 if (!NT_SUCCESS(Status
))
1897 * Load the driver module
1900 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
1902 if (!NT_SUCCESS(Status
) && Status
!= STATUS_IMAGE_ALREADY_LOADED
)
1904 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
1905 IopFreeDeviceNode(DeviceNode
);
1906 LoadParams
->Status
= Status
;
1907 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1912 * Set a service name for the device node
1915 RtlCreateUnicodeString(&DeviceNode
->ServiceName
, ServiceName
.Buffer
);
1918 * Initialize the driver module if it's loaded for the first time
1920 if (Status
!= STATUS_IMAGE_ALREADY_LOADED
)
1922 Status
= IopInitializeDriverModule(
1925 &DeviceNode
->ServiceName
,
1926 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1927 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
1930 if (!NT_SUCCESS(Status
))
1932 DPRINT("IopInitializeDriver() failed (Status %lx)\n", Status
);
1933 MmUnloadSystemImage(ModuleObject
);
1934 IopFreeDeviceNode(DeviceNode
);
1935 LoadParams
->Status
= Status
;
1936 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1941 /* Initialize and start device */
1942 IopInitializeDevice(DeviceNode
, DriverObject
);
1943 Status
= IopStartDevice(DeviceNode
);
1947 DPRINT("DriverObject already exist in ObjectManager\n");
1949 /* IopGetDriverObject references the DriverObject, so dereference it */
1950 ObDereferenceObject(DriverObject
);
1952 /* Free device node since driver loading failed */
1953 IopFreeDeviceNode(DeviceNode
);
1956 /* Pass status to the caller and signal the event */
1957 LoadParams
->Status
= Status
;
1958 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1964 * Loads a device driver.
1968 * Name of the service to load (registry key).
1977 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
1979 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
1980 KPROCESSOR_MODE PreviousMode
;
1981 LOAD_UNLOAD_PARAMS LoadParams
;
1986 PreviousMode
= KeGetPreviousMode();
1989 * Check security privileges
1992 /* FIXME: Uncomment when privileges will be correctly implemented. */
1994 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
1996 DPRINT("Privilege not held\n");
1997 return STATUS_PRIVILEGE_NOT_HELD
;
2001 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2004 if (!NT_SUCCESS(Status
))
2009 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2011 LoadParams
.ServiceName
= &CapturedDriverServiceName
;
2012 LoadParams
.DriverObject
= NULL
;
2013 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
2015 /* Call the load/unload routine, depending on current process */
2016 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
2018 /* Just call right away */
2019 IopLoadUnloadDriver(&LoadParams
);
2023 /* Load/Unload must be called from system process */
2024 ExInitializeWorkItem(&LoadParams
.WorkItem
,
2025 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
2026 (PVOID
)&LoadParams
);
2029 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
2031 /* And wait when it completes */
2032 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
2036 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2039 return LoadParams
.Status
;
2045 * Unloads a legacy device driver.
2049 * Name of the service to unload (registry key).
2059 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2061 return IopUnloadDriver(DriverServiceName
, FALSE
);