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
;
880 * Display 'Loading XXX...' message
882 IopDisplayLoadingMessage(ModuleName
);
883 InbvIndicateProgress();
886 * Generate filename without path (not needed by freeldr)
888 FileNameWithoutPath
= wcsrchr(ModuleName
->Buffer
, L
'\\');
889 if (FileNameWithoutPath
== NULL
)
891 FileNameWithoutPath
= ModuleName
->Buffer
;
895 FileNameWithoutPath
++;
899 * Strip the file extension from ServiceName
901 Success
= RtlCreateUnicodeString(&ServiceName
, FileNameWithoutPath
);
904 return STATUS_INSUFFICIENT_RESOURCES
;
907 FileExtension
= wcsrchr(ServiceName
.Buffer
, '.');
908 if (FileExtension
!= NULL
)
910 ServiceName
.Length
-= (USHORT
)wcslen(FileExtension
) * sizeof(WCHAR
);
911 FileExtension
[0] = 0;
915 * Determine the right device object
917 /* Use IopRootDeviceNode for now */
918 Status
= IopCreateDeviceNode(IopRootDeviceNode
,
922 RtlFreeUnicodeString(&ServiceName
);
923 if (!NT_SUCCESS(Status
))
925 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
929 /* Lookup the new Ldr entry in PsLoadedModuleList */
930 NextEntry
= PsLoadedModuleList
.Flink
;
931 while (NextEntry
!= &PsLoadedModuleList
)
933 LdrEntry
= CONTAINING_RECORD(NextEntry
,
934 LDR_DATA_TABLE_ENTRY
,
936 if (RtlEqualUnicodeString(ModuleName
, &LdrEntry
->BaseDllName
, TRUE
))
941 NextEntry
= NextEntry
->Flink
;
943 ASSERT(NextEntry
!= &PsLoadedModuleList
);
946 * Initialize the driver
948 Status
= IopInitializeDriverModule(DeviceNode
,
950 &DeviceNode
->ServiceName
,
954 if (!NT_SUCCESS(Status
))
959 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
960 if (NT_SUCCESS(Status
))
962 Status
= IopStartDevice(DeviceNode
);
965 /* Remove extra reference from IopInitializeDriverModule */
966 ObDereferenceObject(DriverObject
);
972 * IopInitializeBootDrivers
974 * Initialize boot drivers and free memory for boot files.
985 IopInitializeBootDrivers(VOID
)
987 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
988 PLDR_DATA_TABLE_ENTRY LdrEntry
;
989 PDEVICE_NODE DeviceNode
;
990 PDRIVER_OBJECT DriverObject
;
991 LDR_DATA_TABLE_ENTRY ModuleObject
;
993 UNICODE_STRING DriverName
;
995 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
997 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
998 DPRINT("IopInitializeBootDrivers()\n");
1000 /* Use IopRootDeviceNode for now */
1001 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
1002 if (!NT_SUCCESS(Status
)) return;
1004 /* Setup the module object for the RAW FS Driver */
1005 ModuleObject
.DllBase
= NULL
;
1006 ModuleObject
.SizeOfImage
= 0;
1007 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
1008 RtlInitUnicodeString(&DriverName
, L
"RAW");
1011 Status
= IopInitializeDriverModule(DeviceNode
,
1016 if (!NT_SUCCESS(Status
))
1022 /* Now initialize the associated device */
1023 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
1024 if (!NT_SUCCESS(Status
))
1027 ObDereferenceObject(DriverObject
);
1032 Status
= IopStartDevice(DeviceNode
);
1033 if (!NT_SUCCESS(Status
))
1036 ObDereferenceObject(DriverObject
);
1040 /* Get highest group order index */
1041 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
1042 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
1044 /* Allocate the group table */
1045 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
1046 IopGroupIndex
* sizeof(LIST_ENTRY
),
1048 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
1050 /* Initialize the group table lists */
1051 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
1053 /* Loop the boot modules */
1054 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
1055 NextEntry
= ListHead
->Flink
;
1056 while (ListHead
!= NextEntry
)
1059 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1060 LDR_DATA_TABLE_ENTRY
,
1063 /* Check if the DLL needs to be initialized */
1064 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
1066 /* Call its entrypoint */
1067 MmCallDllInitialize(LdrEntry
, NULL
);
1070 /* Go to the next driver */
1071 NextEntry
= NextEntry
->Flink
;
1074 /* Loop the boot drivers */
1075 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
1076 NextEntry
= ListHead
->Flink
;
1077 while (ListHead
!= NextEntry
)
1080 BootEntry
= CONTAINING_RECORD(NextEntry
,
1081 BOOT_DRIVER_LIST_ENTRY
,
1084 /* Get the driver loader entry */
1085 LdrEntry
= BootEntry
->LdrEntry
;
1087 /* Allocate our internal accounting structure */
1088 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
1089 sizeof(DRIVER_INFORMATION
),
1093 /* Zero it and initialize it */
1094 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1095 InitializeListHead(&DriverInfo
->Link
);
1096 DriverInfo
->DataTableEntry
= BootEntry
;
1098 /* Open the registry key */
1099 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1101 &BootEntry
->RegistryPath
,
1103 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1104 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1106 /* Save the handle */
1107 DriverInfo
->ServiceHandle
= KeyHandle
;
1109 /* Get the group oder index */
1110 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1112 /* Get the tag position */
1113 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1115 /* Insert it into the list, at the right place */
1116 ASSERT(Index
< IopGroupIndex
);
1117 NextEntry2
= IopGroupTable
[Index
].Flink
;
1118 while (NextEntry2
!= &IopGroupTable
[Index
])
1120 /* Get the driver info */
1121 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1125 /* Check if we found the right tag position */
1126 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1133 NextEntry2
= NextEntry2
->Flink
;
1136 /* Insert us right before the next entry */
1137 NextEntry2
= NextEntry2
->Blink
;
1138 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1142 /* Go to the next driver */
1143 NextEntry
= NextEntry
->Flink
;
1146 /* Loop each group index */
1147 for (i
= 0; i
< IopGroupIndex
; i
++)
1149 /* Loop each group table */
1150 NextEntry
= IopGroupTable
[i
].Flink
;
1151 while (NextEntry
!= &IopGroupTable
[i
])
1154 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1158 /* Get the driver loader entry */
1159 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1162 IopInitializeBuiltinDriver(LdrEntry
);
1165 NextEntry
= NextEntry
->Flink
;
1169 /* In old ROS, the loader list became empty after this point. Simulate. */
1170 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1176 IopInitializeSystemDrivers(VOID
)
1178 PUNICODE_STRING
*DriverList
, *SavedList
;
1180 /* No system drivers on the boot cd */
1181 if (KeLoaderBlock
->SetupLdrBlock
) return;
1183 /* Get the driver list */
1184 SavedList
= DriverList
= CmGetSystemDriverList();
1190 /* Load the driver */
1191 ZwLoadDriver(*DriverList
);
1193 /* Free the entry */
1194 RtlFreeUnicodeString(*DriverList
);
1195 ExFreePool(*DriverList
);
1198 InbvIndicateProgress();
1203 ExFreePool(SavedList
);
1209 * Unloads a device driver.
1213 * Name of the service to unload (registry key).
1216 * Whether to unload Plug & Plug or only legacy drivers. If this
1217 * parameter is set to FALSE, the routine will unload only legacy
1224 * Guard the whole function by SEH.
1228 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1230 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1231 UNICODE_STRING ImagePath
;
1232 UNICODE_STRING ServiceName
;
1233 UNICODE_STRING ObjectName
;
1234 PDRIVER_OBJECT DriverObject
;
1235 PDEVICE_OBJECT DeviceObject
;
1236 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1239 BOOLEAN SafeToUnload
= TRUE
;
1241 DPRINT("IopUnloadDriver('%wZ', %u)\n", DriverServiceName
, UnloadPnpDrivers
);
1246 * Get the service name from the registry key name
1249 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1251 Start
= DriverServiceName
->Buffer
;
1255 RtlInitUnicodeString(&ServiceName
, Start
);
1258 * Construct the driver object name
1261 ObjectName
.Length
= ((USHORT
)wcslen(Start
) + 8) * sizeof(WCHAR
);
1262 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1263 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1264 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1265 wcscpy(ObjectName
.Buffer
, DRIVER_ROOT_NAME
);
1266 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1267 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1270 * Find the driver object
1272 Status
= ObReferenceObjectByName(&ObjectName
,
1279 (PVOID
*)&DriverObject
);
1281 if (!NT_SUCCESS(Status
))
1283 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1284 ExFreePool(ObjectName
.Buffer
);
1289 * Free the buffer for driver object name
1291 ExFreePool(ObjectName
.Buffer
);
1293 /* Check that driver is not already unloading */
1294 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1296 DPRINT1("Driver deletion pending\n");
1297 ObDereferenceObject(DriverObject
);
1298 return STATUS_DELETE_PENDING
;
1302 * Get path of service...
1304 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1306 RtlInitUnicodeString(&ImagePath
, NULL
);
1308 QueryTable
[0].Name
= L
"ImagePath";
1309 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1310 QueryTable
[0].EntryContext
= &ImagePath
;
1312 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1313 DriverServiceName
->Buffer
,
1318 if (!NT_SUCCESS(Status
))
1320 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1321 ObDereferenceObject(DriverObject
);
1326 * Normalize the image path for all later processing.
1328 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1330 if (!NT_SUCCESS(Status
))
1332 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1333 ObDereferenceObject(DriverObject
);
1338 * Free the service path
1340 ExFreePool(ImagePath
.Buffer
);
1343 * Unload the module and release the references to the device object
1346 /* Call the load/unload routine, depending on current process */
1347 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
&&
1348 (UnloadPnpDrivers
|| (DriverObject
->Flags
& DRVO_LEGACY_DRIVER
)))
1350 /* Loop through each device object of the driver
1351 and set DOE_UNLOAD_PENDING flag */
1352 DeviceObject
= DriverObject
->DeviceObject
;
1353 while (DeviceObject
)
1355 /* Set the unload pending flag for the device */
1356 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1357 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1359 /* Make sure there are no attached devices or no reference counts */
1360 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1362 /* Not safe to unload */
1363 DPRINT1("Drivers device object is referenced or has attached devices\n");
1365 SafeToUnload
= FALSE
;
1368 DeviceObject
= DeviceObject
->NextDevice
;
1371 /* If not safe to unload, then return success */
1374 ObDereferenceObject(DriverObject
);
1375 return STATUS_SUCCESS
;
1378 DPRINT1("Unloading driver '%wZ' (manual)\n", &DriverObject
->DriverName
);
1380 /* Set the unload invoked flag and call the unload routine */
1381 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1382 Status
= IopLoadUnloadDriver(NULL
, &DriverObject
);
1383 ASSERT(Status
== STATUS_SUCCESS
);
1385 /* Mark the driver object temporary, so it could be deleted later */
1386 ObMakeTemporaryObject(DriverObject
);
1388 /* Dereference it 2 times */
1389 ObDereferenceObject(DriverObject
);
1390 ObDereferenceObject(DriverObject
);
1396 DPRINT1("No DriverUnload function! '%wZ' will not be unloaded!\n", &DriverObject
->DriverName
);
1398 /* Dereference one time (refd inside this function) */
1399 ObDereferenceObject(DriverObject
);
1401 /* Return unloading failure */
1402 return STATUS_INVALID_DEVICE_REQUEST
;
1408 IopReinitializeDrivers(VOID
)
1410 PDRIVER_REINIT_ITEM ReinitItem
;
1413 /* Get the first entry and start looping */
1414 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1415 &DriverReinitListLock
);
1419 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1421 /* Increment reinitialization counter */
1422 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1424 /* Remove the device object flag */
1425 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1427 /* Call the routine */
1428 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1429 ReinitItem
->Context
,
1430 ReinitItem
->DriverObject
->
1431 DriverExtension
->Count
);
1433 /* Free the entry */
1436 /* Move to the next one */
1437 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1438 &DriverReinitListLock
);
1444 IopReinitializeBootDrivers(VOID
)
1446 PDRIVER_REINIT_ITEM ReinitItem
;
1449 /* Get the first entry and start looping */
1450 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1451 &DriverBootReinitListLock
);
1455 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1457 /* Increment reinitialization counter */
1458 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1460 /* Remove the device object flag */
1461 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1463 /* Call the routine */
1464 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1465 ReinitItem
->Context
,
1466 ReinitItem
->DriverObject
->
1467 DriverExtension
->Count
);
1469 /* Free the entry */
1472 /* Move to the next one */
1473 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1474 &DriverBootReinitListLock
);
1480 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1481 IN PDRIVER_INITIALIZE InitializationFunction
,
1482 IN PUNICODE_STRING RegistryPath
,
1483 IN PCUNICODE_STRING ServiceName
,
1484 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1485 OUT PDRIVER_OBJECT
*pDriverObject
)
1487 WCHAR NameBuffer
[100];
1489 UNICODE_STRING LocalDriverName
;
1491 OBJECT_ATTRIBUTES ObjectAttributes
;
1493 PDRIVER_OBJECT DriverObject
;
1494 UNICODE_STRING ServiceKeyName
;
1496 ULONG i
, RetryCount
= 0;
1499 /* First, create a unique name for the driver if we don't have one */
1502 /* Create a random name and set up the string*/
1503 NameLength
= (USHORT
)swprintf(NameBuffer
,
1504 DRIVER_ROOT_NAME L
"%08u",
1505 KeTickCount
.LowPart
);
1506 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1507 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1508 LocalDriverName
.Buffer
= NameBuffer
;
1512 /* So we can avoid another code path, use a local var */
1513 LocalDriverName
= *DriverName
;
1516 /* Initialize the Attributes */
1517 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1518 InitializeObjectAttributes(&ObjectAttributes
,
1520 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1524 /* Create the Object */
1525 Status
= ObCreateObject(KernelMode
,
1533 (PVOID
*)&DriverObject
);
1534 if (!NT_SUCCESS(Status
)) return Status
;
1536 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1538 /* Set up the Object */
1539 RtlZeroMemory(DriverObject
, ObjectSize
);
1540 DriverObject
->Type
= IO_TYPE_DRIVER
;
1541 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1542 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;
1543 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1544 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1545 DriverObject
->DriverInit
= InitializationFunction
;
1546 DriverObject
->DriverSection
= ModuleObject
;
1547 /* Loop all Major Functions */
1548 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1550 /* Invalidate each function */
1551 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1554 /* Set up the service key name buffer */
1555 ServiceKeyName
.MaximumLength
= ServiceName
->Length
+ sizeof(UNICODE_NULL
);
1556 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
1557 ServiceKeyName
.MaximumLength
,
1559 if (!ServiceKeyName
.Buffer
)
1562 ObMakeTemporaryObject(DriverObject
);
1563 ObDereferenceObject(DriverObject
);
1564 return STATUS_INSUFFICIENT_RESOURCES
;
1567 /* Copy the name and set it in the driver extension */
1568 RtlCopyUnicodeString(&ServiceKeyName
,
1570 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1572 /* Make a copy of the driver name to store in the driver object */
1573 DriverObject
->DriverName
.MaximumLength
= LocalDriverName
.Length
;
1574 DriverObject
->DriverName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1575 DriverObject
->DriverName
.MaximumLength
,
1577 if (!DriverObject
->DriverName
.Buffer
)
1580 ObMakeTemporaryObject(DriverObject
);
1581 ObDereferenceObject(DriverObject
);
1582 return STATUS_INSUFFICIENT_RESOURCES
;
1585 RtlCopyUnicodeString(&DriverObject
->DriverName
,
1588 /* Add the Object and get its handle */
1589 Status
= ObInsertObject(DriverObject
,
1596 /* Eliminate small possibility when this function is called more than
1597 once in a row, and KeTickCount doesn't get enough time to change */
1598 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1604 if (!NT_SUCCESS(Status
)) return Status
;
1606 /* Now reference it */
1607 Status
= ObReferenceObjectByHandle(hDriver
,
1611 (PVOID
*)&DriverObject
,
1614 /* Close the extra handle */
1617 if (!NT_SUCCESS(Status
))
1620 ObMakeTemporaryObject(DriverObject
);
1621 ObDereferenceObject(DriverObject
);
1625 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1626 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1627 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1629 /* Finally, call its init function */
1630 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1631 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1632 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1633 if (!NT_SUCCESS(Status
))
1635 /* If it didn't work, then kill the object */
1636 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1637 DriverObject
->DriverSection
= NULL
;
1638 ObMakeTemporaryObject(DriverObject
);
1639 ObDereferenceObject(DriverObject
);
1644 /* Returns to caller the object */
1645 *pDriverObject
= DriverObject
;
1648 /* We're going to say if we don't have any DOs from DriverEntry, then we're not legacy.
1649 * Other parts of the I/O manager depend on this behavior */
1650 if (!DriverObject
->DeviceObject
) DriverObject
->Flags
&= ~DRVO_LEGACY_DRIVER
;
1652 /* Loop all Major Functions */
1653 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1656 * Make sure the driver didn't set any dispatch entry point to NULL!
1657 * Doing so is illegal; drivers shouldn't touch entry points they
1661 /* Check if it did so anyway */
1662 if (!DriverObject
->MajorFunction
[i
])
1664 /* Print a warning in the debug log */
1665 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%lu] to NULL!\n",
1666 &DriverObject
->DriverName
, i
);
1669 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1673 /* Return the Status */
1677 /* PUBLIC FUNCTIONS ***********************************************************/
1684 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1685 IN PDRIVER_INITIALIZE InitializationFunction
)
1687 PDRIVER_OBJECT DriverObject
;
1688 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, DriverName
, NULL
, &DriverObject
);
1696 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1698 /* Simply dereference the Object */
1699 ObDereferenceObject(DriverObject
);
1707 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1708 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1711 PDRIVER_REINIT_ITEM ReinitItem
;
1713 /* Allocate the entry */
1714 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1715 sizeof(DRIVER_REINIT_ITEM
),
1717 if (!ReinitItem
) return;
1720 ReinitItem
->DriverObject
= DriverObject
;
1721 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1722 ReinitItem
->Context
= Context
;
1724 /* Set the Driver Object flag and insert the entry into the list */
1725 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1726 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1727 &ReinitItem
->ItemEntry
,
1728 &DriverBootReinitListLock
);
1736 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1737 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1740 PDRIVER_REINIT_ITEM ReinitItem
;
1742 /* Allocate the entry */
1743 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1744 sizeof(DRIVER_REINIT_ITEM
),
1746 if (!ReinitItem
) return;
1749 ReinitItem
->DriverObject
= DriverObject
;
1750 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1751 ReinitItem
->Context
= Context
;
1753 /* Set the Driver Object flag and insert the entry into the list */
1754 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1755 ExInterlockedInsertTailList(&DriverReinitListHead
,
1756 &ReinitItem
->ItemEntry
,
1757 &DriverReinitListLock
);
1765 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1766 IN PVOID ClientIdentificationAddress
,
1767 IN ULONG DriverObjectExtensionSize
,
1768 OUT PVOID
*DriverObjectExtension
)
1771 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1772 BOOLEAN Inserted
= FALSE
;
1774 /* Assume failure */
1775 *DriverObjectExtension
= NULL
;
1777 /* Allocate the extension */
1778 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1779 sizeof(IO_CLIENT_EXTENSION
) +
1780 DriverObjectExtensionSize
,
1781 TAG_DRIVER_EXTENSION
);
1782 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1784 /* Clear the extension for teh caller */
1785 RtlZeroMemory(NewDriverExtension
,
1786 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1789 OldIrql
= KeRaiseIrqlToDpcLevel();
1791 /* Fill out the extension */
1792 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1794 /* Loop the current extensions */
1795 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1796 ClientDriverExtension
;
1797 while (DriverExtensions
)
1799 /* Check if the identifier matches */
1800 if (DriverExtensions
->ClientIdentificationAddress
==
1801 ClientIdentificationAddress
)
1803 /* We have a collision, break out */
1807 /* Go to the next one */
1808 DriverExtensions
= DriverExtensions
->NextExtension
;
1811 /* Check if we didn't collide */
1812 if (!DriverExtensions
)
1814 /* Link this one in */
1815 NewDriverExtension
->NextExtension
=
1816 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1817 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1822 /* Release the lock */
1823 KeLowerIrql(OldIrql
);
1825 /* Check if insertion failed */
1828 /* Free the entry and fail */
1829 ExFreePoolWithTag(NewDriverExtension
, TAG_DRIVER_EXTENSION
);
1830 return STATUS_OBJECT_NAME_COLLISION
;
1833 /* Otherwise, return the pointer */
1834 *DriverObjectExtension
= NewDriverExtension
+ 1;
1835 return STATUS_SUCCESS
;
1843 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1844 IN PVOID ClientIdentificationAddress
)
1847 PIO_CLIENT_EXTENSION DriverExtensions
;
1850 OldIrql
= KeRaiseIrqlToDpcLevel();
1852 /* Loop the list until we find the right one */
1853 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1854 while (DriverExtensions
)
1856 /* Check for a match */
1857 if (DriverExtensions
->ClientIdentificationAddress
==
1858 ClientIdentificationAddress
)
1865 DriverExtensions
= DriverExtensions
->NextExtension
;
1869 KeLowerIrql(OldIrql
);
1871 /* Return nothing or the extension */
1872 if (!DriverExtensions
) return NULL
;
1873 return DriverExtensions
+ 1;
1878 IopLoadUnloadDriverWorker(
1879 _Inout_ PVOID Parameter
)
1881 PLOAD_UNLOAD_PARAMS LoadParams
= Parameter
;
1883 ASSERT(PsGetCurrentProcess() == PsInitialSystemProcess
);
1884 LoadParams
->Status
= IopLoadUnloadDriver(LoadParams
->RegistryPath
,
1885 &LoadParams
->DriverObject
);
1886 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1891 IopLoadUnloadDriver(
1892 _In_opt_ PCUNICODE_STRING RegistryPath
,
1893 _Inout_ PDRIVER_OBJECT
*DriverObject
)
1895 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1896 UNICODE_STRING ImagePath
;
1897 UNICODE_STRING ServiceName
;
1900 PDEVICE_NODE DeviceNode
;
1901 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1905 /* Load/Unload must be called from system process */
1906 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1908 LOAD_UNLOAD_PARAMS LoadParams
;
1910 /* Prepare parameters block */
1911 LoadParams
.RegistryPath
= RegistryPath
;
1912 LoadParams
.DriverObject
= *DriverObject
;
1913 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1915 /* Initialize and queue a work item */
1916 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1917 IopLoadUnloadDriverWorker
,
1919 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1921 /* And wait till it completes */
1922 KeWaitForSingleObject(&LoadParams
.Event
,
1927 return LoadParams
.Status
;
1930 /* Check if it's an unload request */
1933 (*DriverObject
)->DriverUnload(*DriverObject
);
1934 return STATUS_SUCCESS
;
1937 RtlInitUnicodeString(&ImagePath
, NULL
);
1940 * Get the service name from the registry key name.
1942 ASSERT(RegistryPath
->Length
>= sizeof(WCHAR
));
1944 ServiceName
= *RegistryPath
;
1945 cur
= RegistryPath
->Buffer
+ RegistryPath
->Length
/ sizeof(WCHAR
) - 1;
1946 while (RegistryPath
->Buffer
!= cur
)
1950 ServiceName
.Buffer
= cur
+ 1;
1951 ServiceName
.Length
= RegistryPath
->Length
-
1952 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1953 (ULONG_PTR
)RegistryPath
->Buffer
);
1962 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1964 RtlInitUnicodeString(&ImagePath
, NULL
);
1966 QueryTable
[0].Name
= L
"Type";
1967 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1968 QueryTable
[0].EntryContext
= &Type
;
1970 QueryTable
[1].Name
= L
"ImagePath";
1971 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1972 QueryTable
[1].EntryContext
= &ImagePath
;
1974 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1975 RegistryPath
->Buffer
,
1976 QueryTable
, NULL
, NULL
);
1977 if (!NT_SUCCESS(Status
))
1979 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1980 if (ImagePath
.Buffer
) ExFreePool(ImagePath
.Buffer
);
1985 * Normalize the image path for all later processing.
1987 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1988 if (!NT_SUCCESS(Status
))
1990 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1994 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1995 DPRINT("Type: %lx\n", Type
);
1997 KeEnterCriticalRegion();
1998 ExAcquireResourceExclusiveLite(&IopDriverLoadResource
, TRUE
);
2000 * Get existing DriverObject pointer (in case the driver
2001 * has already been loaded and initialized).
2003 Status
= IopGetDriverObject(DriverObject
,
2005 (Type
== SERVICE_FILE_SYSTEM_DRIVER
||
2006 Type
== SERVICE_RECOGNIZER_DRIVER
));
2008 if (!NT_SUCCESS(Status
))
2011 * Load the driver module
2013 DPRINT("Loading module from %wZ\n", &ImagePath
);
2014 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
2015 if (!NT_SUCCESS(Status
))
2017 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
2018 ExReleaseResourceLite(&IopDriverLoadResource
);
2019 KeLeaveCriticalRegion();
2024 * Initialize the driver module if it's loaded for the first time
2026 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
2027 if (!NT_SUCCESS(Status
))
2029 DPRINT1("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
2030 ExReleaseResourceLite(&IopDriverLoadResource
);
2031 KeLeaveCriticalRegion();
2032 MmUnloadSystemImage(ModuleObject
);
2036 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
2038 Status
= IopInitializeDriverModule(DeviceNode
,
2040 &DeviceNode
->ServiceName
,
2041 (Type
== SERVICE_FILE_SYSTEM_DRIVER
||
2042 Type
== SERVICE_RECOGNIZER_DRIVER
),
2044 if (!NT_SUCCESS(Status
))
2046 DPRINT1("IopInitializeDriverModule() failed (Status %lx)\n", Status
);
2047 ExReleaseResourceLite(&IopDriverLoadResource
);
2048 KeLeaveCriticalRegion();
2049 MmUnloadSystemImage(ModuleObject
);
2053 ExReleaseResourceLite(&IopDriverLoadResource
);
2054 KeLeaveCriticalRegion();
2056 /* Initialize and start device */
2057 IopInitializeDevice(DeviceNode
, *DriverObject
);
2058 Status
= IopStartDevice(DeviceNode
);
2062 ExReleaseResourceLite(&IopDriverLoadResource
);
2063 KeLeaveCriticalRegion();
2065 DPRINT("DriverObject already exist in ObjectManager\n");
2066 Status
= STATUS_IMAGE_ALREADY_LOADED
;
2068 /* IopGetDriverObject references the DriverObject, so dereference it */
2069 ObDereferenceObject(*DriverObject
);
2078 * Loads a device driver.
2082 * Name of the service to load (registry key).
2091 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
2093 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
2094 KPROCESSOR_MODE PreviousMode
;
2095 PDRIVER_OBJECT DriverObject
;
2100 PreviousMode
= KeGetPreviousMode();
2103 * Check security privileges
2106 /* FIXME: Uncomment when privileges will be correctly implemented. */
2108 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
2110 DPRINT("Privilege not held\n");
2111 return STATUS_PRIVILEGE_NOT_HELD
;
2115 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2118 if (!NT_SUCCESS(Status
))
2123 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2125 /* Load driver and call its entry point */
2126 DriverObject
= NULL
;
2127 Status
= IopLoadUnloadDriver(&CapturedDriverServiceName
, &DriverObject
);
2129 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2138 * Unloads a legacy device driver.
2142 * Name of the service to unload (registry key).
2152 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2154 return IopUnloadDriver(DriverServiceName
, FALSE
);