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 if (ExpInTextModeSetup
)
315 /* We have no registry, but luckily we know where all the drivers are */
317 /* ServiceStart < 4 is all that matters */
320 /* IopNormalizeImagePath will do all of the work for us if we give it an empty string */
321 ServiceImagePath
.Length
= ServiceImagePath
.MaximumLength
= 0;
322 ServiceImagePath
.Buffer
= NULL
;
326 /* Open CurrentControlSet */
327 RtlInitUnicodeString(&CCSName
,
328 L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services");
329 Status
= IopOpenRegistryKeyEx(&CCSKey
, NULL
, &CCSName
, KEY_READ
);
330 if (!NT_SUCCESS(Status
))
332 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
336 /* Open service key */
337 Status
= IopOpenRegistryKeyEx(&ServiceKey
, CCSKey
, ServiceName
, KEY_READ
);
338 if (!NT_SUCCESS(Status
))
340 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
346 * Get information about the service.
349 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
351 RtlInitUnicodeString(&ServiceImagePath
, NULL
);
353 QueryTable
[0].Name
= L
"Start";
354 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
355 QueryTable
[0].EntryContext
= &ServiceStart
;
357 QueryTable
[1].Name
= L
"ImagePath";
358 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
359 QueryTable
[1].EntryContext
= &ServiceImagePath
;
361 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
362 (PWSTR
)ServiceKey
, QueryTable
, NULL
, NULL
);
367 if (!NT_SUCCESS(Status
))
369 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
375 * Normalize the image path for all later processing.
378 Status
= IopNormalizeImagePath(&ServiceImagePath
, ServiceName
);
380 if (!NT_SUCCESS(Status
))
382 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
387 * Case for disabled drivers
390 if (ServiceStart
>= 4)
392 /* FIXME: Check if it is the right status code */
393 Status
= STATUS_PLUGPLAY_NO_DEVICE
;
397 DPRINT("Loading module\n");
398 Status
= MmLoadSystemImage(&ServiceImagePath
, NULL
, NULL
, 0, (PVOID
)ModuleObject
, &BaseAddress
);
401 ExFreePool(ServiceImagePath
.Buffer
);
404 * Now check if the module was loaded successfully.
407 if (!NT_SUCCESS(Status
))
409 DPRINT("Module loading failed (Status %x)\n", Status
);
412 DPRINT("Module loading (Status %x)\n", Status
);
418 * IopInitializeDriverModule
420 * Initalize a loaded driver.
424 * Pointer to device node.
427 * Module object representing the driver. It can be retrieve by
428 * IopLoadServiceModule.
431 * Name of the service (as in registry).
434 * Set to TRUE for file system drivers.
437 * On successful return this contains the driver object representing
442 IopInitializeDriverModule(
443 IN PDEVICE_NODE DeviceNode
,
444 IN PLDR_DATA_TABLE_ENTRY ModuleObject
,
445 IN PUNICODE_STRING ServiceName
,
446 IN BOOLEAN FileSystemDriver
,
447 OUT PDRIVER_OBJECT
*DriverObject
)
449 const WCHAR ServicesKeyName
[] = L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";
450 WCHAR NameBuffer
[MAX_PATH
];
451 UNICODE_STRING DriverName
;
452 UNICODE_STRING RegistryKey
;
453 PDRIVER_INITIALIZE DriverEntry
;
454 PDRIVER_OBJECT Driver
;
457 DriverEntry
= ModuleObject
->EntryPoint
;
459 if (ServiceName
!= NULL
&& ServiceName
->Length
!= 0)
461 RegistryKey
.Length
= 0;
462 RegistryKey
.MaximumLength
= sizeof(ServicesKeyName
) + ServiceName
->Length
;
463 RegistryKey
.Buffer
= ExAllocatePool(PagedPool
, RegistryKey
.MaximumLength
);
464 if (RegistryKey
.Buffer
== NULL
)
466 return STATUS_INSUFFICIENT_RESOURCES
;
468 RtlAppendUnicodeToString(&RegistryKey
, ServicesKeyName
);
469 RtlAppendUnicodeStringToString(&RegistryKey
, ServiceName
);
473 RtlInitUnicodeString(&RegistryKey
, NULL
);
476 /* Create ModuleName string */
477 if (ServiceName
&& ServiceName
->Length
> 0)
479 if (FileSystemDriver
== TRUE
)
480 wcscpy(NameBuffer
, FILESYSTEM_ROOT_NAME
);
482 wcscpy(NameBuffer
, DRIVER_ROOT_NAME
);
484 RtlInitUnicodeString(&DriverName
, NameBuffer
);
485 DriverName
.MaximumLength
= sizeof(NameBuffer
);
487 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
489 DPRINT("Driver name: '%wZ'\n", &DriverName
);
492 DriverName
.Length
= 0;
494 Status
= IopCreateDriver(
495 DriverName
.Length
> 0 ? &DriverName
: NULL
,
500 RtlFreeUnicodeString(&RegistryKey
);
502 *DriverObject
= Driver
;
503 if (!NT_SUCCESS(Status
))
505 DPRINT("IopCreateDriver() failed (Status 0x%08lx)\n", Status
);
509 /* Set the driver as initialized */
510 IopReadyDeviceObjects(Driver
);
512 if (PnpSystemInit
) IopReinitializeDrivers();
514 return STATUS_SUCCESS
;
518 * IopAttachFilterDriversCallback
520 * Internal routine used by IopAttachFilterDrivers.
524 IopAttachFilterDriversCallback(
532 PDEVICE_NODE DeviceNode
= Context
;
533 UNICODE_STRING ServiceName
;
535 PLDR_DATA_TABLE_ENTRY ModuleObject
;
536 PDRIVER_OBJECT DriverObject
;
539 for (Filters
= ValueData
;
540 ((ULONG_PTR
)Filters
- (ULONG_PTR
)ValueData
) < ValueLength
&&
542 Filters
+= (ServiceName
.Length
/ sizeof(WCHAR
)) + 1)
544 DPRINT("Filter Driver: %S (%wZ)\n", Filters
, &DeviceNode
->InstancePath
);
545 ServiceName
.Buffer
= Filters
;
546 ServiceName
.MaximumLength
=
547 ServiceName
.Length
= wcslen(Filters
) * sizeof(WCHAR
);
549 /* Load and initialize the filter driver */
550 Status
= IopLoadServiceModule(&ServiceName
, &ModuleObject
);
551 if (Status
!= STATUS_IMAGE_ALREADY_LOADED
)
553 if (!NT_SUCCESS(Status
))
556 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
, &ServiceName
,
557 FALSE
, &DriverObject
);
558 if (!NT_SUCCESS(Status
))
563 /* get existing DriverObject pointer */
564 Status
= IopGetDriverObject(
568 if (!NT_SUCCESS(Status
))
570 DPRINT1("IopGetDriverObject() returned status 0x%08x!\n", Status
);
575 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
576 if (!NT_SUCCESS(Status
))
580 return STATUS_SUCCESS
;
584 * IopAttachFilterDrivers
586 * Load filter drivers for specified device node.
590 * Set to TRUE for loading lower level filters or FALSE for upper
595 IopAttachFilterDrivers(
596 PDEVICE_NODE DeviceNode
,
599 RTL_QUERY_REGISTRY_TABLE QueryTable
[2] = { { NULL
, 0, NULL
, NULL
, 0, NULL
, 0 }, };
600 UNICODE_STRING Class
;
601 WCHAR ClassBuffer
[40];
602 UNICODE_STRING EnumRoot
= RTL_CONSTANT_STRING(ENUM_ROOT
);
603 HANDLE EnumRootKey
, SubKey
;
606 /* Open enumeration root key */
607 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
608 &EnumRoot
, KEY_READ
);
609 if (!NT_SUCCESS(Status
))
611 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
616 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
617 &DeviceNode
->InstancePath
, KEY_READ
);
618 if (!NT_SUCCESS(Status
))
620 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
621 ZwClose(EnumRootKey
);
626 * First load the device filters
628 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
630 QueryTable
[0].Name
= L
"LowerFilters";
632 QueryTable
[0].Name
= L
"UpperFilters";
633 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
635 RtlQueryRegistryValues(
643 * Now get the class GUID
646 Class
.MaximumLength
= 40 * sizeof(WCHAR
);
647 Class
.Buffer
= ClassBuffer
;
648 QueryTable
[0].QueryRoutine
= NULL
;
649 QueryTable
[0].Name
= L
"ClassGUID";
650 QueryTable
[0].EntryContext
= &Class
;
651 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
| RTL_QUERY_REGISTRY_DIRECT
;
653 Status
= RtlQueryRegistryValues(
662 ZwClose(EnumRootKey
);
665 * Load the class filter driver
667 if (NT_SUCCESS(Status
))
669 UNICODE_STRING ControlClass
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class");
671 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
672 &ControlClass
, KEY_READ
);
673 if (!NT_SUCCESS(Status
))
675 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
680 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
682 if (!NT_SUCCESS(Status
))
684 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
685 ZwClose(EnumRootKey
);
689 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
691 QueryTable
[0].Name
= L
"LowerFilters";
693 QueryTable
[0].Name
= L
"UpperFilters";
694 QueryTable
[0].EntryContext
= NULL
;
695 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
697 RtlQueryRegistryValues(
706 ZwClose(EnumRootKey
);
709 return STATUS_SUCCESS
;
714 MiResolveImageReferences(IN PVOID ImageBase
,
715 IN PUNICODE_STRING ImageFileDirectory
,
716 IN PUNICODE_STRING NamePrefix OPTIONAL
,
717 OUT PCHAR
*MissingApi
,
718 OUT PWCHAR
*MissingDriver
,
719 OUT PLOAD_IMPORTS
*LoadImports
);
722 // Used for images already loaded (boot drivers)
727 LdrProcessDriverModule(PLDR_DATA_TABLE_ENTRY LdrEntry
,
728 PUNICODE_STRING FileName
,
729 PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
732 UNICODE_STRING BaseName
, BaseDirectory
;
733 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
734 PCHAR MissingApiName
, Buffer
;
735 PWCHAR MissingDriverName
;
736 PVOID DriverBase
= LdrEntry
->DllBase
;
738 /* Allocate a buffer we'll use for names */
739 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
743 return STATUS_INSUFFICIENT_RESOURCES
;
746 /* Check for a separator */
747 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
752 /* Loop the path until we get to the base name */
753 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
754 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
757 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
758 BaseLength
*= sizeof(WCHAR
);
760 /* Setup the string */
761 BaseName
.Length
= (USHORT
)BaseLength
;
766 /* Otherwise, we already have a base name */
767 BaseName
.Length
= FileName
->Length
;
768 BaseName
.Buffer
= FileName
->Buffer
;
771 /* Setup the maximum length */
772 BaseName
.MaximumLength
= BaseName
.Length
;
774 /* Now compute the base directory */
775 BaseDirectory
= *FileName
;
776 BaseDirectory
.Length
-= BaseName
.Length
;
777 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
779 /* Resolve imports */
780 MissingApiName
= Buffer
;
781 Status
= MiResolveImageReferences(DriverBase
,
787 if (!NT_SUCCESS(Status
)) return Status
;
790 *ModuleObject
= LdrEntry
;
791 return STATUS_SUCCESS
;
795 * IopInitializeBuiltinDriver
797 * Initialize a driver that is already loaded in memory.
803 IopInitializeBuiltinDriver(IN PLDR_DATA_TABLE_ENTRY LdrEntry
)
805 PDEVICE_NODE DeviceNode
;
806 PDRIVER_OBJECT DriverObject
;
808 PWCHAR FileNameWithoutPath
;
809 LPWSTR FileExtension
;
810 PUNICODE_STRING ModuleName
= &LdrEntry
->BaseDllName
;
811 UNICODE_STRING ServiceName
;
814 * Display 'Loading XXX...' message
816 IopDisplayLoadingMessage(ModuleName
);
817 InbvIndicateProgress();
820 * Generate filename without path (not needed by freeldr)
822 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
823 if (FileNameWithoutPath
== NULL
)
825 FileNameWithoutPath
= ModuleName
->Buffer
;
829 FileNameWithoutPath
++;
833 * Strip the file extension from ServiceName
835 RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
836 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
837 if (FileExtension
!= NULL
)
839 ServiceName
.Length
-= wcslen(FileExtension
) * sizeof(WCHAR
);
840 FileExtension
[0] = 0;
844 * Determine the right device object
846 /* Use IopRootDeviceNode for now */
847 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
848 if (!NT_SUCCESS(Status
))
850 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
855 * Initialize the driver
857 Status
= IopInitializeDriverModule(DeviceNode
, LdrEntry
,
858 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
860 if (!NT_SUCCESS(Status
))
862 IopFreeDeviceNode(DeviceNode
);
866 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
867 if (NT_SUCCESS(Status
))
869 Status
= IopStartDevice(DeviceNode
);
876 * IopInitializeBootDrivers
878 * Initialize boot drivers and free memory for boot files.
889 IopInitializeBootDrivers(VOID
)
891 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
892 PLDR_DATA_TABLE_ENTRY LdrEntry
;
893 PDEVICE_NODE DeviceNode
;
894 PDRIVER_OBJECT DriverObject
;
895 LDR_DATA_TABLE_ENTRY ModuleObject
;
897 UNICODE_STRING DriverName
;
899 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
901 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
902 DPRINT("IopInitializeBootDrivers()\n");
904 /* Use IopRootDeviceNode for now */
905 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
906 if (!NT_SUCCESS(Status
)) return;
908 /* Setup the module object for the RAW FS Driver */
909 ModuleObject
.DllBase
= NULL
;
910 ModuleObject
.SizeOfImage
= 0;
911 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
912 RtlInitUnicodeString(&DriverName
, L
"RAW");
915 Status
= IopInitializeDriverModule(DeviceNode
,
920 if (!NT_SUCCESS(Status
))
923 IopFreeDeviceNode(DeviceNode
);
927 /* Now initialize the associated device */
928 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
929 if (!NT_SUCCESS(Status
))
932 IopFreeDeviceNode(DeviceNode
);
937 Status
= IopStartDevice(DeviceNode
);
938 if (!NT_SUCCESS(Status
))
941 IopFreeDeviceNode(DeviceNode
);
945 /* Get highest group order index */
946 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
947 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
949 /* Allocate the group table */
950 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
951 IopGroupIndex
* sizeof(LIST_ENTRY
),
953 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
955 /* Initialize the group table lists */
956 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
958 /* Loop the boot modules */
959 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
960 NextEntry
= ListHead
->Flink
;
961 while (ListHead
!= NextEntry
)
964 LdrEntry
= CONTAINING_RECORD(NextEntry
,
965 LDR_DATA_TABLE_ENTRY
,
968 /* Check if the DLL needs to be initialized */
969 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
971 /* Call its entrypoint */
972 MmCallDllInitialize(LdrEntry
, NULL
);
975 /* Go to the next driver */
976 NextEntry
= NextEntry
->Flink
;
979 /* Loop the boot drivers */
980 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
981 NextEntry
= ListHead
->Flink
;
982 while (ListHead
!= NextEntry
)
985 BootEntry
= CONTAINING_RECORD(NextEntry
,
986 BOOT_DRIVER_LIST_ENTRY
,
989 /* Get the driver loader entry */
990 LdrEntry
= BootEntry
->LdrEntry
;
992 /* Allocate our internal accounting structure */
993 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
994 sizeof(DRIVER_INFORMATION
),
998 /* Zero it and initialize it */
999 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1000 InitializeListHead(&DriverInfo
->Link
);
1001 DriverInfo
->DataTableEntry
= BootEntry
;
1003 /* Open the registry key */
1004 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1006 &BootEntry
->RegistryPath
,
1008 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1009 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1011 /* Save the handle */
1012 DriverInfo
->ServiceHandle
= KeyHandle
;
1014 /* Get the group oder index */
1015 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1017 /* Get the tag position */
1018 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1020 /* Insert it into the list, at the right place */
1021 ASSERT(Index
< IopGroupIndex
);
1022 NextEntry2
= IopGroupTable
[Index
].Flink
;
1023 while (NextEntry2
!= &IopGroupTable
[Index
])
1025 /* Get the driver info */
1026 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1030 /* Check if we found the right tag position */
1031 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1038 NextEntry2
= NextEntry2
->Flink
;
1041 /* Insert us right before the next entry */
1042 NextEntry2
= NextEntry2
->Blink
;
1043 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1047 /* Go to the next driver */
1048 NextEntry
= NextEntry
->Flink
;
1051 /* Loop each group index */
1052 for (i
= 0; i
< IopGroupIndex
; i
++)
1054 /* Loop each group table */
1055 NextEntry
= IopGroupTable
[i
].Flink
;
1056 while (NextEntry
!= &IopGroupTable
[i
])
1059 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1063 /* Get the driver loader entry */
1064 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1067 IopInitializeBuiltinDriver(LdrEntry
);
1070 NextEntry
= NextEntry
->Flink
;
1074 /* In old ROS, the loader list became empty after this point. Simulate. */
1075 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1081 IopInitializeSystemDrivers(VOID
)
1083 PUNICODE_STRING
*DriverList
, *SavedList
;
1085 /* No system drivers on the boot cd */
1086 if (KeLoaderBlock
->SetupLdrBlock
) return;
1088 /* Get the driver list */
1089 SavedList
= DriverList
= CmGetSystemDriverList();
1095 /* Load the driver */
1096 ZwLoadDriver(*DriverList
);
1098 /* Free the entry */
1099 RtlFreeUnicodeString(*DriverList
);
1100 ExFreePool(*DriverList
);
1103 InbvIndicateProgress();
1108 ExFreePool(SavedList
);
1114 * Unloads a device driver.
1118 * Name of the service to unload (registry key).
1121 * Whether to unload Plug & Plug or only legacy drivers. If this
1122 * parameter is set to FALSE, the routine will unload only legacy
1129 * Guard the whole function by SEH.
1133 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1135 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1136 UNICODE_STRING ImagePath
;
1137 UNICODE_STRING ServiceName
;
1138 UNICODE_STRING ObjectName
;
1139 PDRIVER_OBJECT DriverObject
;
1140 PDEVICE_OBJECT DeviceObject
;
1141 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1142 LOAD_UNLOAD_PARAMS LoadParams
;
1145 BOOLEAN SafeToUnload
= TRUE
;
1147 DPRINT("IopUnloadDriver('%wZ', %d)\n", DriverServiceName
, UnloadPnpDrivers
);
1152 * Get the service name from the registry key name
1155 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1157 Start
= DriverServiceName
->Buffer
;
1161 RtlInitUnicodeString(&ServiceName
, Start
);
1164 * Construct the driver object name
1167 ObjectName
.Length
= (wcslen(Start
) + 8) * sizeof(WCHAR
);
1168 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1169 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1170 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1171 wcscpy(ObjectName
.Buffer
, L
"\\Driver\\");
1172 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1173 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1176 * Find the driver object
1178 Status
= ObReferenceObjectByName(&ObjectName
,
1185 (PVOID
*)&DriverObject
);
1187 if (!NT_SUCCESS(Status
))
1189 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1190 ExFreePool(ObjectName
.Buffer
);
1195 * Free the buffer for driver object name
1197 ExFreePool(ObjectName
.Buffer
);
1199 /* Check that driver is not already unloading */
1200 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1202 DPRINT1("Driver deletion pending\n");
1203 ObDereferenceObject(DriverObject
);
1204 return STATUS_DELETE_PENDING
;
1208 * Get path of service...
1211 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1213 RtlInitUnicodeString(&ImagePath
, NULL
);
1215 QueryTable
[0].Name
= L
"ImagePath";
1216 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1217 QueryTable
[0].EntryContext
= &ImagePath
;
1219 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1220 DriverServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1222 if (!NT_SUCCESS(Status
))
1224 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1225 ObDereferenceObject(DriverObject
);
1230 * Normalize the image path for all later processing.
1233 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1235 if (!NT_SUCCESS(Status
))
1237 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1238 ObDereferenceObject(DriverObject
);
1243 * Free the service path
1246 ExFreePool(ImagePath
.Buffer
);
1249 * Unload the module and release the references to the device object
1252 /* Call the load/unload routine, depending on current process */
1253 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
)
1255 /* Loop through each device object of the driver
1256 and set DOE_UNLOAD_PENDING flag */
1257 DeviceObject
= DriverObject
->DeviceObject
;
1258 while (DeviceObject
)
1260 /* Set the unload pending flag for the device */
1261 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1262 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1264 /* Make sure there are no attached devices or no reference counts */
1265 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1267 /* Not safe to unload */
1268 DPRINT1("Drivers device object is referenced or has attached devices\n");
1270 SafeToUnload
= FALSE
;
1273 DeviceObject
= DeviceObject
->NextDevice
;
1276 /* If not safe to unload, then return success */
1279 ObDereferenceObject(DriverObject
);
1280 return STATUS_SUCCESS
;
1283 /* Set the unload invoked flag */
1284 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1286 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
1288 /* Just call right away */
1289 (*DriverObject
->DriverUnload
)(DriverObject
);
1293 /* Load/Unload must be called from system process */
1295 /* Prepare parameters block */
1296 LoadParams
.DriverObject
= DriverObject
;
1297 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1299 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1300 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
1301 (PVOID
)&LoadParams
);
1304 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1306 /* And wait when it completes */
1307 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
1311 /* Mark the driver object temporary, so it could be deleted later */
1312 ObMakeTemporaryObject(DriverObject
);
1314 /* Dereference it 2 times */
1315 ObDereferenceObject(DriverObject
);
1316 ObDereferenceObject(DriverObject
);
1318 return STATUS_SUCCESS
;
1322 /* Dereference one time (refd inside this function) */
1323 ObDereferenceObject(DriverObject
);
1325 /* Return unloading failure */
1326 return STATUS_INVALID_DEVICE_REQUEST
;
1332 IopReinitializeDrivers(VOID
)
1334 PDRIVER_REINIT_ITEM ReinitItem
;
1337 /* Get the first entry and start looping */
1338 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1339 &DriverReinitListLock
);
1343 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1345 /* Increment reinitialization counter */
1346 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1348 /* Remove the device object flag */
1349 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1351 /* Call the routine */
1352 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1353 ReinitItem
->Context
,
1354 ReinitItem
->DriverObject
->
1355 DriverExtension
->Count
);
1357 /* Free the entry */
1360 /* Move to the next one */
1361 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1362 &DriverReinitListLock
);
1368 IopReinitializeBootDrivers(VOID
)
1370 PDRIVER_REINIT_ITEM ReinitItem
;
1373 /* Get the first entry and start looping */
1374 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1375 &DriverBootReinitListLock
);
1379 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1381 /* Increment reinitialization counter */
1382 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1384 /* Remove the device object flag */
1385 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1387 /* Call the routine */
1388 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1389 ReinitItem
->Context
,
1390 ReinitItem
->DriverObject
->
1391 DriverExtension
->Count
);
1393 /* Free the entry */
1396 /* Move to the next one */
1397 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1398 &DriverBootReinitListLock
);
1404 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1405 IN PDRIVER_INITIALIZE InitializationFunction
,
1406 IN PUNICODE_STRING RegistryPath
,
1407 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1408 OUT PDRIVER_OBJECT
*pDriverObject
)
1410 WCHAR NameBuffer
[100];
1412 UNICODE_STRING LocalDriverName
;
1414 OBJECT_ATTRIBUTES ObjectAttributes
;
1416 PDRIVER_OBJECT DriverObject
;
1417 UNICODE_STRING ServiceKeyName
;
1419 ULONG i
, RetryCount
= 0;
1422 /* First, create a unique name for the driver if we don't have one */
1425 /* Create a random name and set up the string*/
1426 NameLength
= (USHORT
)swprintf(NameBuffer
,
1429 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1430 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1431 LocalDriverName
.Buffer
= NameBuffer
;
1435 /* So we can avoid another code path, use a local var */
1436 LocalDriverName
= *DriverName
;
1439 /* Initialize the Attributes */
1440 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1441 InitializeObjectAttributes(&ObjectAttributes
,
1443 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
,
1447 /* Create the Object */
1448 Status
= ObCreateObject(KernelMode
,
1456 (PVOID
*)&DriverObject
);
1457 if (!NT_SUCCESS(Status
)) return Status
;
1459 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1461 /* Set up the Object */
1462 RtlZeroMemory(DriverObject
, ObjectSize
);
1463 DriverObject
->Type
= IO_TYPE_DRIVER
;
1464 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1465 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;//DRVO_BUILTIN_DRIVER;
1466 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1467 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1468 DriverObject
->DriverInit
= InitializationFunction
;
1469 DriverObject
->DriverSection
= ModuleObject
;
1470 /* Loop all Major Functions */
1471 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1473 /* Invalidate each function */
1474 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1477 /* Set up the service key name buffer */
1478 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1479 LocalDriverName
.Length
+
1482 if (!ServiceKeyName
.Buffer
)
1485 ObMakeTemporaryObject(DriverObject
);
1486 ObDereferenceObject(DriverObject
);
1487 return STATUS_INSUFFICIENT_RESOURCES
;
1490 /* Fill out the key data and copy the buffer */
1491 ServiceKeyName
.Length
= LocalDriverName
.Length
;
1492 ServiceKeyName
.MaximumLength
= LocalDriverName
.MaximumLength
;
1493 RtlCopyMemory(ServiceKeyName
.Buffer
,
1494 LocalDriverName
.Buffer
,
1495 LocalDriverName
.Length
);
1497 /* Null-terminate it and set it */
1498 ServiceKeyName
.Buffer
[ServiceKeyName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1499 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1501 /* Also store it in the Driver Object. This is a bit of a hack. */
1502 RtlCopyMemory(&DriverObject
->DriverName
,
1504 sizeof(UNICODE_STRING
));
1506 /* Add the Object and get its handle */
1507 Status
= ObInsertObject(DriverObject
,
1514 /* Eliminate small possibility when this function is called more than
1515 once in a row, and KeTickCount doesn't get enough time to change */
1516 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1522 if (!NT_SUCCESS(Status
)) return Status
;
1524 /* Now reference it */
1525 Status
= ObReferenceObjectByHandle(hDriver
,
1529 (PVOID
*)&DriverObject
,
1531 if (!NT_SUCCESS(Status
))
1534 ObMakeTemporaryObject(DriverObject
);
1535 ObDereferenceObject(DriverObject
);
1539 /* Close the extra handle */
1542 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1543 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1544 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1546 /* Finally, call its init function */
1547 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1548 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1549 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1550 if (!NT_SUCCESS(Status
))
1552 /* If it didn't work, then kill the object */
1553 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1554 DriverObject
->DriverSection
= NULL
;
1555 ObMakeTemporaryObject(DriverObject
);
1556 ObDereferenceObject(DriverObject
);
1560 /* Returns to caller the object */
1561 *pDriverObject
= DriverObject
;
1564 /* Loop all Major Functions */
1565 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1568 * Make sure the driver didn't set any dispatch entry point to NULL!
1569 * Doing so is illegal; drivers shouldn't touch entry points they
1573 /* Check if it did so anyway */
1574 if (!DriverObject
->MajorFunction
[i
])
1576 /* Print a warning in the debug log */
1577 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%d] to NULL!\n",
1578 &DriverObject
->DriverName
, i
);
1581 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1585 /* Return the Status */
1589 /* PUBLIC FUNCTIONS ***********************************************************/
1596 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1597 IN PDRIVER_INITIALIZE InitializationFunction
)
1599 PDRIVER_OBJECT DriverObject
;
1600 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, NULL
, &DriverObject
);
1608 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1610 /* Simply dereference the Object */
1611 ObDereferenceObject(DriverObject
);
1619 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1620 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1623 PDRIVER_REINIT_ITEM ReinitItem
;
1625 /* Allocate the entry */
1626 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1627 sizeof(DRIVER_REINIT_ITEM
),
1629 if (!ReinitItem
) return;
1632 ReinitItem
->DriverObject
= DriverObject
;
1633 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1634 ReinitItem
->Context
= Context
;
1636 /* Set the Driver Object flag and insert the entry into the list */
1637 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1638 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1639 &ReinitItem
->ItemEntry
,
1640 &DriverBootReinitListLock
);
1648 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1649 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1652 PDRIVER_REINIT_ITEM ReinitItem
;
1654 /* Allocate the entry */
1655 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1656 sizeof(DRIVER_REINIT_ITEM
),
1658 if (!ReinitItem
) return;
1661 ReinitItem
->DriverObject
= DriverObject
;
1662 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1663 ReinitItem
->Context
= Context
;
1665 /* Set the Driver Object flag and insert the entry into the list */
1666 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1667 ExInterlockedInsertTailList(&DriverReinitListHead
,
1668 &ReinitItem
->ItemEntry
,
1669 &DriverReinitListLock
);
1677 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1678 IN PVOID ClientIdentificationAddress
,
1679 IN ULONG DriverObjectExtensionSize
,
1680 OUT PVOID
*DriverObjectExtension
)
1683 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1684 BOOLEAN Inserted
= FALSE
;
1686 /* Assume failure */
1687 *DriverObjectExtension
= NULL
;
1689 /* Allocate the extension */
1690 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1691 sizeof(IO_CLIENT_EXTENSION
) +
1692 DriverObjectExtensionSize
,
1693 TAG_DRIVER_EXTENSION
);
1694 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1696 /* Clear the extension for teh caller */
1697 RtlZeroMemory(NewDriverExtension
,
1698 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1701 OldIrql
= KeRaiseIrqlToDpcLevel();
1703 /* Fill out the extension */
1704 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1706 /* Loop the current extensions */
1707 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1708 ClientDriverExtension
;
1709 while (DriverExtensions
)
1711 /* Check if the identifier matches */
1712 if (DriverExtensions
->ClientIdentificationAddress
==
1713 ClientIdentificationAddress
)
1715 /* We have a collision, break out */
1719 /* Go to the next one */
1720 DriverExtensions
= DriverExtensions
->NextExtension
;
1723 /* Check if we didn't collide */
1724 if (!DriverExtensions
)
1726 /* Link this one in */
1727 NewDriverExtension
->NextExtension
=
1728 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1729 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1734 /* Release the lock */
1735 KeLowerIrql(OldIrql
);
1737 /* Check if insertion failed */
1740 /* Free the entry and fail */
1741 ExFreePool(NewDriverExtension
);
1742 return STATUS_OBJECT_NAME_COLLISION
;
1745 /* Otherwise, return the pointer */
1746 *DriverObjectExtension
= NewDriverExtension
+ 1;
1747 return STATUS_SUCCESS
;
1755 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1756 IN PVOID ClientIdentificationAddress
)
1759 PIO_CLIENT_EXTENSION DriverExtensions
;
1762 OldIrql
= KeRaiseIrqlToDpcLevel();
1764 /* Loop the list until we find the right one */
1765 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1766 while (DriverExtensions
)
1768 /* Check for a match */
1769 if (DriverExtensions
->ClientIdentificationAddress
==
1770 ClientIdentificationAddress
)
1777 DriverExtensions
= DriverExtensions
->NextExtension
;
1781 KeLowerIrql(OldIrql
);
1783 /* Return nothing or the extension */
1784 if (!DriverExtensions
) return NULL
;
1785 return DriverExtensions
+ 1;
1789 IopLoadUnloadDriver(PLOAD_UNLOAD_PARAMS LoadParams
)
1791 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1792 UNICODE_STRING ImagePath
;
1793 UNICODE_STRING ServiceName
;
1796 PDEVICE_NODE DeviceNode
;
1797 PDRIVER_OBJECT DriverObject
;
1798 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1802 /* Check if it's an unload request */
1803 if (LoadParams
->DriverObject
)
1805 (*LoadParams
->DriverObject
->DriverUnload
)(LoadParams
->DriverObject
);
1807 /* Return success and signal the event */
1808 LoadParams
->Status
= STATUS_SUCCESS
;
1809 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1813 RtlInitUnicodeString(&ImagePath
, NULL
);
1816 * Get the service name from the registry key name.
1818 ASSERT(LoadParams
->ServiceName
->Length
>= sizeof(WCHAR
));
1820 ServiceName
= *LoadParams
->ServiceName
;
1821 cur
= LoadParams
->ServiceName
->Buffer
+
1822 (LoadParams
->ServiceName
->Length
/ sizeof(WCHAR
)) - 1;
1823 while (LoadParams
->ServiceName
->Buffer
!= cur
)
1827 ServiceName
.Buffer
= cur
+ 1;
1828 ServiceName
.Length
= LoadParams
->ServiceName
->Length
-
1829 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1830 (ULONG_PTR
)LoadParams
->ServiceName
->Buffer
);
1840 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1842 RtlInitUnicodeString(&ImagePath
, NULL
);
1844 QueryTable
[0].Name
= L
"Type";
1845 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1846 QueryTable
[0].EntryContext
= &Type
;
1848 QueryTable
[1].Name
= L
"ImagePath";
1849 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1850 QueryTable
[1].EntryContext
= &ImagePath
;
1852 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1853 LoadParams
->ServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1855 if (!NT_SUCCESS(Status
))
1857 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1858 if (ImagePath
.Buffer
)
1859 ExFreePool(ImagePath
.Buffer
);
1860 LoadParams
->Status
= Status
;
1861 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1866 * Normalize the image path for all later processing.
1869 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1871 if (!NT_SUCCESS(Status
))
1873 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1874 LoadParams
->Status
= Status
;
1875 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1879 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1880 DPRINT("Type: %lx\n", Type
);
1882 /* Get existing DriverObject pointer (in case the driver has
1883 already been loaded and initialized) */
1884 Status
= IopGetDriverObject(
1887 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1888 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
1890 if (!NT_SUCCESS(Status
))
1893 * Load the driver module
1896 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
1898 if (!NT_SUCCESS(Status
) && Status
!= STATUS_IMAGE_ALREADY_LOADED
)
1900 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
1901 LoadParams
->Status
= Status
;
1902 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1907 * Initialize the driver module if it's loaded for the first time
1909 if (Status
!= STATUS_IMAGE_ALREADY_LOADED
)
1911 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
1913 if (!NT_SUCCESS(Status
))
1915 DPRINT("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
1916 MmUnloadSystemImage(ModuleObject
);
1917 LoadParams
->Status
= Status
;
1918 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1922 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
1924 Status
= IopInitializeDriverModule(
1927 &DeviceNode
->ServiceName
,
1928 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1929 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
1932 if (!NT_SUCCESS(Status
))
1934 DPRINT("IopInitializeDriver() failed (Status %lx)\n", Status
);
1935 MmUnloadSystemImage(ModuleObject
);
1936 IopFreeDeviceNode(DeviceNode
);
1937 LoadParams
->Status
= Status
;
1938 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1942 /* Initialize and start device */
1943 IopInitializeDevice(DeviceNode
, DriverObject
);
1944 Status
= IopStartDevice(DeviceNode
);
1949 DPRINT("DriverObject already exist in ObjectManager\n");
1951 /* IopGetDriverObject references the DriverObject, so dereference it */
1952 ObDereferenceObject(DriverObject
);
1955 /* Pass status to the caller and signal the event */
1956 LoadParams
->Status
= Status
;
1957 (VOID
)KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1963 * Loads a device driver.
1967 * Name of the service to load (registry key).
1976 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
1978 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
1979 KPROCESSOR_MODE PreviousMode
;
1980 LOAD_UNLOAD_PARAMS LoadParams
;
1985 PreviousMode
= KeGetPreviousMode();
1988 * Check security privileges
1991 /* FIXME: Uncomment when privileges will be correctly implemented. */
1993 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
1995 DPRINT("Privilege not held\n");
1996 return STATUS_PRIVILEGE_NOT_HELD
;
2000 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2003 if (!NT_SUCCESS(Status
))
2008 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2010 LoadParams
.ServiceName
= &CapturedDriverServiceName
;
2011 LoadParams
.DriverObject
= NULL
;
2012 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
2014 /* Call the load/unload routine, depending on current process */
2015 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
2017 /* Just call right away */
2018 IopLoadUnloadDriver(&LoadParams
);
2022 /* Load/Unload must be called from system process */
2023 ExInitializeWorkItem(&LoadParams
.WorkItem
,
2024 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
2025 (PVOID
)&LoadParams
);
2028 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
2030 /* And wait when it completes */
2031 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
2035 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2038 return LoadParams
.Status
;
2044 * Unloads a legacy device driver.
2048 * Name of the service to unload (registry key).
2058 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2060 return IopUnloadDriver(DriverServiceName
, FALSE
);