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 ERESOURCE IopDriverLoadResource
;
21 LIST_ENTRY DriverReinitListHead
;
22 KSPIN_LOCK DriverReinitListLock
;
23 PLIST_ENTRY DriverReinitTailEntry
;
25 PLIST_ENTRY DriverBootReinitTailEntry
;
26 LIST_ENTRY DriverBootReinitListHead
;
27 KSPIN_LOCK DriverBootReinitListLock
;
29 UNICODE_STRING IopHardwareDatabaseKey
=
30 RTL_CONSTANT_STRING(L
"\\REGISTRY\\MACHINE\\HARDWARE\\DESCRIPTION\\SYSTEM");
32 POBJECT_TYPE IoDriverObjectType
= NULL
;
34 #define TAG_RTLREGISTRY 'vrqR'
36 extern BOOLEAN ExpInTextModeSetup
;
37 extern BOOLEAN PnpSystemInit
;
40 PLIST_ENTRY IopGroupTable
;
42 /* PRIVATE FUNCTIONS **********************************************************/
46 IopInvalidDeviceRequest(
47 PDEVICE_OBJECT DeviceObject
,
50 Irp
->IoStatus
.Status
= STATUS_INVALID_DEVICE_REQUEST
;
51 Irp
->IoStatus
.Information
= 0;
52 IoCompleteRequest(Irp
, IO_NO_INCREMENT
);
53 return STATUS_INVALID_DEVICE_REQUEST
;
58 IopDeleteDriver(IN PVOID ObjectBody
)
60 PDRIVER_OBJECT DriverObject
= ObjectBody
;
61 PIO_CLIENT_EXTENSION DriverExtension
, NextDriverExtension
;
64 DPRINT1("Deleting driver object '%wZ'\n", &DriverObject
->DriverName
);
66 /* There must be no device objects remaining at this point */
67 ASSERT(!DriverObject
->DeviceObject
);
69 /* Get the extension and loop them */
70 DriverExtension
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
71 while (DriverExtension
)
73 /* Get the next one */
74 NextDriverExtension
= DriverExtension
->NextExtension
;
75 ExFreePoolWithTag(DriverExtension
, TAG_DRIVER_EXTENSION
);
78 DriverExtension
= NextDriverExtension
;
81 /* Check if the driver image is still loaded */
82 if (DriverObject
->DriverSection
)
85 MmUnloadSystemImage(DriverObject
->DriverSection
);
88 /* Check if it has a name */
89 if (DriverObject
->DriverName
.Buffer
)
92 ExFreePool(DriverObject
->DriverName
.Buffer
);
95 /* Check if it has a service key name */
96 if (DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
)
99 ExFreePool(DriverObject
->DriverExtension
->ServiceKeyName
.Buffer
);
106 PDRIVER_OBJECT
*DriverObject
,
107 PUNICODE_STRING ServiceName
,
110 PDRIVER_OBJECT Object
;
111 WCHAR NameBuffer
[MAX_PATH
];
112 UNICODE_STRING DriverName
;
115 DPRINT("IopGetDriverObject(%p '%wZ' %x)\n",
116 DriverObject
, ServiceName
, FileSystem
);
118 ASSERT(ExIsResourceAcquiredExclusiveLite(&IopDriverLoadResource
));
119 *DriverObject
= NULL
;
121 /* Create ModuleName string */
122 if (ServiceName
== NULL
|| ServiceName
->Buffer
== NULL
)
123 /* We don't know which DriverObject we have to open */
124 return STATUS_INVALID_PARAMETER_2
;
126 DriverName
.Buffer
= NameBuffer
;
127 DriverName
.Length
= 0;
128 DriverName
.MaximumLength
= sizeof(NameBuffer
);
130 if (FileSystem
!= FALSE
)
131 RtlAppendUnicodeToString(&DriverName
, FILESYSTEM_ROOT_NAME
);
133 RtlAppendUnicodeToString(&DriverName
, DRIVER_ROOT_NAME
);
134 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
136 DPRINT("Driver name: '%wZ'\n", &DriverName
);
138 /* Open driver object */
139 Status
= ObReferenceObjectByName(&DriverName
,
140 OBJ_OPENIF
| OBJ_KERNEL_HANDLE
| OBJ_CASE_INSENSITIVE
, /* Attributes */
141 NULL
, /* PassedAccessState */
142 0, /* DesiredAccess */
145 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.
200 IopDisplayLoadingMessage(PUNICODE_STRING ServiceName
)
202 CHAR TextBuffer
[256];
203 UNICODE_STRING DotSys
= RTL_CONSTANT_STRING(L
".SYS");
205 if (ExpInTextModeSetup
) return;
206 if (!KeLoaderBlock
) return;
207 RtlUpcaseUnicodeString(ServiceName
, ServiceName
, FALSE
);
208 snprintf(TextBuffer
, sizeof(TextBuffer
),
209 "%s%sSystem32\\Drivers\\%wZ%s\r\n",
210 KeLoaderBlock
->ArcBootDeviceName
,
211 KeLoaderBlock
->NtBootPathName
,
213 IopSuffixUnicodeString(&DotSys
, ServiceName
) ? "" : ".SYS");
214 HalDisplayString(TextBuffer
);
218 * IopNormalizeImagePath
220 * Normalize an image path to contain complete path.
224 * The input path and on exit the result path. ImagePath.Buffer
225 * must be allocated by ExAllocatePool on input. Caller is responsible
226 * for freeing the buffer when it's no longer needed.
229 * Name of the service that ImagePath belongs to.
235 * The input image path isn't freed on error.
239 IopNormalizeImagePath(
240 _Inout_
_When_(return>=0, _At_(ImagePath
->Buffer
, _Post_notnull_
__drv_allocatesMem(Mem
)))
241 PUNICODE_STRING ImagePath
,
242 _In_ PUNICODE_STRING ServiceName
)
244 UNICODE_STRING SystemRootString
= RTL_CONSTANT_STRING(L
"\\SystemRoot\\");
245 UNICODE_STRING DriversPathString
= RTL_CONSTANT_STRING(L
"\\SystemRoot\\System32\\drivers\\");
246 UNICODE_STRING DotSysString
= RTL_CONSTANT_STRING(L
".sys");
247 UNICODE_STRING InputImagePath
;
249 DPRINT("Normalizing image path '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
251 InputImagePath
= *ImagePath
;
252 if (InputImagePath
.Length
== 0)
254 ImagePath
->Length
= 0;
255 ImagePath
->MaximumLength
= DriversPathString
.Length
+
256 ServiceName
->Length
+
257 DotSysString
.Length
+
258 sizeof(UNICODE_NULL
);
259 ImagePath
->Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
260 ImagePath
->MaximumLength
,
262 if (ImagePath
->Buffer
== NULL
)
263 return STATUS_NO_MEMORY
;
265 RtlCopyUnicodeString(ImagePath
, &DriversPathString
);
266 RtlAppendUnicodeStringToString(ImagePath
, ServiceName
);
267 RtlAppendUnicodeStringToString(ImagePath
, &DotSysString
);
269 else if (InputImagePath
.Buffer
[0] != L
'\\')
271 ImagePath
->Length
= 0;
272 ImagePath
->MaximumLength
= SystemRootString
.Length
+
273 InputImagePath
.Length
+
274 sizeof(UNICODE_NULL
);
275 ImagePath
->Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
276 ImagePath
->MaximumLength
,
278 if (ImagePath
->Buffer
== NULL
)
279 return STATUS_NO_MEMORY
;
281 RtlCopyUnicodeString(ImagePath
, &SystemRootString
);
282 RtlAppendUnicodeStringToString(ImagePath
, &InputImagePath
);
284 /* Free caller's string */
285 ExFreePoolWithTag(InputImagePath
.Buffer
, TAG_RTLREGISTRY
);
288 DPRINT("Normalized image path is '%wZ' for service '%wZ'\n", ImagePath
, ServiceName
);
290 return STATUS_SUCCESS
;
294 * IopLoadServiceModule
296 * Load a module specified by registry settings for service.
300 * Name of the service to load.
307 IopLoadServiceModule(
308 IN PUNICODE_STRING ServiceName
,
309 OUT PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
311 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
313 UNICODE_STRING ServiceImagePath
, CCSName
;
315 HANDLE CCSKey
, ServiceKey
;
318 ASSERT(ExIsResourceAcquiredExclusiveLite(&IopDriverLoadResource
));
319 ASSERT(ServiceName
->Length
);
320 DPRINT("IopLoadServiceModule(%wZ, 0x%p)\n", ServiceName
, ModuleObject
);
322 if (ExpInTextModeSetup
)
324 /* We have no registry, but luckily we know where all the drivers are */
326 /* ServiceStart < 4 is all that matters */
329 /* IopNormalizeImagePath will do all of the work for us if we give it an empty string */
330 RtlInitEmptyUnicodeString(&ServiceImagePath
, NULL
, 0);
334 /* Open CurrentControlSet */
335 RtlInitUnicodeString(&CCSName
,
336 L
"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Services");
337 Status
= IopOpenRegistryKeyEx(&CCSKey
, NULL
, &CCSName
, KEY_READ
);
338 if (!NT_SUCCESS(Status
))
340 DPRINT1("IopOpenRegistryKeyEx() failed for '%wZ' with Status %08X\n",
345 /* Open service key */
346 Status
= IopOpenRegistryKeyEx(&ServiceKey
, CCSKey
, ServiceName
, KEY_READ
);
347 if (!NT_SUCCESS(Status
))
349 DPRINT1("IopOpenRegistryKeyEx() failed for '%wZ' with Status %08X\n",
350 ServiceName
, Status
);
356 * Get information about the service.
358 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
360 RtlInitUnicodeString(&ServiceImagePath
, NULL
);
362 QueryTable
[0].Name
= L
"Start";
363 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
364 QueryTable
[0].EntryContext
= &ServiceStart
;
366 QueryTable
[1].Name
= L
"ImagePath";
367 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
368 QueryTable
[1].EntryContext
= &ServiceImagePath
;
370 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
379 if (!NT_SUCCESS(Status
))
381 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
387 * Normalize the image path for all later processing.
389 Status
= IopNormalizeImagePath(&ServiceImagePath
, ServiceName
);
391 if (!NT_SUCCESS(Status
))
393 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
398 * Case for disabled drivers
400 if (ServiceStart
>= 4)
402 /* We can't load this */
403 Status
= STATUS_DRIVER_UNABLE_TO_LOAD
;
407 DPRINT("Loading module from %wZ\n", &ServiceImagePath
);
408 Status
= MmLoadSystemImage(&ServiceImagePath
, NULL
, NULL
, 0, (PVOID
)ModuleObject
, &BaseAddress
);
409 if (NT_SUCCESS(Status
))
411 IopDisplayLoadingMessage(ServiceName
);
415 ExFreePool(ServiceImagePath
.Buffer
);
418 * Now check if the module was loaded successfully.
420 if (!NT_SUCCESS(Status
))
422 DPRINT("Module loading failed (Status %x)\n", Status
);
425 DPRINT("Module loading (Status %x)\n", Status
);
432 MmFreeDriverInitialization(IN PLDR_DATA_TABLE_ENTRY LdrEntry
);
435 * IopInitializeDriverModule
437 * Initialize a loaded driver.
441 * Pointer to device node.
444 * Module object representing the driver. It can be retrieve by
445 * IopLoadServiceModule.
448 * Name of the service (as in registry).
451 * Set to TRUE for file system drivers.
454 * On successful return this contains the driver object representing
459 IopInitializeDriverModule(
460 IN PDEVICE_NODE DeviceNode
,
461 IN PLDR_DATA_TABLE_ENTRY ModuleObject
,
462 IN PUNICODE_STRING ServiceName
,
463 IN BOOLEAN FileSystemDriver
,
464 OUT PDRIVER_OBJECT
*DriverObject
)
466 const WCHAR ServicesKeyName
[] = L
"\\Registry\\Machine\\System\\CurrentControlSet\\Services\\";
467 WCHAR NameBuffer
[MAX_PATH
];
468 UNICODE_STRING DriverName
;
469 UNICODE_STRING RegistryKey
;
470 PDRIVER_INITIALIZE DriverEntry
;
471 PDRIVER_OBJECT Driver
;
474 DriverEntry
= ModuleObject
->EntryPoint
;
476 if (ServiceName
!= NULL
&& ServiceName
->Length
!= 0)
478 RegistryKey
.Length
= 0;
479 RegistryKey
.MaximumLength
= sizeof(ServicesKeyName
) + ServiceName
->Length
;
480 RegistryKey
.Buffer
= ExAllocatePool(PagedPool
, RegistryKey
.MaximumLength
);
481 if (RegistryKey
.Buffer
== NULL
)
483 return STATUS_INSUFFICIENT_RESOURCES
;
485 RtlAppendUnicodeToString(&RegistryKey
, ServicesKeyName
);
486 RtlAppendUnicodeStringToString(&RegistryKey
, ServiceName
);
490 RtlInitUnicodeString(&RegistryKey
, NULL
);
493 /* Create ModuleName string */
494 if (ServiceName
&& ServiceName
->Length
> 0)
496 if (FileSystemDriver
!= FALSE
)
497 wcscpy(NameBuffer
, FILESYSTEM_ROOT_NAME
);
499 wcscpy(NameBuffer
, DRIVER_ROOT_NAME
);
501 RtlInitUnicodeString(&DriverName
, NameBuffer
);
502 DriverName
.MaximumLength
= sizeof(NameBuffer
);
504 RtlAppendUnicodeStringToString(&DriverName
, ServiceName
);
506 DPRINT("Driver name: '%wZ'\n", &DriverName
);
509 DriverName
.Length
= 0;
511 Status
= IopCreateDriver(DriverName
.Length
> 0 ? &DriverName
: NULL
,
517 RtlFreeUnicodeString(&RegistryKey
);
519 *DriverObject
= Driver
;
520 if (!NT_SUCCESS(Status
))
522 DPRINT("IopCreateDriver() failed (Status 0x%08lx)\n", Status
);
526 MmFreeDriverInitialization((PLDR_DATA_TABLE_ENTRY
)Driver
->DriverSection
);
528 /* Set the driver as initialized */
529 IopReadyDeviceObjects(Driver
);
531 if (PnpSystemInit
) IopReinitializeDrivers();
533 return STATUS_SUCCESS
;
537 * IopAttachFilterDriversCallback
539 * Internal routine used by IopAttachFilterDrivers.
543 IopAttachFilterDriversCallback(
551 PDEVICE_NODE DeviceNode
= Context
;
552 UNICODE_STRING ServiceName
;
554 PLDR_DATA_TABLE_ENTRY ModuleObject
;
555 PDRIVER_OBJECT DriverObject
;
558 /* No filter value present */
559 if (ValueType
== REG_NONE
)
560 return STATUS_SUCCESS
;
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 KeEnterCriticalRegion();
574 ExAcquireResourceExclusiveLite(&IopDriverLoadResource
, TRUE
);
575 Status
= IopGetDriverObject(&DriverObject
,
578 if (!NT_SUCCESS(Status
))
580 /* Load and initialize the filter driver */
581 Status
= IopLoadServiceModule(&ServiceName
, &ModuleObject
);
582 if (!NT_SUCCESS(Status
))
584 ExReleaseResourceLite(&IopDriverLoadResource
);
585 KeLeaveCriticalRegion();
589 Status
= IopInitializeDriverModule(DeviceNode
,
594 if (!NT_SUCCESS(Status
))
596 ExReleaseResourceLite(&IopDriverLoadResource
);
597 KeLeaveCriticalRegion();
602 ExReleaseResourceLite(&IopDriverLoadResource
);
603 KeLeaveCriticalRegion();
605 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
607 /* Remove extra reference */
608 ObDereferenceObject(DriverObject
);
610 if (!NT_SUCCESS(Status
))
614 return STATUS_SUCCESS
;
618 * IopAttachFilterDrivers
620 * Load filter drivers for specified device node.
624 * Set to TRUE for loading lower level filters or FALSE for upper
629 IopAttachFilterDrivers(
630 PDEVICE_NODE DeviceNode
,
633 RTL_QUERY_REGISTRY_TABLE QueryTable
[2] = { { NULL
, 0, NULL
, NULL
, 0, NULL
, 0 }, };
634 UNICODE_STRING Class
;
635 WCHAR ClassBuffer
[40];
636 UNICODE_STRING EnumRoot
= RTL_CONSTANT_STRING(ENUM_ROOT
);
637 HANDLE EnumRootKey
, SubKey
;
640 /* Open enumeration root key */
641 Status
= IopOpenRegistryKeyEx(&EnumRootKey
,
645 if (!NT_SUCCESS(Status
))
647 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
652 Status
= IopOpenRegistryKeyEx(&SubKey
,
654 &DeviceNode
->InstancePath
,
656 if (!NT_SUCCESS(Status
))
658 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
659 ZwClose(EnumRootKey
);
664 * First load the device filters
666 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
668 QueryTable
[0].Name
= L
"LowerFilters";
670 QueryTable
[0].Name
= L
"UpperFilters";
671 QueryTable
[0].Flags
= 0;
672 QueryTable
[0].DefaultType
= REG_NONE
;
674 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
679 if (!NT_SUCCESS(Status
))
681 DPRINT1("Failed to load device %s filters: %08X\n",
682 Lower
? "lower" : "upper", Status
);
684 ZwClose(EnumRootKey
);
689 * Now get the class GUID
692 Class
.MaximumLength
= 40 * sizeof(WCHAR
);
693 Class
.Buffer
= ClassBuffer
;
694 QueryTable
[0].QueryRoutine
= NULL
;
695 QueryTable
[0].Name
= L
"ClassGUID";
696 QueryTable
[0].EntryContext
= &Class
;
697 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_REQUIRED
| RTL_QUERY_REGISTRY_DIRECT
;
699 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
707 ZwClose(EnumRootKey
);
710 * Load the class filter driver
712 if (NT_SUCCESS(Status
))
714 UNICODE_STRING ControlClass
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Class");
716 Status
= IopOpenRegistryKeyEx(&EnumRootKey
,
720 if (!NT_SUCCESS(Status
))
722 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
727 Status
= IopOpenRegistryKeyEx(&SubKey
,
731 if (!NT_SUCCESS(Status
))
733 /* It's okay if there's no class key */
734 DPRINT1("ZwOpenKey() failed with Status %08X\n", Status
);
735 ZwClose(EnumRootKey
);
736 return STATUS_SUCCESS
;
739 QueryTable
[0].QueryRoutine
= IopAttachFilterDriversCallback
;
741 QueryTable
[0].Name
= L
"LowerFilters";
743 QueryTable
[0].Name
= L
"UpperFilters";
744 QueryTable
[0].EntryContext
= NULL
;
745 QueryTable
[0].Flags
= 0;
746 QueryTable
[0].DefaultType
= REG_NONE
;
748 Status
= RtlQueryRegistryValues(RTL_REGISTRY_HANDLE
,
756 ZwClose(EnumRootKey
);
758 if (!NT_SUCCESS(Status
))
760 DPRINT1("Failed to load class %s filters: %08X\n",
761 Lower
? "lower" : "upper", Status
);
763 ZwClose(EnumRootKey
);
768 return STATUS_SUCCESS
;
773 MiResolveImageReferences(IN PVOID ImageBase
,
774 IN PUNICODE_STRING ImageFileDirectory
,
775 IN PUNICODE_STRING NamePrefix OPTIONAL
,
776 OUT PCHAR
*MissingApi
,
777 OUT PWCHAR
*MissingDriver
,
778 OUT PLOAD_IMPORTS
*LoadImports
);
781 // Used for images already loaded (boot drivers)
786 LdrProcessDriverModule(PLDR_DATA_TABLE_ENTRY LdrEntry
,
787 PUNICODE_STRING FileName
,
788 PLDR_DATA_TABLE_ENTRY
*ModuleObject
)
791 UNICODE_STRING BaseName
, BaseDirectory
;
792 PLOAD_IMPORTS LoadedImports
= (PVOID
)-2;
793 PCHAR MissingApiName
, Buffer
;
794 PWCHAR MissingDriverName
;
795 PVOID DriverBase
= LdrEntry
->DllBase
;
797 /* Allocate a buffer we'll use for names */
798 Buffer
= ExAllocatePoolWithTag(NonPagedPool
, MAX_PATH
, TAG_LDR_WSTR
);
802 return STATUS_INSUFFICIENT_RESOURCES
;
805 /* Check for a separator */
806 if (FileName
->Buffer
[0] == OBJ_NAME_PATH_SEPARATOR
)
811 /* Loop the path until we get to the base name */
812 p
= &FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)];
813 while (*(p
- 1) != OBJ_NAME_PATH_SEPARATOR
) p
--;
816 BaseLength
= (ULONG
)(&FileName
->Buffer
[FileName
->Length
/ sizeof(WCHAR
)] - p
);
817 BaseLength
*= sizeof(WCHAR
);
819 /* Setup the string */
820 BaseName
.Length
= (USHORT
)BaseLength
;
825 /* Otherwise, we already have a base name */
826 BaseName
.Length
= FileName
->Length
;
827 BaseName
.Buffer
= FileName
->Buffer
;
830 /* Setup the maximum length */
831 BaseName
.MaximumLength
= BaseName
.Length
;
833 /* Now compute the base directory */
834 BaseDirectory
= *FileName
;
835 BaseDirectory
.Length
-= BaseName
.Length
;
836 BaseDirectory
.MaximumLength
= BaseDirectory
.Length
;
838 /* Resolve imports */
839 MissingApiName
= Buffer
;
840 Status
= MiResolveImageReferences(DriverBase
,
847 /* Free the temporary buffer */
848 ExFreePoolWithTag(Buffer
, TAG_LDR_WSTR
);
850 /* Check the result of the imports resolution */
851 if (!NT_SUCCESS(Status
)) return Status
;
854 *ModuleObject
= LdrEntry
;
855 return STATUS_SUCCESS
;
859 * IopInitializeBuiltinDriver
861 * Initialize a driver that is already loaded in memory.
866 IopInitializeBuiltinDriver(IN PLDR_DATA_TABLE_ENTRY BootLdrEntry
)
868 PDEVICE_NODE DeviceNode
;
869 PDRIVER_OBJECT DriverObject
;
871 PWCHAR FileNameWithoutPath
;
872 LPWSTR FileExtension
;
873 PUNICODE_STRING ModuleName
= &BootLdrEntry
->BaseDllName
;
874 PLDR_DATA_TABLE_ENTRY LdrEntry
;
875 PLIST_ENTRY NextEntry
;
876 UNICODE_STRING ServiceName
;
879 * Display 'Loading XXX...' message
881 IopDisplayLoadingMessage(ModuleName
);
882 InbvIndicateProgress();
885 * Generate filename without path (not needed by freeldr)
887 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
888 if (FileNameWithoutPath
== NULL
)
890 FileNameWithoutPath
= ModuleName
->Buffer
;
894 FileNameWithoutPath
++;
898 * Strip the file extension from ServiceName
900 RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
901 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
902 if (FileExtension
!= NULL
)
904 ServiceName
.Length
-= (USHORT
)wcslen(FileExtension
) * sizeof(WCHAR
);
905 FileExtension
[0] = 0;
909 * Determine the right device object
911 /* Use IopRootDeviceNode for now */
912 Status
= IopCreateDeviceNode(IopRootDeviceNode
,
916 if (!NT_SUCCESS(Status
))
918 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
922 /* Lookup the new Ldr entry in PsLoadedModuleList */
923 NextEntry
= PsLoadedModuleList
.Flink
;
924 while (NextEntry
!= &PsLoadedModuleList
)
926 LdrEntry
= CONTAINING_RECORD(NextEntry
,
927 LDR_DATA_TABLE_ENTRY
,
929 if (RtlEqualUnicodeString(ModuleName
, &LdrEntry
->BaseDllName
, TRUE
))
934 NextEntry
= NextEntry
->Flink
;
936 ASSERT(NextEntry
!= &PsLoadedModuleList
);
939 * Initialize the driver
941 Status
= IopInitializeDriverModule(DeviceNode
,
943 &DeviceNode
->ServiceName
,
947 if (!NT_SUCCESS(Status
))
952 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
953 if (NT_SUCCESS(Status
))
955 Status
= IopStartDevice(DeviceNode
);
958 /* Remove extra reference from IopInitializeDriverModule */
959 ObDereferenceObject(DriverObject
);
965 * IopInitializeBootDrivers
967 * Initialize boot drivers and free memory for boot files.
978 IopInitializeBootDrivers(VOID
)
980 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
981 PLDR_DATA_TABLE_ENTRY LdrEntry
;
982 PDEVICE_NODE DeviceNode
;
983 PDRIVER_OBJECT DriverObject
;
984 LDR_DATA_TABLE_ENTRY ModuleObject
;
986 UNICODE_STRING DriverName
;
988 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
990 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
991 DPRINT("IopInitializeBootDrivers()\n");
993 /* Use IopRootDeviceNode for now */
994 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
995 if (!NT_SUCCESS(Status
)) return;
997 /* Setup the module object for the RAW FS Driver */
998 ModuleObject
.DllBase
= NULL
;
999 ModuleObject
.SizeOfImage
= 0;
1000 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
1001 RtlInitUnicodeString(&DriverName
, L
"RAW");
1004 Status
= IopInitializeDriverModule(DeviceNode
,
1009 if (!NT_SUCCESS(Status
))
1015 /* Now initialize the associated device */
1016 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
1017 if (!NT_SUCCESS(Status
))
1020 ObDereferenceObject(DriverObject
);
1025 Status
= IopStartDevice(DeviceNode
);
1026 if (!NT_SUCCESS(Status
))
1029 ObDereferenceObject(DriverObject
);
1033 /* Get highest group order index */
1034 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
1035 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
1037 /* Allocate the group table */
1038 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
1039 IopGroupIndex
* sizeof(LIST_ENTRY
),
1041 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
1043 /* Initialize the group table lists */
1044 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
1046 /* Loop the boot modules */
1047 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
1048 NextEntry
= ListHead
->Flink
;
1049 while (ListHead
!= NextEntry
)
1052 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1053 LDR_DATA_TABLE_ENTRY
,
1056 /* Check if the DLL needs to be initialized */
1057 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
1059 /* Call its entrypoint */
1060 MmCallDllInitialize(LdrEntry
, NULL
);
1063 /* Go to the next driver */
1064 NextEntry
= NextEntry
->Flink
;
1067 /* Loop the boot drivers */
1068 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
1069 NextEntry
= ListHead
->Flink
;
1070 while (ListHead
!= NextEntry
)
1073 BootEntry
= CONTAINING_RECORD(NextEntry
,
1074 BOOT_DRIVER_LIST_ENTRY
,
1077 /* Get the driver loader entry */
1078 LdrEntry
= BootEntry
->LdrEntry
;
1080 /* Allocate our internal accounting structure */
1081 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
1082 sizeof(DRIVER_INFORMATION
),
1086 /* Zero it and initialize it */
1087 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1088 InitializeListHead(&DriverInfo
->Link
);
1089 DriverInfo
->DataTableEntry
= BootEntry
;
1091 /* Open the registry key */
1092 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1094 &BootEntry
->RegistryPath
,
1096 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1097 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1099 /* Save the handle */
1100 DriverInfo
->ServiceHandle
= KeyHandle
;
1102 /* Get the group oder index */
1103 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1105 /* Get the tag position */
1106 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1108 /* Insert it into the list, at the right place */
1109 ASSERT(Index
< IopGroupIndex
);
1110 NextEntry2
= IopGroupTable
[Index
].Flink
;
1111 while (NextEntry2
!= &IopGroupTable
[Index
])
1113 /* Get the driver info */
1114 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1118 /* Check if we found the right tag position */
1119 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1126 NextEntry2
= NextEntry2
->Flink
;
1129 /* Insert us right before the next entry */
1130 NextEntry2
= NextEntry2
->Blink
;
1131 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1135 /* Go to the next driver */
1136 NextEntry
= NextEntry
->Flink
;
1139 /* Loop each group index */
1140 for (i
= 0; i
< IopGroupIndex
; i
++)
1142 /* Loop each group table */
1143 NextEntry
= IopGroupTable
[i
].Flink
;
1144 while (NextEntry
!= &IopGroupTable
[i
])
1147 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1151 /* Get the driver loader entry */
1152 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1155 IopInitializeBuiltinDriver(LdrEntry
);
1158 NextEntry
= NextEntry
->Flink
;
1162 /* In old ROS, the loader list became empty after this point. Simulate. */
1163 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1169 IopInitializeSystemDrivers(VOID
)
1171 PUNICODE_STRING
*DriverList
, *SavedList
;
1173 /* No system drivers on the boot cd */
1174 if (KeLoaderBlock
->SetupLdrBlock
) return;
1176 /* Get the driver list */
1177 SavedList
= DriverList
= CmGetSystemDriverList();
1183 /* Load the driver */
1184 ZwLoadDriver(*DriverList
);
1186 /* Free the entry */
1187 RtlFreeUnicodeString(*DriverList
);
1188 ExFreePool(*DriverList
);
1191 InbvIndicateProgress();
1196 ExFreePool(SavedList
);
1202 * Unloads a device driver.
1206 * Name of the service to unload (registry key).
1209 * Whether to unload Plug & Plug or only legacy drivers. If this
1210 * parameter is set to FALSE, the routine will unload only legacy
1217 * Guard the whole function by SEH.
1221 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1223 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1224 UNICODE_STRING ImagePath
;
1225 UNICODE_STRING ServiceName
;
1226 UNICODE_STRING ObjectName
;
1227 PDRIVER_OBJECT DriverObject
;
1228 PDEVICE_OBJECT DeviceObject
;
1229 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1232 BOOLEAN SafeToUnload
= TRUE
;
1234 DPRINT("IopUnloadDriver('%wZ', %u)\n", DriverServiceName
, UnloadPnpDrivers
);
1239 * Get the service name from the registry key name
1242 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1244 Start
= DriverServiceName
->Buffer
;
1248 RtlInitUnicodeString(&ServiceName
, Start
);
1251 * Construct the driver object name
1254 ObjectName
.Length
= ((USHORT
)wcslen(Start
) + 8) * sizeof(WCHAR
);
1255 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1256 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1257 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1258 wcscpy(ObjectName
.Buffer
, DRIVER_ROOT_NAME
);
1259 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1260 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1263 * Find the driver object
1265 Status
= ObReferenceObjectByName(&ObjectName
,
1272 (PVOID
*)&DriverObject
);
1274 if (!NT_SUCCESS(Status
))
1276 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1277 ExFreePool(ObjectName
.Buffer
);
1282 * Free the buffer for driver object name
1284 ExFreePool(ObjectName
.Buffer
);
1286 /* Check that driver is not already unloading */
1287 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1289 DPRINT1("Driver deletion pending\n");
1290 ObDereferenceObject(DriverObject
);
1291 return STATUS_DELETE_PENDING
;
1295 * Get path of service...
1297 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1299 RtlInitUnicodeString(&ImagePath
, NULL
);
1301 QueryTable
[0].Name
= L
"ImagePath";
1302 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1303 QueryTable
[0].EntryContext
= &ImagePath
;
1305 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1306 DriverServiceName
->Buffer
,
1311 if (!NT_SUCCESS(Status
))
1313 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1314 ObDereferenceObject(DriverObject
);
1319 * Normalize the image path for all later processing.
1321 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1323 if (!NT_SUCCESS(Status
))
1325 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1326 ObDereferenceObject(DriverObject
);
1331 * Free the service path
1333 ExFreePool(ImagePath
.Buffer
);
1336 * Unload the module and release the references to the device object
1339 /* Call the load/unload routine, depending on current process */
1340 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
&&
1341 (UnloadPnpDrivers
|| (DriverObject
->Flags
& DRVO_LEGACY_DRIVER
)))
1343 /* Loop through each device object of the driver
1344 and set DOE_UNLOAD_PENDING flag */
1345 DeviceObject
= DriverObject
->DeviceObject
;
1346 while (DeviceObject
)
1348 /* Set the unload pending flag for the device */
1349 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1350 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1352 /* Make sure there are no attached devices or no reference counts */
1353 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1355 /* Not safe to unload */
1356 DPRINT1("Drivers device object is referenced or has attached devices\n");
1358 SafeToUnload
= FALSE
;
1361 DeviceObject
= DeviceObject
->NextDevice
;
1364 /* If not safe to unload, then return success */
1367 ObDereferenceObject(DriverObject
);
1368 return STATUS_SUCCESS
;
1371 DPRINT1("Unloading driver '%wZ' (manual)\n", &DriverObject
->DriverName
);
1373 /* Set the unload invoked flag and call the unload routine */
1374 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1375 Status
= IopLoadUnloadDriver(NULL
, &DriverObject
);
1376 ASSERT(Status
== STATUS_SUCCESS
);
1378 /* Mark the driver object temporary, so it could be deleted later */
1379 ObMakeTemporaryObject(DriverObject
);
1381 /* Dereference it 2 times */
1382 ObDereferenceObject(DriverObject
);
1383 ObDereferenceObject(DriverObject
);
1389 DPRINT1("No DriverUnload function! '%wZ' will not be unloaded!\n", &DriverObject
->DriverName
);
1391 /* Dereference one time (refd inside this function) */
1392 ObDereferenceObject(DriverObject
);
1394 /* Return unloading failure */
1395 return STATUS_INVALID_DEVICE_REQUEST
;
1401 IopReinitializeDrivers(VOID
)
1403 PDRIVER_REINIT_ITEM ReinitItem
;
1406 /* Get the first entry and start looping */
1407 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1408 &DriverReinitListLock
);
1412 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1414 /* Increment reinitialization counter */
1415 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1417 /* Remove the device object flag */
1418 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1420 /* Call the routine */
1421 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1422 ReinitItem
->Context
,
1423 ReinitItem
->DriverObject
->
1424 DriverExtension
->Count
);
1426 /* Free the entry */
1429 /* Move to the next one */
1430 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1431 &DriverReinitListLock
);
1437 IopReinitializeBootDrivers(VOID
)
1439 PDRIVER_REINIT_ITEM ReinitItem
;
1442 /* Get the first entry and start looping */
1443 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1444 &DriverBootReinitListLock
);
1448 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1450 /* Increment reinitialization counter */
1451 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1453 /* Remove the device object flag */
1454 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1456 /* Call the routine */
1457 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1458 ReinitItem
->Context
,
1459 ReinitItem
->DriverObject
->
1460 DriverExtension
->Count
);
1462 /* Free the entry */
1465 /* Move to the next one */
1466 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1467 &DriverBootReinitListLock
);
1473 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1474 IN PDRIVER_INITIALIZE InitializationFunction
,
1475 IN PUNICODE_STRING RegistryPath
,
1476 IN PCUNICODE_STRING ServiceName
,
1477 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1478 OUT PDRIVER_OBJECT
*pDriverObject
)
1480 WCHAR NameBuffer
[100];
1482 UNICODE_STRING LocalDriverName
;
1484 OBJECT_ATTRIBUTES ObjectAttributes
;
1486 PDRIVER_OBJECT DriverObject
;
1487 UNICODE_STRING ServiceKeyName
;
1489 ULONG i
, RetryCount
= 0;
1492 /* First, create a unique name for the driver if we don't have one */
1495 /* Create a random name and set up the string*/
1496 NameLength
= (USHORT
)swprintf(NameBuffer
,
1497 DRIVER_ROOT_NAME L
"%08u",
1498 KeTickCount
.LowPart
);
1499 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1500 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1501 LocalDriverName
.Buffer
= NameBuffer
;
1505 /* So we can avoid another code path, use a local var */
1506 LocalDriverName
= *DriverName
;
1509 /* Initialize the Attributes */
1510 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1511 InitializeObjectAttributes(&ObjectAttributes
,
1513 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1517 /* Create the Object */
1518 Status
= ObCreateObject(KernelMode
,
1526 (PVOID
*)&DriverObject
);
1527 if (!NT_SUCCESS(Status
)) return Status
;
1529 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1531 /* Set up the Object */
1532 RtlZeroMemory(DriverObject
, ObjectSize
);
1533 DriverObject
->Type
= IO_TYPE_DRIVER
;
1534 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1535 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;
1536 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1537 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1538 DriverObject
->DriverInit
= InitializationFunction
;
1539 DriverObject
->DriverSection
= ModuleObject
;
1540 /* Loop all Major Functions */
1541 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1543 /* Invalidate each function */
1544 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1547 /* Set up the service key name buffer */
1548 ServiceKeyName
.MaximumLength
= ServiceName
->Length
+ sizeof(UNICODE_NULL
);
1549 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
1550 ServiceKeyName
.MaximumLength
,
1552 if (!ServiceKeyName
.Buffer
)
1555 ObMakeTemporaryObject(DriverObject
);
1556 ObDereferenceObject(DriverObject
);
1557 return STATUS_INSUFFICIENT_RESOURCES
;
1560 /* Copy the name and set it in the driver extension */
1561 RtlCopyUnicodeString(&ServiceKeyName
,
1563 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1565 /* Make a copy of the driver name to store in the driver object */
1566 DriverObject
->DriverName
.MaximumLength
= LocalDriverName
.Length
;
1567 DriverObject
->DriverName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1568 DriverObject
->DriverName
.MaximumLength
,
1570 if (!DriverObject
->DriverName
.Buffer
)
1573 ObMakeTemporaryObject(DriverObject
);
1574 ObDereferenceObject(DriverObject
);
1575 return STATUS_INSUFFICIENT_RESOURCES
;
1578 RtlCopyUnicodeString(&DriverObject
->DriverName
,
1581 /* Add the Object and get its handle */
1582 Status
= ObInsertObject(DriverObject
,
1589 /* Eliminate small possibility when this function is called more than
1590 once in a row, and KeTickCount doesn't get enough time to change */
1591 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1597 if (!NT_SUCCESS(Status
)) return Status
;
1599 /* Now reference it */
1600 Status
= ObReferenceObjectByHandle(hDriver
,
1604 (PVOID
*)&DriverObject
,
1607 /* Close the extra handle */
1610 if (!NT_SUCCESS(Status
))
1613 ObMakeTemporaryObject(DriverObject
);
1614 ObDereferenceObject(DriverObject
);
1618 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1619 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1620 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1622 /* Finally, call its init function */
1623 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1624 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1625 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1626 if (!NT_SUCCESS(Status
))
1628 /* If it didn't work, then kill the object */
1629 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1630 DriverObject
->DriverSection
= NULL
;
1631 ObMakeTemporaryObject(DriverObject
);
1632 ObDereferenceObject(DriverObject
);
1637 /* Returns to caller the object */
1638 *pDriverObject
= DriverObject
;
1641 /* We're going to say if we don't have any DOs from DriverEntry, then we're not legacy.
1642 * Other parts of the I/O manager depend on this behavior */
1643 if (!DriverObject
->DeviceObject
) DriverObject
->Flags
&= ~DRVO_LEGACY_DRIVER
;
1645 /* Loop all Major Functions */
1646 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1649 * Make sure the driver didn't set any dispatch entry point to NULL!
1650 * Doing so is illegal; drivers shouldn't touch entry points they
1654 /* Check if it did so anyway */
1655 if (!DriverObject
->MajorFunction
[i
])
1657 /* Print a warning in the debug log */
1658 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%lu] to NULL!\n",
1659 &DriverObject
->DriverName
, i
);
1662 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1666 /* Return the Status */
1670 /* PUBLIC FUNCTIONS ***********************************************************/
1677 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1678 IN PDRIVER_INITIALIZE InitializationFunction
)
1680 PDRIVER_OBJECT DriverObject
;
1681 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, DriverName
, NULL
, &DriverObject
);
1689 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1691 /* Simply dereference the Object */
1692 ObDereferenceObject(DriverObject
);
1700 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1701 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1704 PDRIVER_REINIT_ITEM ReinitItem
;
1706 /* Allocate the entry */
1707 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1708 sizeof(DRIVER_REINIT_ITEM
),
1710 if (!ReinitItem
) return;
1713 ReinitItem
->DriverObject
= DriverObject
;
1714 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1715 ReinitItem
->Context
= Context
;
1717 /* Set the Driver Object flag and insert the entry into the list */
1718 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1719 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1720 &ReinitItem
->ItemEntry
,
1721 &DriverBootReinitListLock
);
1729 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1730 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1733 PDRIVER_REINIT_ITEM ReinitItem
;
1735 /* Allocate the entry */
1736 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1737 sizeof(DRIVER_REINIT_ITEM
),
1739 if (!ReinitItem
) return;
1742 ReinitItem
->DriverObject
= DriverObject
;
1743 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1744 ReinitItem
->Context
= Context
;
1746 /* Set the Driver Object flag and insert the entry into the list */
1747 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1748 ExInterlockedInsertTailList(&DriverReinitListHead
,
1749 &ReinitItem
->ItemEntry
,
1750 &DriverReinitListLock
);
1758 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1759 IN PVOID ClientIdentificationAddress
,
1760 IN ULONG DriverObjectExtensionSize
,
1761 OUT PVOID
*DriverObjectExtension
)
1764 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1765 BOOLEAN Inserted
= FALSE
;
1767 /* Assume failure */
1768 *DriverObjectExtension
= NULL
;
1770 /* Allocate the extension */
1771 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1772 sizeof(IO_CLIENT_EXTENSION
) +
1773 DriverObjectExtensionSize
,
1774 TAG_DRIVER_EXTENSION
);
1775 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1777 /* Clear the extension for teh caller */
1778 RtlZeroMemory(NewDriverExtension
,
1779 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1782 OldIrql
= KeRaiseIrqlToDpcLevel();
1784 /* Fill out the extension */
1785 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1787 /* Loop the current extensions */
1788 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1789 ClientDriverExtension
;
1790 while (DriverExtensions
)
1792 /* Check if the identifier matches */
1793 if (DriverExtensions
->ClientIdentificationAddress
==
1794 ClientIdentificationAddress
)
1796 /* We have a collision, break out */
1800 /* Go to the next one */
1801 DriverExtensions
= DriverExtensions
->NextExtension
;
1804 /* Check if we didn't collide */
1805 if (!DriverExtensions
)
1807 /* Link this one in */
1808 NewDriverExtension
->NextExtension
=
1809 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1810 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1815 /* Release the lock */
1816 KeLowerIrql(OldIrql
);
1818 /* Check if insertion failed */
1821 /* Free the entry and fail */
1822 ExFreePoolWithTag(NewDriverExtension
, TAG_DRIVER_EXTENSION
);
1823 return STATUS_OBJECT_NAME_COLLISION
;
1826 /* Otherwise, return the pointer */
1827 *DriverObjectExtension
= NewDriverExtension
+ 1;
1828 return STATUS_SUCCESS
;
1836 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1837 IN PVOID ClientIdentificationAddress
)
1840 PIO_CLIENT_EXTENSION DriverExtensions
;
1843 OldIrql
= KeRaiseIrqlToDpcLevel();
1845 /* Loop the list until we find the right one */
1846 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1847 while (DriverExtensions
)
1849 /* Check for a match */
1850 if (DriverExtensions
->ClientIdentificationAddress
==
1851 ClientIdentificationAddress
)
1858 DriverExtensions
= DriverExtensions
->NextExtension
;
1862 KeLowerIrql(OldIrql
);
1864 /* Return nothing or the extension */
1865 if (!DriverExtensions
) return NULL
;
1866 return DriverExtensions
+ 1;
1871 IopLoadUnloadDriverWorker(
1872 _Inout_ PVOID Parameter
)
1874 PLOAD_UNLOAD_PARAMS LoadParams
= Parameter
;
1876 ASSERT(PsGetCurrentProcess() == PsInitialSystemProcess
);
1877 LoadParams
->Status
= IopLoadUnloadDriver(LoadParams
->RegistryPath
,
1878 &LoadParams
->DriverObject
);
1879 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1884 IopLoadUnloadDriver(
1885 _In_opt_ PCUNICODE_STRING RegistryPath
,
1886 _Inout_ PDRIVER_OBJECT
*DriverObject
)
1888 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1889 UNICODE_STRING ImagePath
;
1890 UNICODE_STRING ServiceName
;
1893 PDEVICE_NODE DeviceNode
;
1894 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1898 /* Load/Unload must be called from system process */
1899 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1901 LOAD_UNLOAD_PARAMS LoadParams
;
1903 /* Prepare parameters block */
1904 LoadParams
.RegistryPath
= RegistryPath
;
1905 LoadParams
.DriverObject
= *DriverObject
;
1906 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1908 /* Initialize and queue a work item */
1909 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1910 IopLoadUnloadDriverWorker
,
1912 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1914 /* And wait till it completes */
1915 KeWaitForSingleObject(&LoadParams
.Event
,
1920 return LoadParams
.Status
;
1923 /* Check if it's an unload request */
1926 (*DriverObject
)->DriverUnload(*DriverObject
);
1927 return STATUS_SUCCESS
;
1930 RtlInitUnicodeString(&ImagePath
, NULL
);
1933 * Get the service name from the registry key name.
1935 ASSERT(RegistryPath
->Length
>= sizeof(WCHAR
));
1937 ServiceName
= *RegistryPath
;
1938 cur
= RegistryPath
->Buffer
+ RegistryPath
->Length
/ sizeof(WCHAR
) - 1;
1939 while (RegistryPath
->Buffer
!= cur
)
1943 ServiceName
.Buffer
= cur
+ 1;
1944 ServiceName
.Length
= RegistryPath
->Length
-
1945 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1946 (ULONG_PTR
)RegistryPath
->Buffer
);
1955 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1957 RtlInitUnicodeString(&ImagePath
, NULL
);
1959 QueryTable
[0].Name
= L
"Type";
1960 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1961 QueryTable
[0].EntryContext
= &Type
;
1963 QueryTable
[1].Name
= L
"ImagePath";
1964 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1965 QueryTable
[1].EntryContext
= &ImagePath
;
1967 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1968 RegistryPath
->Buffer
,
1969 QueryTable
, NULL
, NULL
);
1970 if (!NT_SUCCESS(Status
))
1972 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1973 if (ImagePath
.Buffer
) ExFreePool(ImagePath
.Buffer
);
1978 * Normalize the image path for all later processing.
1980 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1981 if (!NT_SUCCESS(Status
))
1983 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1987 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1988 DPRINT("Type: %lx\n", Type
);
1990 KeEnterCriticalRegion();
1991 ExAcquireResourceExclusiveLite(&IopDriverLoadResource
, TRUE
);
1993 * Get existing DriverObject pointer (in case the driver
1994 * has already been loaded and initialized).
1996 Status
= IopGetDriverObject(DriverObject
,
1998 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
1999 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
2001 if (!NT_SUCCESS(Status
))
2004 * Load the driver module
2006 DPRINT("Loading module from %wZ\n", &ImagePath
);
2007 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
2008 if (!NT_SUCCESS(Status
))
2010 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
2011 ExReleaseResourceLite(&IopDriverLoadResource
);
2012 KeLeaveCriticalRegion();
2017 * Initialize the driver module if it's loaded for the first time
2019 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
2020 if (!NT_SUCCESS(Status
))
2022 DPRINT1("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
2023 ExReleaseResourceLite(&IopDriverLoadResource
);
2024 KeLeaveCriticalRegion();
2025 MmUnloadSystemImage(ModuleObject
);
2029 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
2031 Status
= IopInitializeDriverModule(DeviceNode
,
2033 &DeviceNode
->ServiceName
,
2034 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
2035 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
2037 if (!NT_SUCCESS(Status
))
2039 DPRINT1("IopInitializeDriverModule() failed (Status %lx)\n", Status
);
2040 ExReleaseResourceLite(&IopDriverLoadResource
);
2041 KeLeaveCriticalRegion();
2042 MmUnloadSystemImage(ModuleObject
);
2046 ExReleaseResourceLite(&IopDriverLoadResource
);
2047 KeLeaveCriticalRegion();
2049 /* Initialize and start device */
2050 IopInitializeDevice(DeviceNode
, *DriverObject
);
2051 Status
= IopStartDevice(DeviceNode
);
2055 ExReleaseResourceLite(&IopDriverLoadResource
);
2056 KeLeaveCriticalRegion();
2058 DPRINT("DriverObject already exist in ObjectManager\n");
2059 Status
= STATUS_IMAGE_ALREADY_LOADED
;
2061 /* IopGetDriverObject references the DriverObject, so dereference it */
2062 ObDereferenceObject(*DriverObject
);
2071 * Loads a device driver.
2075 * Name of the service to load (registry key).
2084 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
2086 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
2087 KPROCESSOR_MODE PreviousMode
;
2088 PDRIVER_OBJECT DriverObject
;
2093 PreviousMode
= KeGetPreviousMode();
2096 * Check security privileges
2099 /* FIXME: Uncomment when privileges will be correctly implemented. */
2101 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
2103 DPRINT("Privilege not held\n");
2104 return STATUS_PRIVILEGE_NOT_HELD
;
2108 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2111 if (!NT_SUCCESS(Status
))
2116 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2118 /* Load driver and call its entry point */
2119 DriverObject
= NULL
;
2120 Status
= IopLoadUnloadDriver(&CapturedDriverServiceName
, &DriverObject
);
2122 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2131 * Unloads a legacy device driver.
2135 * Name of the service to unload (registry key).
2145 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2147 return IopUnloadDriver(DriverServiceName
, FALSE
);