2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/io/iomgr/driver.c
5 * PURPOSE: Driver Object Management
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Filip Navara (navaraf@reactos.org)
8 * Hervé Poussineau (hpoussin@reactos.org)
11 /* INCLUDES *******************************************************************/
17 /* GLOBALS ********************************************************************/
19 LIST_ENTRY DriverReinitListHead
;
20 KSPIN_LOCK DriverReinitListLock
;
21 PLIST_ENTRY DriverReinitTailEntry
;
23 PLIST_ENTRY DriverBootReinitTailEntry
;
24 LIST_ENTRY DriverBootReinitListHead
;
25 KSPIN_LOCK DriverBootReinitListLock
;
27 UNICODE_STRING IopHardwareDatabaseKey
=
28 RTL_CONSTANT_STRING(L
"\\REGISTRY\\MACHINE\\HARDWARE\\DESCRIPTION\\SYSTEM");
30 POBJECT_TYPE IoDriverObjectType
= NULL
;
32 #define TAG_RTLREGISTRY 'vrqR'
34 extern BOOLEAN ExpInTextModeSetup
;
35 extern BOOLEAN PnpSystemInit
;
38 PLIST_ENTRY IopGroupTable
;
40 /* PRIVATE FUNCTIONS **********************************************************/
43 IopInvalidDeviceRequest(
44 PDEVICE_OBJECT DeviceObject
,
47 Irp
->IoStatus
.Status
= STATUS_INVALID_DEVICE_REQUEST
;
48 Irp
->IoStatus
.Information
= 0;
49 IoCompleteRequest(Irp
, IO_NO_INCREMENT
);
50 return STATUS_INVALID_DEVICE_REQUEST
;
55 IopDeleteDriver(IN PVOID ObjectBody
)
57 PDRIVER_OBJECT DriverObject
= ObjectBody
;
58 PIO_CLIENT_EXTENSION DriverExtension
, NextDriverExtension
;
61 DPRINT1("Deleting driver object '%wZ'\n", &DriverObject
->DriverName
);
63 /* There must be no device objects remaining at this point */
64 ASSERT(!DriverObject
->DeviceObject
);
66 /* Get the extension and loop them */
67 DriverExtension
= IoGetDrvObjExtension(DriverObject
)->
68 ClientDriverExtension
;
69 while (DriverExtension
)
71 /* Get the next one */
72 NextDriverExtension
= DriverExtension
->NextExtension
;
73 ExFreePoolWithTag(DriverExtension
, TAG_DRIVER_EXTENSION
);
76 DriverExtension
= NextDriverExtension
;
79 /* Check if the driver image is still loaded */
80 if (DriverObject
->DriverSection
)
83 MmUnloadSystemImage(DriverObject
->DriverSection
);
86 /* Check if it has a name */
87 if (DriverObject
->DriverName
.Buffer
)
90 ExFreePool(DriverObject
->DriverName
.Buffer
);
93 #if 0 /* See a bit of hack in IopCreateDriver */
94 /* Check if it has a service key name */
95 if (DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
)
98 ExFreePool(DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
);
105 PDRIVER_OBJECT
*DriverObject
,
106 PUNICODE_STRING ServiceName
,
109 PDRIVER_OBJECT Object
;
110 WCHAR NameBuffer
[MAX_PATH
];
111 UNICODE_STRING DriverName
;
114 DPRINT("IopGetDriverObject(%p '%wZ' %x)\n",
115 DriverObject
, ServiceName
, FileSystem
);
117 *DriverObject
= NULL
;
119 /* Create ModuleName string */
120 if (ServiceName
== NULL
|| ServiceName
->Buffer
== NULL
)
121 /* We don't know which DriverObject we have to open */
122 return STATUS_INVALID_PARAMETER_2
;
124 DriverName
.Buffer
= NameBuffer
;
125 DriverName
.Length
= 0;
126 DriverName
.MaximumLength
= sizeof(NameBuffer
);
128 if (FileSystem
== TRUE
)
129 RtlAppendUnicodeToString(&DriverName
, FILESYSTEM_ROOT_NAME
);
131 RtlAppendUnicodeToString(&DriverName
, DRIVER_ROOT_NAME
);
132 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
134 DPRINT("Driver name: '%wZ'\n", &DriverName
);
136 /* Open driver object */
137 Status
= ObReferenceObjectByName(
139 OBJ_OPENIF
| OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, /* Attributes */
140 NULL
, /* PassedAccessState */
141 0, /* DesiredAccess */
144 NULL
, /* ParseContext */
147 if (!NT_SUCCESS(Status
))
149 DPRINT("Failed to reference driver object, status=0x%08x\n", Status
);
153 *DriverObject
= Object
;
155 DPRINT("Driver Object: %p\n", Object
);
157 return STATUS_SUCCESS
;
162 * TRUE if String2 contains String1 as a suffix.
166 IopSuffixUnicodeString(
167 IN PCUNICODE_STRING String1
,
168 IN PCUNICODE_STRING String2
)
174 if (String2
->Length
< String1
->Length
)
177 Length
= String1
->Length
/ 2;
178 pc1
= String1
->Buffer
;
179 pc2
= &String2
->Buffer
[String2
->Length
/ sizeof(WCHAR
) - Length
];
185 if( *pc1
++ != *pc2
++ )
194 * IopDisplayLoadingMessage
196 * Display 'Loading XXX...' message.
202 IopDisplayLoadingMessage(PUNICODE_STRING ServiceName
)
204 CHAR TextBuffer
[256];
205 UNICODE_STRING DotSys
= RTL_CONSTANT_STRING(L
".SYS");
207 if (ExpInTextModeSetup
) return;
208 if (!KeLoaderBlock
) return;
209 RtlUpcaseUnicodeString(ServiceName
, ServiceName
, FALSE
);
210 snprintf(TextBuffer
, sizeof(TextBuffer
),
211 "%s%sSystem32\\Drivers\\%wZ%s\r\n",
212 KeLoaderBlock
->ArcBootDeviceName
,
213 KeLoaderBlock
->NtBootPathName
,
215 IopSuffixUnicodeString(&DotSys
, ServiceName
) ? "" : ".SYS");
216 HalDisplayString(TextBuffer
);
220 * IopNormalizeImagePath
222 * Normalize an image path to contain complete path.
226 * The input path and on exit the result path. ImagePath.Buffer
227 * must be allocated by ExAllocatePool on input. Caller is responsible
228 * for freeing the buffer when it's no longer needed.
231 * Name of the service that ImagePath belongs to.
237 * The input image path isn't freed on error.
242 IopNormalizeImagePath(
243 _Inout_
_When_(return>=0, _At_(ImagePath
->Buffer
, _Post_notnull_
__drv_allocatesMem(Mem
)))
244 PUNICODE_STRING ImagePath
,
245 _In_ PUNICODE_STRING ServiceName
)
247 UNICODE_STRING InputImagePath
;
249 DPRINT("Normalizing image path '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
254 sizeof(UNICODE_STRING
));
256 if (InputImagePath
.Length
== 0)
258 ImagePath
->Length
= 0;
259 ImagePath
->MaximumLength
=
260 (33 * sizeof(WCHAR
)) + ServiceName
->Length
+ sizeof(UNICODE_NULL
);
261 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
262 if (ImagePath
->Buffer
== NULL
)
263 return STATUS_NO_MEMORY
;
265 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\system32\\drivers\\");
266 RtlAppendUnicodeStringToString(ImagePath
, ServiceName
);
267 RtlAppendUnicodeToString(ImagePath
, L
".sys");
269 if (InputImagePath
.Buffer
[0] != L
'\\')
271 ImagePath
->Length
= 0;
272 ImagePath
->MaximumLength
=
273 12 * sizeof(WCHAR
) + InputImagePath
.Length
+ sizeof(UNICODE_NULL
);
274 ImagePath
->Buffer
= ExAllocatePool(NonPagedPool
, ImagePath
->MaximumLength
);
275 if (ImagePath
->Buffer
== NULL
)
276 return STATUS_NO_MEMORY
;
278 RtlAppendUnicodeToString(ImagePath
, L
"\\SystemRoot\\");
279 RtlAppendUnicodeStringToString(ImagePath
, &InputImagePath
);
281 /* Free caller's string */
282 ExFreePoolWithTag(InputImagePath
.Buffer
, TAG_RTLREGISTRY
);
285 DPRINT("Normalized image path is '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
287 return STATUS_SUCCESS
;
291 * IopLoadServiceModule
293 * Load a module specified by registry settings for service.
297 * Name of the service to load.
304 IopLoadServiceModule(
305 IN PUNICODE_STRING ServiceName
,
306 OUT PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
308 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
310 UNICODE_STRING ServiceImagePath
, CCSName
;
312 HANDLE CCSKey
, ServiceKey
;
315 DPRINT("IopLoadServiceModule(%wZ, 0x%p)\n", ServiceName
, ModuleObject
);
317 /* FIXME: This check may be removed once the bug is fixed */
318 if (ServiceName
->Buffer
== NULL
)
320 DPRINT1("If you see this, please report to Fireball or hpoussin!\n");
321 return STATUS_UNSUCCESSFUL
;
324 if (ExpInTextModeSetup
)
326 /* We have no registry, but luckily we know where all the drivers are */
328 /* ServiceStart < 4 is all that matters */
331 /* IopNormalizeImagePath will do all of the work for us if we give it an empty string */
332 ServiceImagePath
.Length
= ServiceImagePath
.MaximumLength
= 0;
333 ServiceImagePath
.Buffer
= NULL
;
337 /* Open CurrentControlSet */
338 RtlInitUnicodeString(&CCSName
,
339 L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services");
340 Status
= IopOpenRegistryKeyEx(&CCSKey
, NULL
, &CCSName
, KEY_READ
);
341 if (!NT_SUCCESS(Status
))
343 DPRINT1("IopOpenRegistryKeyEx() failed for '%wZ' with Status %08X\n",
348 /* Open service key */
349 Status
= IopOpenRegistryKeyEx(&ServiceKey
, CCSKey
, ServiceName
, KEY_READ
);
350 if (!NT_SUCCESS(Status
))
352 DPRINT1("IopOpenRegistryKeyEx() failed for '%wZ' with Status %08X\n",
353 ServiceName
, Status
);
359 * Get information about the service.
362 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
364 RtlInitUnicodeString(&ServiceImagePath
, NULL
);
366 QueryTable
[0].Name
= L
"Start";
367 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
368 QueryTable
[0].EntryContext
= &ServiceStart
;
370 QueryTable
[1].Name
= L
"ImagePath";
371 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
372 QueryTable
[1].EntryContext
= &ServiceImagePath
;
374 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
375 (PWSTR
)ServiceKey
, QueryTable
, NULL
, NULL
);
380 if (!NT_SUCCESS(Status
))
382 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
388 * Normalize the image path for all later processing.
391 Status
= IopNormalizeImagePath(&ServiceImagePath
, ServiceName
);
393 if (!NT_SUCCESS(Status
))
395 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
400 * Case for disabled drivers
403 if (ServiceStart
>= 4)
405 /* We can't load this */
406 Status
= STATUS_DRIVER_UNABLE_TO_LOAD
;
410 DPRINT("Loading module from %wZ\n", &ServiceImagePath
);
411 Status
= MmLoadSystemImage(&ServiceImagePath
, NULL
, NULL
, 0, (PVOID
)ModuleObject
, &BaseAddress
);
412 if (NT_SUCCESS(Status
))
414 IopDisplayLoadingMessage(ServiceName
);
418 ExFreePool(ServiceImagePath
.Buffer
);
421 * Now check if the module was loaded successfully.
424 if (!NT_SUCCESS(Status
))
426 DPRINT("Module loading failed (Status %x)\n", Status
);
429 DPRINT("Module loading (Status %x)\n", Status
);
436 MmFreeDriverInitialization(IN PLDR_DATA_TABLE_ENTRY LdrEntry
);
439 * IopInitializeDriverModule
441 * Initialize a loaded driver.
445 * Pointer to device node.
448 * Module object representing the driver. It can be retrieve by
449 * IopLoadServiceModule.
452 * Name of the service (as in registry).
455 * Set to TRUE for file system drivers.
458 * On successful return this contains the driver object representing
463 IopInitializeDriverModule(
464 IN PDEVICE_NODE DeviceNode
,
465 IN PLDR_DATA_TABLE_ENTRY ModuleObject
,
466 IN PUNICODE_STRING ServiceName
,
467 IN BOOLEAN FileSystemDriver
,
468 OUT PDRIVER_OBJECT
*DriverObject
)
470 const WCHAR ServicesKeyName
[] = L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";
471 WCHAR NameBuffer
[MAX_PATH
];
472 UNICODE_STRING DriverName
;
473 UNICODE_STRING RegistryKey
;
474 PDRIVER_INITIALIZE DriverEntry
;
475 PDRIVER_OBJECT Driver
;
478 DriverEntry
= ModuleObject
->EntryPoint
;
480 if (ServiceName
!= NULL
&& ServiceName
->Length
!= 0)
482 RegistryKey
.Length
= 0;
483 RegistryKey
.MaximumLength
= sizeof(ServicesKeyName
) + ServiceName
->Length
;
484 RegistryKey
.Buffer
= ExAllocatePool(PagedPool
, RegistryKey
.MaximumLength
);
485 if (RegistryKey
.Buffer
== NULL
)
487 return STATUS_INSUFFICIENT_RESOURCES
;
489 RtlAppendUnicodeToString(&RegistryKey
, ServicesKeyName
);
490 RtlAppendUnicodeStringToString(&RegistryKey
, ServiceName
);
494 RtlInitUnicodeString(&RegistryKey
, NULL
);
497 /* Create ModuleName string */
498 if (ServiceName
&& ServiceName
->Length
> 0)
500 if (FileSystemDriver
== TRUE
)
501 wcscpy(NameBuffer
, FILESYSTEM_ROOT_NAME
);
503 wcscpy(NameBuffer
, DRIVER_ROOT_NAME
);
505 RtlInitUnicodeString(&DriverName
, NameBuffer
);
506 DriverName
.MaximumLength
= sizeof(NameBuffer
);
508 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
510 DPRINT("Driver name: '%wZ'\n", &DriverName
);
513 DriverName
.Length
= 0;
515 Status
= IopCreateDriver(
516 DriverName
.Length
> 0 ? &DriverName
: NULL
,
521 RtlFreeUnicodeString(&RegistryKey
);
523 *DriverObject
= Driver
;
524 if (!NT_SUCCESS(Status
))
526 DPRINT("IopCreateDriver() failed (Status 0x%08lx)\n", Status
);
530 MmFreeDriverInitialization((PLDR_DATA_TABLE_ENTRY
)Driver
->DriverSection
);
532 /* Set the driver as initialized */
533 IopReadyDeviceObjects(Driver
);
535 if (PnpSystemInit
) IopReinitializeDrivers();
537 return STATUS_SUCCESS
;
541 * IopAttachFilterDriversCallback
543 * Internal routine used by IopAttachFilterDrivers.
547 IopAttachFilterDriversCallback(
555 PDEVICE_NODE DeviceNode
= Context
;
556 UNICODE_STRING ServiceName
;
558 PLDR_DATA_TABLE_ENTRY ModuleObject
;
559 PDRIVER_OBJECT DriverObject
;
562 for (Filters
= ValueData
;
563 ((ULONG_PTR
)Filters
- (ULONG_PTR
)ValueData
) < ValueLength
&&
565 Filters
+= (ServiceName
.Length
/ sizeof(WCHAR
)) + 1)
567 DPRINT("Filter Driver: %S (%wZ)\n", Filters
, &DeviceNode
->InstancePath
);
569 ServiceName
.Buffer
= Filters
;
570 ServiceName
.MaximumLength
=
571 ServiceName
.Length
= (USHORT
)wcslen(Filters
) * sizeof(WCHAR
);
573 Status
= IopGetDriverObject(&DriverObject
,
576 if (!NT_SUCCESS(Status
))
578 /* Load and initialize the filter driver */
579 Status
= IopLoadServiceModule(&ServiceName
, &ModuleObject
);
580 if (!NT_SUCCESS(Status
))
583 Status
= IopInitializeDriverModule(DeviceNode
, ModuleObject
, &ServiceName
,
584 FALSE
, &DriverObject
);
585 if (!NT_SUCCESS(Status
))
589 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
591 /* Remove extra reference */
592 ObDereferenceObject(DriverObject
);
595 return STATUS_SUCCESS
;
599 * IopAttachFilterDrivers
601 * Load filter drivers for specified device node.
605 * Set to TRUE for loading lower level filters or FALSE for upper
610 IopAttachFilterDrivers(
611 PDEVICE_NODE DeviceNode
,
614 RTL_QUERY_REGISTRY_TABLE QueryTable
[2] = { { NULL
, 0, NULL
, NULL
, 0, NULL
, 0 }, };
615 UNICODE_STRING Class
;
616 WCHAR ClassBuffer
[40];
617 UNICODE_STRING EnumRoot
= RTL_CONSTANT_STRING(ENUM_ROOT
);
618 HANDLE EnumRootKey
, SubKey
;
621 /* Open enumeration root key */
622 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
623 &EnumRoot
, KEY_READ
);
624 if (!NT_SUCCESS(Status
))
626 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
631 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
632 &DeviceNode
->InstancePath
, KEY_READ
);
633 if (!NT_SUCCESS(Status
))
635 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
636 ZwClose(EnumRootKey
);
641 * First load the device filters
643 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
645 QueryTable
[0].Name
= L
"LowerFilters";
647 QueryTable
[0].Name
= L
"UpperFilters";
648 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
650 RtlQueryRegistryValues(
658 * Now get the class GUID
661 Class
.MaximumLength
= 40 * sizeof(WCHAR
);
662 Class
.Buffer
= ClassBuffer
;
663 QueryTable
[0].QueryRoutine
= NULL
;
664 QueryTable
[0].Name
= L
"ClassGUID";
665 QueryTable
[0].EntryContext
= &Class
;
666 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
| RTL_QUERY_REGISTRY_DIRECT
;
668 Status
= RtlQueryRegistryValues(
677 ZwClose(EnumRootKey
);
680 * Load the class filter driver
682 if (NT_SUCCESS(Status
))
684 UNICODE_STRING ControlClass
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class");
686 Status
= IopOpenRegistryKeyEx(&EnumRootKey
, NULL
,
687 &ControlClass
, KEY_READ
);
688 if (!NT_SUCCESS(Status
))
690 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
695 Status
= IopOpenRegistryKeyEx(&SubKey
, EnumRootKey
,
697 if (!NT_SUCCESS(Status
))
699 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
700 ZwClose(EnumRootKey
);
704 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
706 QueryTable
[0].Name
= L
"LowerFilters";
708 QueryTable
[0].Name
= L
"UpperFilters";
709 QueryTable
[0].EntryContext
= NULL
;
710 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
;
712 RtlQueryRegistryValues(
721 ZwClose(EnumRootKey
);
724 return STATUS_SUCCESS
;
729 MiResolveImageReferences(IN PVOID ImageBase
,
730 IN PUNICODE_STRING ImageFileDirectory
,
731 IN PUNICODE_STRING NamePrefix OPTIONAL
,
732 OUT PCHAR
*MissingApi
,
733 OUT PWCHAR
*MissingDriver
,
734 OUT PLOAD_IMPORTS
*LoadImports
);
737 // Used for images already loaded (boot drivers)
742 LdrProcessDriverModule(PLDR_DATA_TABLE_ENTRY LdrEntry
,
743 PUNICODE_STRING FileName
,
744 PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
747 UNICODE_STRING BaseName
, BaseDirectory
;
748 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
749 PCHAR MissingApiName
, Buffer
;
750 PWCHAR MissingDriverName
;
751 PVOID DriverBase
= LdrEntry
->DllBase
;
753 /* Allocate a buffer we'll use for names */
754 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
758 return STATUS_INSUFFICIENT_RESOURCES
;
761 /* Check for a separator */
762 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
767 /* Loop the path until we get to the base name */
768 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
769 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
772 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
773 BaseLength
*= sizeof(WCHAR
);
775 /* Setup the string */
776 BaseName
.Length
= (USHORT
)BaseLength
;
781 /* Otherwise, we already have a base name */
782 BaseName
.Length
= FileName
->Length
;
783 BaseName
.Buffer
= FileName
->Buffer
;
786 /* Setup the maximum length */
787 BaseName
.MaximumLength
= BaseName
.Length
;
789 /* Now compute the base directory */
790 BaseDirectory
= *FileName
;
791 BaseDirectory
.Length
-= BaseName
.Length
;
792 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
794 /* Resolve imports */
795 MissingApiName
= Buffer
;
796 Status
= MiResolveImageReferences(DriverBase
,
803 /* Free the temporary buffer */
804 ExFreePoolWithTag(Buffer
, TAG_LDR_WSTR
);
806 /* Check the result of the imports resolution */
807 if (!NT_SUCCESS(Status
)) return Status
;
810 *ModuleObject
= LdrEntry
;
811 return STATUS_SUCCESS
;
815 * IopInitializeBuiltinDriver
817 * Initialize a driver that is already loaded in memory.
823 IopInitializeBuiltinDriver(IN PLDR_DATA_TABLE_ENTRY BootLdrEntry
)
825 PDEVICE_NODE DeviceNode
;
826 PDRIVER_OBJECT DriverObject
;
828 PWCHAR FileNameWithoutPath
;
829 LPWSTR FileExtension
;
830 PUNICODE_STRING ModuleName
= &BootLdrEntry
->BaseDllName
;
831 PLDR_DATA_TABLE_ENTRY LdrEntry
;
832 PLIST_ENTRY NextEntry
;
833 UNICODE_STRING ServiceName
;
836 * Display 'Loading XXX...' message
838 IopDisplayLoadingMessage(ModuleName
);
839 InbvIndicateProgress();
842 * Generate filename without path (not needed by freeldr)
844 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
845 if (FileNameWithoutPath
== NULL
)
847 FileNameWithoutPath
= ModuleName
->Buffer
;
851 FileNameWithoutPath
++;
855 * Strip the file extension from ServiceName
857 RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
858 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
859 if (FileExtension
!= NULL
)
861 ServiceName
.Length
-= (USHORT
)wcslen(FileExtension
) * sizeof(WCHAR
);
862 FileExtension
[0] = 0;
866 * Determine the right device object
868 /* Use IopRootDeviceNode for now */
869 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
870 if (!NT_SUCCESS(Status
))
872 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
876 /* Lookup the new Ldr entry in PsLoadedModuleList */
877 NextEntry
= PsLoadedModuleList
.Flink
;
878 while (NextEntry
!= &PsLoadedModuleList
)
880 LdrEntry
= CONTAINING_RECORD(NextEntry
,
881 LDR_DATA_TABLE_ENTRY
,
883 if (RtlEqualUnicodeString(ModuleName
, &LdrEntry
->BaseDllName
, TRUE
))
888 NextEntry
= NextEntry
->Flink
;
890 NT_ASSERT(NextEntry
!= &PsLoadedModuleList
);
893 * Initialize the driver
895 Status
= IopInitializeDriverModule(DeviceNode
, LdrEntry
,
896 &DeviceNode
->ServiceName
, FALSE
, &DriverObject
);
898 if (!NT_SUCCESS(Status
))
900 IopFreeDeviceNode(DeviceNode
);
904 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
905 if (NT_SUCCESS(Status
))
907 Status
= IopStartDevice(DeviceNode
);
910 /* Remove extra reference from IopInitializeDriverModule */
911 ObDereferenceObject(DriverObject
);
917 * IopInitializeBootDrivers
919 * Initialize boot drivers and free memory for boot files.
930 IopInitializeBootDrivers(VOID
)
932 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
933 PLDR_DATA_TABLE_ENTRY LdrEntry
;
934 PDEVICE_NODE DeviceNode
;
935 PDRIVER_OBJECT DriverObject
;
936 LDR_DATA_TABLE_ENTRY ModuleObject
;
938 UNICODE_STRING DriverName
;
940 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
942 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
943 DPRINT("IopInitializeBootDrivers()\n");
945 /* Use IopRootDeviceNode for now */
946 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
947 if (!NT_SUCCESS(Status
)) return;
949 /* Setup the module object for the RAW FS Driver */
950 ModuleObject
.DllBase
= NULL
;
951 ModuleObject
.SizeOfImage
= 0;
952 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
953 RtlInitUnicodeString(&DriverName
, L
"RAW");
956 Status
= IopInitializeDriverModule(DeviceNode
,
961 if (!NT_SUCCESS(Status
))
964 IopFreeDeviceNode(DeviceNode
);
968 /* Now initialize the associated device */
969 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
970 if (!NT_SUCCESS(Status
))
973 IopFreeDeviceNode(DeviceNode
);
974 ObDereferenceObject(DriverObject
);
979 Status
= IopStartDevice(DeviceNode
);
980 if (!NT_SUCCESS(Status
))
983 IopFreeDeviceNode(DeviceNode
);
984 ObDereferenceObject(DriverObject
);
988 /* Get highest group order index */
989 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
990 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
992 /* Allocate the group table */
993 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
994 IopGroupIndex
* sizeof(LIST_ENTRY
),
996 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
998 /* Initialize the group table lists */
999 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
1001 /* Loop the boot modules */
1002 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
1003 NextEntry
= ListHead
->Flink
;
1004 while (ListHead
!= NextEntry
)
1007 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1008 LDR_DATA_TABLE_ENTRY
,
1011 /* Check if the DLL needs to be initialized */
1012 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
1014 /* Call its entrypoint */
1015 MmCallDllInitialize(LdrEntry
, NULL
);
1018 /* Go to the next driver */
1019 NextEntry
= NextEntry
->Flink
;
1022 /* Loop the boot drivers */
1023 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
1024 NextEntry
= ListHead
->Flink
;
1025 while (ListHead
!= NextEntry
)
1028 BootEntry
= CONTAINING_RECORD(NextEntry
,
1029 BOOT_DRIVER_LIST_ENTRY
,
1032 /* Get the driver loader entry */
1033 LdrEntry
= BootEntry
->LdrEntry
;
1035 /* Allocate our internal accounting structure */
1036 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
1037 sizeof(DRIVER_INFORMATION
),
1041 /* Zero it and initialize it */
1042 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1043 InitializeListHead(&DriverInfo
->Link
);
1044 DriverInfo
->DataTableEntry
= BootEntry
;
1046 /* Open the registry key */
1047 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1049 &BootEntry
->RegistryPath
,
1051 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1052 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1054 /* Save the handle */
1055 DriverInfo
->ServiceHandle
= KeyHandle
;
1057 /* Get the group oder index */
1058 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1060 /* Get the tag position */
1061 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1063 /* Insert it into the list, at the right place */
1064 ASSERT(Index
< IopGroupIndex
);
1065 NextEntry2
= IopGroupTable
[Index
].Flink
;
1066 while (NextEntry2
!= &IopGroupTable
[Index
])
1068 /* Get the driver info */
1069 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1073 /* Check if we found the right tag position */
1074 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1081 NextEntry2
= NextEntry2
->Flink
;
1084 /* Insert us right before the next entry */
1085 NextEntry2
= NextEntry2
->Blink
;
1086 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1090 /* Go to the next driver */
1091 NextEntry
= NextEntry
->Flink
;
1094 /* Loop each group index */
1095 for (i
= 0; i
< IopGroupIndex
; i
++)
1097 /* Loop each group table */
1098 NextEntry
= IopGroupTable
[i
].Flink
;
1099 while (NextEntry
!= &IopGroupTable
[i
])
1102 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1106 /* Get the driver loader entry */
1107 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1110 IopInitializeBuiltinDriver(LdrEntry
);
1113 NextEntry
= NextEntry
->Flink
;
1117 /* In old ROS, the loader list became empty after this point. Simulate. */
1118 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1124 IopInitializeSystemDrivers(VOID
)
1126 PUNICODE_STRING
*DriverList
, *SavedList
;
1128 /* No system drivers on the boot cd */
1129 if (KeLoaderBlock
->SetupLdrBlock
) return;
1131 /* Get the driver list */
1132 SavedList
= DriverList
= CmGetSystemDriverList();
1138 /* Load the driver */
1139 ZwLoadDriver(*DriverList
);
1141 /* Free the entry */
1142 RtlFreeUnicodeString(*DriverList
);
1143 ExFreePool(*DriverList
);
1146 InbvIndicateProgress();
1151 ExFreePool(SavedList
);
1157 * Unloads a device driver.
1161 * Name of the service to unload (registry key).
1164 * Whether to unload Plug & Plug or only legacy drivers. If this
1165 * parameter is set to FALSE, the routine will unload only legacy
1172 * Guard the whole function by SEH.
1176 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1178 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1179 UNICODE_STRING ImagePath
;
1180 UNICODE_STRING ServiceName
;
1181 UNICODE_STRING ObjectName
;
1182 PDRIVER_OBJECT DriverObject
;
1183 PDEVICE_OBJECT DeviceObject
;
1184 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1185 LOAD_UNLOAD_PARAMS LoadParams
;
1188 BOOLEAN SafeToUnload
= TRUE
;
1190 DPRINT("IopUnloadDriver('%wZ', %u)\n", DriverServiceName
, UnloadPnpDrivers
);
1195 * Get the service name from the registry key name
1198 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1200 Start
= DriverServiceName
->Buffer
;
1204 RtlInitUnicodeString(&ServiceName
, Start
);
1207 * Construct the driver object name
1210 ObjectName
.Length
= ((USHORT
)wcslen(Start
) + 8) * sizeof(WCHAR
);
1211 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1212 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1213 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1214 wcscpy(ObjectName
.Buffer
, DRIVER_ROOT_NAME
);
1215 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1216 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1219 * Find the driver object
1221 Status
= ObReferenceObjectByName(&ObjectName
,
1228 (PVOID
*)&DriverObject
);
1230 if (!NT_SUCCESS(Status
))
1232 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1233 ExFreePool(ObjectName
.Buffer
);
1238 * Free the buffer for driver object name
1240 ExFreePool(ObjectName
.Buffer
);
1242 /* Check that driver is not already unloading */
1243 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1245 DPRINT1("Driver deletion pending\n");
1246 ObDereferenceObject(DriverObject
);
1247 return STATUS_DELETE_PENDING
;
1251 * Get path of service...
1254 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1256 RtlInitUnicodeString(&ImagePath
, NULL
);
1258 QueryTable
[0].Name
= L
"ImagePath";
1259 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1260 QueryTable
[0].EntryContext
= &ImagePath
;
1262 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1263 DriverServiceName
->Buffer
, QueryTable
, NULL
, NULL
);
1265 if (!NT_SUCCESS(Status
))
1267 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1268 ObDereferenceObject(DriverObject
);
1273 * Normalize the image path for all later processing.
1276 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1278 if (!NT_SUCCESS(Status
))
1280 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1281 ObDereferenceObject(DriverObject
);
1286 * Free the service path
1289 ExFreePool(ImagePath
.Buffer
);
1292 * Unload the module and release the references to the device object
1295 /* Call the load/unload routine, depending on current process */
1296 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
&&
1297 (UnloadPnpDrivers
|| (DriverObject
->Flags
& DRVO_LEGACY_DRIVER
)))
1299 /* Loop through each device object of the driver
1300 and set DOE_UNLOAD_PENDING flag */
1301 DeviceObject
= DriverObject
->DeviceObject
;
1302 while (DeviceObject
)
1304 /* Set the unload pending flag for the device */
1305 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1306 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1308 /* Make sure there are no attached devices or no reference counts */
1309 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1311 /* Not safe to unload */
1312 DPRINT1("Drivers device object is referenced or has attached devices\n");
1314 SafeToUnload
= FALSE
;
1317 DeviceObject
= DeviceObject
->NextDevice
;
1320 /* If not safe to unload, then return success */
1323 ObDereferenceObject(DriverObject
);
1324 return STATUS_SUCCESS
;
1327 DPRINT1("Unloading driver '%wZ' (manual)\n", &DriverObject
->DriverName
);
1329 /* Set the unload invoked flag */
1330 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1332 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
1334 /* Just call right away */
1335 (*DriverObject
->DriverUnload
)(DriverObject
);
1339 /* Load/Unload must be called from system process */
1341 /* Prepare parameters block */
1342 LoadParams
.DriverObject
= DriverObject
;
1343 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1345 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1346 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
1347 (PVOID
)&LoadParams
);
1350 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1352 /* And wait when it completes */
1353 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
1357 /* Mark the driver object temporary, so it could be deleted later */
1358 ObMakeTemporaryObject(DriverObject
);
1360 /* Dereference it 2 times */
1361 ObDereferenceObject(DriverObject
);
1362 ObDereferenceObject(DriverObject
);
1364 return STATUS_SUCCESS
;
1368 DPRINT1("No DriverUnload function! '%wZ' will not be unloaded!\n", &DriverObject
->DriverName
);
1370 /* Dereference one time (refd inside this function) */
1371 ObDereferenceObject(DriverObject
);
1373 /* Return unloading failure */
1374 return STATUS_INVALID_DEVICE_REQUEST
;
1380 IopReinitializeDrivers(VOID
)
1382 PDRIVER_REINIT_ITEM ReinitItem
;
1385 /* Get the first entry and start looping */
1386 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1387 &DriverReinitListLock
);
1391 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1393 /* Increment reinitialization counter */
1394 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1396 /* Remove the device object flag */
1397 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1399 /* Call the routine */
1400 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1401 ReinitItem
->Context
,
1402 ReinitItem
->DriverObject
->
1403 DriverExtension
->Count
);
1405 /* Free the entry */
1408 /* Move to the next one */
1409 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1410 &DriverReinitListLock
);
1416 IopReinitializeBootDrivers(VOID
)
1418 PDRIVER_REINIT_ITEM ReinitItem
;
1421 /* Get the first entry and start looping */
1422 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1423 &DriverBootReinitListLock
);
1427 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1429 /* Increment reinitialization counter */
1430 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1432 /* Remove the device object flag */
1433 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1435 /* Call the routine */
1436 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1437 ReinitItem
->Context
,
1438 ReinitItem
->DriverObject
->
1439 DriverExtension
->Count
);
1441 /* Free the entry */
1444 /* Move to the next one */
1445 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1446 &DriverBootReinitListLock
);
1452 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1453 IN PDRIVER_INITIALIZE InitializationFunction
,
1454 IN PUNICODE_STRING RegistryPath
,
1455 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1456 OUT PDRIVER_OBJECT
*pDriverObject
)
1458 WCHAR NameBuffer
[100];
1460 UNICODE_STRING LocalDriverName
;
1462 OBJECT_ATTRIBUTES ObjectAttributes
;
1464 PDRIVER_OBJECT DriverObject
;
1465 UNICODE_STRING ServiceKeyName
;
1467 ULONG i
, RetryCount
= 0;
1470 /* First, create a unique name for the driver if we don't have one */
1473 /* Create a random name and set up the string*/
1474 NameLength
= (USHORT
)swprintf(NameBuffer
,
1475 DRIVER_ROOT_NAME L
"%08u",
1477 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1478 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1479 LocalDriverName
.Buffer
= NameBuffer
;
1483 /* So we can avoid another code path, use a local var */
1484 LocalDriverName
= *DriverName
;
1487 /* Initialize the Attributes */
1488 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1489 InitializeObjectAttributes(&ObjectAttributes
,
1491 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
,
1495 /* Create the Object */
1496 Status
= ObCreateObject(KernelMode
,
1504 (PVOID
*)&DriverObject
);
1505 if (!NT_SUCCESS(Status
)) return Status
;
1507 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1509 /* Set up the Object */
1510 RtlZeroMemory(DriverObject
, ObjectSize
);
1511 DriverObject
->Type
= IO_TYPE_DRIVER
;
1512 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1513 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;
1514 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1515 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1516 DriverObject
->DriverInit
= InitializationFunction
;
1517 DriverObject
->DriverSection
= ModuleObject
;
1518 /* Loop all Major Functions */
1519 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1521 /* Invalidate each function */
1522 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1525 /* Set up the service key name buffer */
1526 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1527 LocalDriverName
.Length
+
1530 if (!ServiceKeyName
.Buffer
)
1533 ObMakeTemporaryObject(DriverObject
);
1534 ObDereferenceObject(DriverObject
);
1535 return STATUS_INSUFFICIENT_RESOURCES
;
1538 /* Fill out the key data and copy the buffer */
1539 ServiceKeyName
.Length
= LocalDriverName
.Length
;
1540 ServiceKeyName
.MaximumLength
= LocalDriverName
.MaximumLength
;
1541 RtlCopyMemory(ServiceKeyName
.Buffer
,
1542 LocalDriverName
.Buffer
,
1543 LocalDriverName
.Length
);
1545 /* Null-terminate it and set it */
1546 ServiceKeyName
.Buffer
[ServiceKeyName
.Length
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1547 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1549 /* Also store it in the Driver Object. This is a bit of a hack. */
1550 RtlCopyMemory(&DriverObject
->DriverName
,
1552 sizeof(UNICODE_STRING
));
1554 /* Add the Object and get its handle */
1555 Status
= ObInsertObject(DriverObject
,
1562 /* Eliminate small possibility when this function is called more than
1563 once in a row, and KeTickCount doesn't get enough time to change */
1564 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1570 if (!NT_SUCCESS(Status
)) return Status
;
1572 /* Now reference it */
1573 Status
= ObReferenceObjectByHandle(hDriver
,
1577 (PVOID
*)&DriverObject
,
1580 /* Close the extra handle */
1583 if (!NT_SUCCESS(Status
))
1586 ObMakeTemporaryObject(DriverObject
);
1587 ObDereferenceObject(DriverObject
);
1591 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1592 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1593 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1595 /* Finally, call its init function */
1596 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1597 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1598 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1599 if (!NT_SUCCESS(Status
))
1601 /* If it didn't work, then kill the object */
1602 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1603 DriverObject
->DriverSection
= NULL
;
1604 ObMakeTemporaryObject(DriverObject
);
1605 ObDereferenceObject(DriverObject
);
1610 /* Returns to caller the object */
1611 *pDriverObject
= DriverObject
;
1614 /* We're going to say if we don't have any DOs from DriverEntry, then we're not legacy.
1615 * Other parts of the I/O manager depend on this behavior */
1616 if (!DriverObject
->DeviceObject
) DriverObject
->Flags
&= ~DRVO_LEGACY_DRIVER
;
1618 /* Loop all Major Functions */
1619 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1622 * Make sure the driver didn't set any dispatch entry point to NULL!
1623 * Doing so is illegal; drivers shouldn't touch entry points they
1627 /* Check if it did so anyway */
1628 if (!DriverObject
->MajorFunction
[i
])
1630 /* Print a warning in the debug log */
1631 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%lu] to NULL!\n",
1632 &DriverObject
->DriverName
, i
);
1635 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1639 /* Return the Status */
1643 /* PUBLIC FUNCTIONS ***********************************************************/
1650 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1651 IN PDRIVER_INITIALIZE InitializationFunction
)
1653 PDRIVER_OBJECT DriverObject
;
1654 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, NULL
, &DriverObject
);
1662 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1664 /* Simply dereference the Object */
1665 ObDereferenceObject(DriverObject
);
1673 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1674 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1677 PDRIVER_REINIT_ITEM ReinitItem
;
1679 /* Allocate the entry */
1680 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1681 sizeof(DRIVER_REINIT_ITEM
),
1683 if (!ReinitItem
) return;
1686 ReinitItem
->DriverObject
= DriverObject
;
1687 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1688 ReinitItem
->Context
= Context
;
1690 /* Set the Driver Object flag and insert the entry into the list */
1691 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1692 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1693 &ReinitItem
->ItemEntry
,
1694 &DriverBootReinitListLock
);
1702 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1703 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1706 PDRIVER_REINIT_ITEM ReinitItem
;
1708 /* Allocate the entry */
1709 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1710 sizeof(DRIVER_REINIT_ITEM
),
1712 if (!ReinitItem
) return;
1715 ReinitItem
->DriverObject
= DriverObject
;
1716 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1717 ReinitItem
->Context
= Context
;
1719 /* Set the Driver Object flag and insert the entry into the list */
1720 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1721 ExInterlockedInsertTailList(&DriverReinitListHead
,
1722 &ReinitItem
->ItemEntry
,
1723 &DriverReinitListLock
);
1731 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1732 IN PVOID ClientIdentificationAddress
,
1733 IN ULONG DriverObjectExtensionSize
,
1734 OUT PVOID
*DriverObjectExtension
)
1737 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1738 BOOLEAN Inserted
= FALSE
;
1740 /* Assume failure */
1741 *DriverObjectExtension
= NULL
;
1743 /* Allocate the extension */
1744 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1745 sizeof(IO_CLIENT_EXTENSION
) +
1746 DriverObjectExtensionSize
,
1747 TAG_DRIVER_EXTENSION
);
1748 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1750 /* Clear the extension for teh caller */
1751 RtlZeroMemory(NewDriverExtension
,
1752 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1755 OldIrql
= KeRaiseIrqlToDpcLevel();
1757 /* Fill out the extension */
1758 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1760 /* Loop the current extensions */
1761 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1762 ClientDriverExtension
;
1763 while (DriverExtensions
)
1765 /* Check if the identifier matches */
1766 if (DriverExtensions
->ClientIdentificationAddress
==
1767 ClientIdentificationAddress
)
1769 /* We have a collision, break out */
1773 /* Go to the next one */
1774 DriverExtensions
= DriverExtensions
->NextExtension
;
1777 /* Check if we didn't collide */
1778 if (!DriverExtensions
)
1780 /* Link this one in */
1781 NewDriverExtension
->NextExtension
=
1782 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1783 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1788 /* Release the lock */
1789 KeLowerIrql(OldIrql
);
1791 /* Check if insertion failed */
1794 /* Free the entry and fail */
1795 ExFreePoolWithTag(NewDriverExtension
, TAG_DRIVER_EXTENSION
);
1796 return STATUS_OBJECT_NAME_COLLISION
;
1799 /* Otherwise, return the pointer */
1800 *DriverObjectExtension
= NewDriverExtension
+ 1;
1801 return STATUS_SUCCESS
;
1809 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1810 IN PVOID ClientIdentificationAddress
)
1813 PIO_CLIENT_EXTENSION DriverExtensions
;
1816 OldIrql
= KeRaiseIrqlToDpcLevel();
1818 /* Loop the list until we find the right one */
1819 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1820 while (DriverExtensions
)
1822 /* Check for a match */
1823 if (DriverExtensions
->ClientIdentificationAddress
==
1824 ClientIdentificationAddress
)
1831 DriverExtensions
= DriverExtensions
->NextExtension
;
1835 KeLowerIrql(OldIrql
);
1837 /* Return nothing or the extension */
1838 if (!DriverExtensions
) return NULL
;
1839 return DriverExtensions
+ 1;
1843 IopLoadUnloadDriver(PLOAD_UNLOAD_PARAMS LoadParams
)
1845 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1846 UNICODE_STRING ImagePath
;
1847 UNICODE_STRING ServiceName
;
1850 PDEVICE_NODE DeviceNode
;
1851 PDRIVER_OBJECT DriverObject
;
1852 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1856 /* Check if it's an unload request */
1857 if (LoadParams
->DriverObject
)
1859 (*LoadParams
->DriverObject
->DriverUnload
)(LoadParams
->DriverObject
);
1861 /* Return success and signal the event */
1862 LoadParams
->Status
= STATUS_SUCCESS
;
1863 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1867 RtlInitUnicodeString(&ImagePath
, NULL
);
1870 * Get the service name from the registry key name.
1872 ASSERT(LoadParams
->ServiceName
->Length
>= sizeof(WCHAR
));
1874 ServiceName
= *LoadParams
->ServiceName
;
1875 cur
= LoadParams
->ServiceName
->Buffer
+
1876 (LoadParams
->ServiceName
->Length
/ sizeof(WCHAR
)) - 1;
1877 while (LoadParams
->ServiceName
->Buffer
!= cur
)
1881 ServiceName
.Buffer
= cur
+ 1;
1882 ServiceName
.Length
= LoadParams
->ServiceName
->Length
-
1883 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1884 (ULONG_PTR
)LoadParams
->ServiceName
->Buffer
);
1894 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1896 RtlInitUnicodeString(&ImagePath
, NULL
);
1898 QueryTable
[0].Name
= L
"Type";
1899 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1900 QueryTable
[0].EntryContext
= &Type
;
1902 QueryTable
[1].Name
= L
"ImagePath";
1903 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1904 QueryTable
[1].EntryContext
= &ImagePath
;
1906 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1907 LoadParams
->ServiceName
->Buffer
,
1908 QueryTable
, NULL
, NULL
);
1909 if (!NT_SUCCESS(Status
))
1911 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1912 if (ImagePath
.Buffer
) ExFreePool(ImagePath
.Buffer
);
1913 LoadParams
->Status
= Status
;
1914 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1919 * Normalize the image path for all later processing.
1922 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1923 if (!NT_SUCCESS(Status
))
1925 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1926 LoadParams
->Status
= Status
;
1927 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1931 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1932 DPRINT("Type: %lx\n", Type
);
1935 * Get existing DriverObject pointer (in case the driver
1936 * has already been loaded and initialized).
1938 Status
= IopGetDriverObject(&DriverObject
,
1940 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1941 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
1943 if (!NT_SUCCESS(Status
))
1946 * Load the driver module
1949 DPRINT("Loading module from %wZ\n", &ImagePath
);
1950 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
1951 if (!NT_SUCCESS(Status
))
1953 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
1954 LoadParams
->Status
= Status
;
1955 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1960 * Initialize the driver module if it's loaded for the first time
1962 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
1963 if (!NT_SUCCESS(Status
))
1965 DPRINT1("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
1966 MmUnloadSystemImage(ModuleObject
);
1967 LoadParams
->Status
= Status
;
1968 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1972 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
1974 Status
= IopInitializeDriverModule(DeviceNode
,
1976 &DeviceNode
->ServiceName
,
1977 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1978 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
1980 if (!NT_SUCCESS(Status
))
1982 DPRINT1("IopInitializeDriverModule() failed (Status %lx)\n", Status
);
1983 MmUnloadSystemImage(ModuleObject
);
1984 IopFreeDeviceNode(DeviceNode
);
1985 LoadParams
->Status
= Status
;
1986 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1990 /* Initialize and start device */
1991 IopInitializeDevice(DeviceNode
, DriverObject
);
1992 Status
= IopStartDevice(DeviceNode
);
1996 DPRINT("DriverObject already exist in ObjectManager\n");
1997 Status
= STATUS_IMAGE_ALREADY_LOADED
;
1999 /* IopGetDriverObject references the DriverObject, so dereference it */
2000 ObDereferenceObject(DriverObject
);
2003 /* Pass status to the caller and signal the event */
2004 LoadParams
->Status
= Status
;
2005 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
2011 * Loads a device driver.
2015 * Name of the service to load (registry key).
2024 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
2026 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
2027 KPROCESSOR_MODE PreviousMode
;
2028 LOAD_UNLOAD_PARAMS LoadParams
;
2033 PreviousMode
= KeGetPreviousMode();
2036 * Check security privileges
2039 /* FIXME: Uncomment when privileges will be correctly implemented. */
2041 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
2043 DPRINT("Privilege not held\n");
2044 return STATUS_PRIVILEGE_NOT_HELD
;
2048 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2051 if (!NT_SUCCESS(Status
))
2056 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2058 LoadParams
.ServiceName
= &CapturedDriverServiceName
;
2059 LoadParams
.DriverObject
= NULL
;
2060 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
2062 /* Call the load/unload routine, depending on current process */
2063 if (PsGetCurrentProcess() == PsInitialSystemProcess
)
2065 /* Just call right away */
2066 IopLoadUnloadDriver(&LoadParams
);
2070 /* Load/Unload must be called from system process */
2071 ExInitializeWorkItem(&LoadParams
.WorkItem
,
2072 (PWORKER_THREAD_ROUTINE
)IopLoadUnloadDriver
,
2073 (PVOID
)&LoadParams
);
2076 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
2078 /* And wait when it completes */
2079 KeWaitForSingleObject(&LoadParams
.Event
, UserRequest
, KernelMode
,
2083 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2086 return LoadParams
.Status
;
2092 * Unloads a legacy device driver.
2096 * Name of the service to unload (registry key).
2106 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2108 return IopUnloadDriver(DriverServiceName
, FALSE
);