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 if (!NT_SUCCESS(Status
))
924 DPRINT1("Driver '%wZ' load failed, status (%x)\n", ModuleName
, Status
);
928 /* Lookup the new Ldr entry in PsLoadedModuleList */
929 NextEntry
= PsLoadedModuleList
.Flink
;
930 while (NextEntry
!= &PsLoadedModuleList
)
932 LdrEntry
= CONTAINING_RECORD(NextEntry
,
933 LDR_DATA_TABLE_ENTRY
,
935 if (RtlEqualUnicodeString(ModuleName
, &LdrEntry
->BaseDllName
, TRUE
))
940 NextEntry
= NextEntry
->Flink
;
942 ASSERT(NextEntry
!= &PsLoadedModuleList
);
945 * Initialize the driver
947 Status
= IopInitializeDriverModule(DeviceNode
,
949 &DeviceNode
->ServiceName
,
953 if (!NT_SUCCESS(Status
))
958 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
959 if (NT_SUCCESS(Status
))
961 Status
= IopStartDevice(DeviceNode
);
964 /* Remove extra reference from IopInitializeDriverModule */
965 ObDereferenceObject(DriverObject
);
971 * IopInitializeBootDrivers
973 * Initialize boot drivers and free memory for boot files.
984 IopInitializeBootDrivers(VOID
)
986 PLIST_ENTRY ListHead
, NextEntry
, NextEntry2
;
987 PLDR_DATA_TABLE_ENTRY LdrEntry
;
988 PDEVICE_NODE DeviceNode
;
989 PDRIVER_OBJECT DriverObject
;
990 LDR_DATA_TABLE_ENTRY ModuleObject
;
992 UNICODE_STRING DriverName
;
994 PDRIVER_INFORMATION DriverInfo
, DriverInfoTag
;
996 PBOOT_DRIVER_LIST_ENTRY BootEntry
;
997 DPRINT("IopInitializeBootDrivers()\n");
999 /* Use IopRootDeviceNode for now */
1000 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, NULL
, &DeviceNode
);
1001 if (!NT_SUCCESS(Status
)) return;
1003 /* Setup the module object for the RAW FS Driver */
1004 ModuleObject
.DllBase
= NULL
;
1005 ModuleObject
.SizeOfImage
= 0;
1006 ModuleObject
.EntryPoint
= RawFsDriverEntry
;
1007 RtlInitUnicodeString(&DriverName
, L
"RAW");
1010 Status
= IopInitializeDriverModule(DeviceNode
,
1015 if (!NT_SUCCESS(Status
))
1021 /* Now initialize the associated device */
1022 Status
= IopInitializeDevice(DeviceNode
, DriverObject
);
1023 if (!NT_SUCCESS(Status
))
1026 ObDereferenceObject(DriverObject
);
1031 Status
= IopStartDevice(DeviceNode
);
1032 if (!NT_SUCCESS(Status
))
1035 ObDereferenceObject(DriverObject
);
1039 /* Get highest group order index */
1040 IopGroupIndex
= PpInitGetGroupOrderIndex(NULL
);
1041 if (IopGroupIndex
== 0xFFFF) ASSERT(FALSE
);
1043 /* Allocate the group table */
1044 IopGroupTable
= ExAllocatePoolWithTag(PagedPool
,
1045 IopGroupIndex
* sizeof(LIST_ENTRY
),
1047 if (IopGroupTable
== NULL
) ASSERT(FALSE
);
1049 /* Initialize the group table lists */
1050 for (i
= 0; i
< IopGroupIndex
; i
++) InitializeListHead(&IopGroupTable
[i
]);
1052 /* Loop the boot modules */
1053 ListHead
= &KeLoaderBlock
->LoadOrderListHead
;
1054 NextEntry
= ListHead
->Flink
;
1055 while (ListHead
!= NextEntry
)
1058 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1059 LDR_DATA_TABLE_ENTRY
,
1062 /* Check if the DLL needs to be initialized */
1063 if (LdrEntry
->Flags
& LDRP_DRIVER_DEPENDENT_DLL
)
1065 /* Call its entrypoint */
1066 MmCallDllInitialize(LdrEntry
, NULL
);
1069 /* Go to the next driver */
1070 NextEntry
= NextEntry
->Flink
;
1073 /* Loop the boot drivers */
1074 ListHead
= &KeLoaderBlock
->BootDriverListHead
;
1075 NextEntry
= ListHead
->Flink
;
1076 while (ListHead
!= NextEntry
)
1079 BootEntry
= CONTAINING_RECORD(NextEntry
,
1080 BOOT_DRIVER_LIST_ENTRY
,
1083 /* Get the driver loader entry */
1084 LdrEntry
= BootEntry
->LdrEntry
;
1086 /* Allocate our internal accounting structure */
1087 DriverInfo
= ExAllocatePoolWithTag(PagedPool
,
1088 sizeof(DRIVER_INFORMATION
),
1092 /* Zero it and initialize it */
1093 RtlZeroMemory(DriverInfo
, sizeof(DRIVER_INFORMATION
));
1094 InitializeListHead(&DriverInfo
->Link
);
1095 DriverInfo
->DataTableEntry
= BootEntry
;
1097 /* Open the registry key */
1098 Status
= IopOpenRegistryKeyEx(&KeyHandle
,
1100 &BootEntry
->RegistryPath
,
1102 if ((NT_SUCCESS(Status
)) || /* ReactOS HACK for SETUPLDR */
1103 ((KeLoaderBlock
->SetupLdrBlock
) && ((KeyHandle
= (PVOID
)1)))) // yes, it's an assignment!
1105 /* Save the handle */
1106 DriverInfo
->ServiceHandle
= KeyHandle
;
1108 /* Get the group oder index */
1109 Index
= PpInitGetGroupOrderIndex(KeyHandle
);
1111 /* Get the tag position */
1112 DriverInfo
->TagPosition
= PipGetDriverTagPriority(KeyHandle
);
1114 /* Insert it into the list, at the right place */
1115 ASSERT(Index
< IopGroupIndex
);
1116 NextEntry2
= IopGroupTable
[Index
].Flink
;
1117 while (NextEntry2
!= &IopGroupTable
[Index
])
1119 /* Get the driver info */
1120 DriverInfoTag
= CONTAINING_RECORD(NextEntry2
,
1124 /* Check if we found the right tag position */
1125 if (DriverInfoTag
->TagPosition
> DriverInfo
->TagPosition
)
1132 NextEntry2
= NextEntry2
->Flink
;
1135 /* Insert us right before the next entry */
1136 NextEntry2
= NextEntry2
->Blink
;
1137 InsertHeadList(NextEntry2
, &DriverInfo
->Link
);
1141 /* Go to the next driver */
1142 NextEntry
= NextEntry
->Flink
;
1145 /* Loop each group index */
1146 for (i
= 0; i
< IopGroupIndex
; i
++)
1148 /* Loop each group table */
1149 NextEntry
= IopGroupTable
[i
].Flink
;
1150 while (NextEntry
!= &IopGroupTable
[i
])
1153 DriverInfo
= CONTAINING_RECORD(NextEntry
,
1157 /* Get the driver loader entry */
1158 LdrEntry
= DriverInfo
->DataTableEntry
->LdrEntry
;
1161 IopInitializeBuiltinDriver(LdrEntry
);
1164 NextEntry
= NextEntry
->Flink
;
1168 /* In old ROS, the loader list became empty after this point. Simulate. */
1169 InitializeListHead(&KeLoaderBlock
->LoadOrderListHead
);
1175 IopInitializeSystemDrivers(VOID
)
1177 PUNICODE_STRING
*DriverList
, *SavedList
;
1179 /* No system drivers on the boot cd */
1180 if (KeLoaderBlock
->SetupLdrBlock
) return;
1182 /* Get the driver list */
1183 SavedList
= DriverList
= CmGetSystemDriverList();
1189 /* Load the driver */
1190 ZwLoadDriver(*DriverList
);
1192 /* Free the entry */
1193 RtlFreeUnicodeString(*DriverList
);
1194 ExFreePool(*DriverList
);
1197 InbvIndicateProgress();
1202 ExFreePool(SavedList
);
1208 * Unloads a device driver.
1212 * Name of the service to unload (registry key).
1215 * Whether to unload Plug & Plug or only legacy drivers. If this
1216 * parameter is set to FALSE, the routine will unload only legacy
1223 * Guard the whole function by SEH.
1227 IopUnloadDriver(PUNICODE_STRING DriverServiceName
, BOOLEAN UnloadPnpDrivers
)
1229 RTL_QUERY_REGISTRY_TABLE QueryTable
[2];
1230 UNICODE_STRING ImagePath
;
1231 UNICODE_STRING ServiceName
;
1232 UNICODE_STRING ObjectName
;
1233 PDRIVER_OBJECT DriverObject
;
1234 PDEVICE_OBJECT DeviceObject
;
1235 PEXTENDED_DEVOBJ_EXTENSION DeviceExtension
;
1238 BOOLEAN SafeToUnload
= TRUE
;
1240 DPRINT("IopUnloadDriver('%wZ', %u)\n", DriverServiceName
, UnloadPnpDrivers
);
1245 * Get the service name from the registry key name
1248 Start
= wcsrchr(DriverServiceName
->Buffer
, L
'\\');
1250 Start
= DriverServiceName
->Buffer
;
1254 RtlInitUnicodeString(&ServiceName
, Start
);
1257 * Construct the driver object name
1260 ObjectName
.Length
= ((USHORT
)wcslen(Start
) + 8) * sizeof(WCHAR
);
1261 ObjectName
.MaximumLength
= ObjectName
.Length
+ sizeof(WCHAR
);
1262 ObjectName
.Buffer
= ExAllocatePool(PagedPool
, ObjectName
.MaximumLength
);
1263 if (!ObjectName
.Buffer
) return STATUS_INSUFFICIENT_RESOURCES
;
1264 wcscpy(ObjectName
.Buffer
, DRIVER_ROOT_NAME
);
1265 memcpy(ObjectName
.Buffer
+ 8, Start
, ObjectName
.Length
- 8 * sizeof(WCHAR
));
1266 ObjectName
.Buffer
[ObjectName
.Length
/sizeof(WCHAR
)] = 0;
1269 * Find the driver object
1271 Status
= ObReferenceObjectByName(&ObjectName
,
1278 (PVOID
*)&DriverObject
);
1280 if (!NT_SUCCESS(Status
))
1282 DPRINT1("Can't locate driver object for %wZ\n", &ObjectName
);
1283 ExFreePool(ObjectName
.Buffer
);
1288 * Free the buffer for driver object name
1290 ExFreePool(ObjectName
.Buffer
);
1292 /* Check that driver is not already unloading */
1293 if (DriverObject
->Flags
& DRVO_UNLOAD_INVOKED
)
1295 DPRINT1("Driver deletion pending\n");
1296 ObDereferenceObject(DriverObject
);
1297 return STATUS_DELETE_PENDING
;
1301 * Get path of service...
1303 RtlZeroMemory(QueryTable
, sizeof(QueryTable
));
1305 RtlInitUnicodeString(&ImagePath
, NULL
);
1307 QueryTable
[0].Name
= L
"ImagePath";
1308 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1309 QueryTable
[0].EntryContext
= &ImagePath
;
1311 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1312 DriverServiceName
->Buffer
,
1317 if (!NT_SUCCESS(Status
))
1319 DPRINT1("RtlQueryRegistryValues() failed (Status %x)\n", Status
);
1320 ObDereferenceObject(DriverObject
);
1325 * Normalize the image path for all later processing.
1327 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1329 if (!NT_SUCCESS(Status
))
1331 DPRINT1("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1332 ObDereferenceObject(DriverObject
);
1337 * Free the service path
1339 ExFreePool(ImagePath
.Buffer
);
1342 * Unload the module and release the references to the device object
1345 /* Call the load/unload routine, depending on current process */
1346 if (DriverObject
->DriverUnload
&& DriverObject
->DriverSection
&&
1347 (UnloadPnpDrivers
|| (DriverObject
->Flags
& DRVO_LEGACY_DRIVER
)))
1349 /* Loop through each device object of the driver
1350 and set DOE_UNLOAD_PENDING flag */
1351 DeviceObject
= DriverObject
->DeviceObject
;
1352 while (DeviceObject
)
1354 /* Set the unload pending flag for the device */
1355 DeviceExtension
= IoGetDevObjExtension(DeviceObject
);
1356 DeviceExtension
->ExtensionFlags
|= DOE_UNLOAD_PENDING
;
1358 /* Make sure there are no attached devices or no reference counts */
1359 if ((DeviceObject
->ReferenceCount
) || (DeviceObject
->AttachedDevice
))
1361 /* Not safe to unload */
1362 DPRINT1("Drivers device object is referenced or has attached devices\n");
1364 SafeToUnload
= FALSE
;
1367 DeviceObject
= DeviceObject
->NextDevice
;
1370 /* If not safe to unload, then return success */
1373 ObDereferenceObject(DriverObject
);
1374 return STATUS_SUCCESS
;
1377 DPRINT1("Unloading driver '%wZ' (manual)\n", &DriverObject
->DriverName
);
1379 /* Set the unload invoked flag and call the unload routine */
1380 DriverObject
->Flags
|= DRVO_UNLOAD_INVOKED
;
1381 Status
= IopLoadUnloadDriver(NULL
, &DriverObject
);
1382 ASSERT(Status
== STATUS_SUCCESS
);
1384 /* Mark the driver object temporary, so it could be deleted later */
1385 ObMakeTemporaryObject(DriverObject
);
1387 /* Dereference it 2 times */
1388 ObDereferenceObject(DriverObject
);
1389 ObDereferenceObject(DriverObject
);
1395 DPRINT1("No DriverUnload function! '%wZ' will not be unloaded!\n", &DriverObject
->DriverName
);
1397 /* Dereference one time (refd inside this function) */
1398 ObDereferenceObject(DriverObject
);
1400 /* Return unloading failure */
1401 return STATUS_INVALID_DEVICE_REQUEST
;
1407 IopReinitializeDrivers(VOID
)
1409 PDRIVER_REINIT_ITEM ReinitItem
;
1412 /* Get the first entry and start looping */
1413 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1414 &DriverReinitListLock
);
1418 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1420 /* Increment reinitialization counter */
1421 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1423 /* Remove the device object flag */
1424 ReinitItem
->DriverObject
->Flags
&= ~DRVO_REINIT_REGISTERED
;
1426 /* Call the routine */
1427 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1428 ReinitItem
->Context
,
1429 ReinitItem
->DriverObject
->
1430 DriverExtension
->Count
);
1432 /* Free the entry */
1435 /* Move to the next one */
1436 Entry
= ExInterlockedRemoveHeadList(&DriverReinitListHead
,
1437 &DriverReinitListLock
);
1443 IopReinitializeBootDrivers(VOID
)
1445 PDRIVER_REINIT_ITEM ReinitItem
;
1448 /* Get the first entry and start looping */
1449 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1450 &DriverBootReinitListLock
);
1454 ReinitItem
= CONTAINING_RECORD(Entry
, DRIVER_REINIT_ITEM
, ItemEntry
);
1456 /* Increment reinitialization counter */
1457 ReinitItem
->DriverObject
->DriverExtension
->Count
++;
1459 /* Remove the device object flag */
1460 ReinitItem
->DriverObject
->Flags
&= ~DRVO_BOOTREINIT_REGISTERED
;
1462 /* Call the routine */
1463 ReinitItem
->ReinitRoutine(ReinitItem
->DriverObject
,
1464 ReinitItem
->Context
,
1465 ReinitItem
->DriverObject
->
1466 DriverExtension
->Count
);
1468 /* Free the entry */
1471 /* Move to the next one */
1472 Entry
= ExInterlockedRemoveHeadList(&DriverBootReinitListHead
,
1473 &DriverBootReinitListLock
);
1479 IopCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1480 IN PDRIVER_INITIALIZE InitializationFunction
,
1481 IN PUNICODE_STRING RegistryPath
,
1482 IN PCUNICODE_STRING ServiceName
,
1483 PLDR_DATA_TABLE_ENTRY ModuleObject
,
1484 OUT PDRIVER_OBJECT
*pDriverObject
)
1486 WCHAR NameBuffer
[100];
1488 UNICODE_STRING LocalDriverName
;
1490 OBJECT_ATTRIBUTES ObjectAttributes
;
1492 PDRIVER_OBJECT DriverObject
;
1493 UNICODE_STRING ServiceKeyName
;
1495 ULONG i
, RetryCount
= 0;
1498 /* First, create a unique name for the driver if we don't have one */
1501 /* Create a random name and set up the string*/
1502 NameLength
= (USHORT
)swprintf(NameBuffer
,
1503 DRIVER_ROOT_NAME L
"%08u",
1504 KeTickCount
.LowPart
);
1505 LocalDriverName
.Length
= NameLength
* sizeof(WCHAR
);
1506 LocalDriverName
.MaximumLength
= LocalDriverName
.Length
+ sizeof(UNICODE_NULL
);
1507 LocalDriverName
.Buffer
= NameBuffer
;
1511 /* So we can avoid another code path, use a local var */
1512 LocalDriverName
= *DriverName
;
1515 /* Initialize the Attributes */
1516 ObjectSize
= sizeof(DRIVER_OBJECT
) + sizeof(EXTENDED_DRIVER_EXTENSION
);
1517 InitializeObjectAttributes(&ObjectAttributes
,
1519 OBJ_PERMANENT
| OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1523 /* Create the Object */
1524 Status
= ObCreateObject(KernelMode
,
1532 (PVOID
*)&DriverObject
);
1533 if (!NT_SUCCESS(Status
)) return Status
;
1535 DPRINT("IopCreateDriver(): created DO %p\n", DriverObject
);
1537 /* Set up the Object */
1538 RtlZeroMemory(DriverObject
, ObjectSize
);
1539 DriverObject
->Type
= IO_TYPE_DRIVER
;
1540 DriverObject
->Size
= sizeof(DRIVER_OBJECT
);
1541 DriverObject
->Flags
= DRVO_LEGACY_DRIVER
;
1542 DriverObject
->DriverExtension
= (PDRIVER_EXTENSION
)(DriverObject
+ 1);
1543 DriverObject
->DriverExtension
->DriverObject
= DriverObject
;
1544 DriverObject
->DriverInit
= InitializationFunction
;
1545 DriverObject
->DriverSection
= ModuleObject
;
1546 /* Loop all Major Functions */
1547 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1549 /* Invalidate each function */
1550 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1553 /* Set up the service key name buffer */
1554 ServiceKeyName
.MaximumLength
= ServiceName
->Length
+ sizeof(UNICODE_NULL
);
1555 ServiceKeyName
.Buffer
= ExAllocatePoolWithTag(NonPagedPool
,
1556 ServiceKeyName
.MaximumLength
,
1558 if (!ServiceKeyName
.Buffer
)
1561 ObMakeTemporaryObject(DriverObject
);
1562 ObDereferenceObject(DriverObject
);
1563 return STATUS_INSUFFICIENT_RESOURCES
;
1566 /* Copy the name and set it in the driver extension */
1567 RtlCopyUnicodeString(&ServiceKeyName
,
1569 DriverObject
->DriverExtension
->ServiceKeyName
= ServiceKeyName
;
1571 /* Make a copy of the driver name to store in the driver object */
1572 DriverObject
->DriverName
.MaximumLength
= LocalDriverName
.Length
;
1573 DriverObject
->DriverName
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
1574 DriverObject
->DriverName
.MaximumLength
,
1576 if (!DriverObject
->DriverName
.Buffer
)
1579 ObMakeTemporaryObject(DriverObject
);
1580 ObDereferenceObject(DriverObject
);
1581 return STATUS_INSUFFICIENT_RESOURCES
;
1584 RtlCopyUnicodeString(&DriverObject
->DriverName
,
1587 /* Add the Object and get its handle */
1588 Status
= ObInsertObject(DriverObject
,
1595 /* Eliminate small possibility when this function is called more than
1596 once in a row, and KeTickCount doesn't get enough time to change */
1597 if (!DriverName
&& (Status
== STATUS_OBJECT_NAME_COLLISION
) && (RetryCount
< 100))
1603 if (!NT_SUCCESS(Status
)) return Status
;
1605 /* Now reference it */
1606 Status
= ObReferenceObjectByHandle(hDriver
,
1610 (PVOID
*)&DriverObject
,
1613 /* Close the extra handle */
1616 if (!NT_SUCCESS(Status
))
1619 ObMakeTemporaryObject(DriverObject
);
1620 ObDereferenceObject(DriverObject
);
1624 DriverObject
->HardwareDatabase
= &IopHardwareDatabaseKey
;
1625 DriverObject
->DriverStart
= ModuleObject
? ModuleObject
->DllBase
: 0;
1626 DriverObject
->DriverSize
= ModuleObject
? ModuleObject
->SizeOfImage
: 0;
1628 /* Finally, call its init function */
1629 DPRINT("RegistryKey: %wZ\n", RegistryPath
);
1630 DPRINT("Calling driver entrypoint at %p\n", InitializationFunction
);
1631 Status
= (*InitializationFunction
)(DriverObject
, RegistryPath
);
1632 if (!NT_SUCCESS(Status
))
1634 /* If it didn't work, then kill the object */
1635 DPRINT1("'%wZ' initialization failed, status (0x%08lx)\n", DriverName
, Status
);
1636 DriverObject
->DriverSection
= NULL
;
1637 ObMakeTemporaryObject(DriverObject
);
1638 ObDereferenceObject(DriverObject
);
1643 /* Returns to caller the object */
1644 *pDriverObject
= DriverObject
;
1647 /* We're going to say if we don't have any DOs from DriverEntry, then we're not legacy.
1648 * Other parts of the I/O manager depend on this behavior */
1649 if (!DriverObject
->DeviceObject
) DriverObject
->Flags
&= ~DRVO_LEGACY_DRIVER
;
1651 /* Loop all Major Functions */
1652 for (i
= 0; i
<= IRP_MJ_MAXIMUM_FUNCTION
; i
++)
1655 * Make sure the driver didn't set any dispatch entry point to NULL!
1656 * Doing so is illegal; drivers shouldn't touch entry points they
1660 /* Check if it did so anyway */
1661 if (!DriverObject
->MajorFunction
[i
])
1663 /* Print a warning in the debug log */
1664 DPRINT1("Driver <%wZ> set DriverObject->MajorFunction[%lu] to NULL!\n",
1665 &DriverObject
->DriverName
, i
);
1668 DriverObject
->MajorFunction
[i
] = IopInvalidDeviceRequest
;
1672 /* Return the Status */
1676 /* PUBLIC FUNCTIONS ***********************************************************/
1683 IoCreateDriver(IN PUNICODE_STRING DriverName OPTIONAL
,
1684 IN PDRIVER_INITIALIZE InitializationFunction
)
1686 PDRIVER_OBJECT DriverObject
;
1687 return IopCreateDriver(DriverName
, InitializationFunction
, NULL
, DriverName
, NULL
, &DriverObject
);
1695 IoDeleteDriver(IN PDRIVER_OBJECT DriverObject
)
1697 /* Simply dereference the Object */
1698 ObDereferenceObject(DriverObject
);
1706 IoRegisterBootDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1707 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1710 PDRIVER_REINIT_ITEM ReinitItem
;
1712 /* Allocate the entry */
1713 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1714 sizeof(DRIVER_REINIT_ITEM
),
1716 if (!ReinitItem
) return;
1719 ReinitItem
->DriverObject
= DriverObject
;
1720 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1721 ReinitItem
->Context
= Context
;
1723 /* Set the Driver Object flag and insert the entry into the list */
1724 DriverObject
->Flags
|= DRVO_BOOTREINIT_REGISTERED
;
1725 ExInterlockedInsertTailList(&DriverBootReinitListHead
,
1726 &ReinitItem
->ItemEntry
,
1727 &DriverBootReinitListLock
);
1735 IoRegisterDriverReinitialization(IN PDRIVER_OBJECT DriverObject
,
1736 IN PDRIVER_REINITIALIZE ReinitRoutine
,
1739 PDRIVER_REINIT_ITEM ReinitItem
;
1741 /* Allocate the entry */
1742 ReinitItem
= ExAllocatePoolWithTag(NonPagedPool
,
1743 sizeof(DRIVER_REINIT_ITEM
),
1745 if (!ReinitItem
) return;
1748 ReinitItem
->DriverObject
= DriverObject
;
1749 ReinitItem
->ReinitRoutine
= ReinitRoutine
;
1750 ReinitItem
->Context
= Context
;
1752 /* Set the Driver Object flag and insert the entry into the list */
1753 DriverObject
->Flags
|= DRVO_REINIT_REGISTERED
;
1754 ExInterlockedInsertTailList(&DriverReinitListHead
,
1755 &ReinitItem
->ItemEntry
,
1756 &DriverReinitListLock
);
1764 IoAllocateDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1765 IN PVOID ClientIdentificationAddress
,
1766 IN ULONG DriverObjectExtensionSize
,
1767 OUT PVOID
*DriverObjectExtension
)
1770 PIO_CLIENT_EXTENSION DriverExtensions
, NewDriverExtension
;
1771 BOOLEAN Inserted
= FALSE
;
1773 /* Assume failure */
1774 *DriverObjectExtension
= NULL
;
1776 /* Allocate the extension */
1777 NewDriverExtension
= ExAllocatePoolWithTag(NonPagedPool
,
1778 sizeof(IO_CLIENT_EXTENSION
) +
1779 DriverObjectExtensionSize
,
1780 TAG_DRIVER_EXTENSION
);
1781 if (!NewDriverExtension
) return STATUS_INSUFFICIENT_RESOURCES
;
1783 /* Clear the extension for teh caller */
1784 RtlZeroMemory(NewDriverExtension
,
1785 sizeof(IO_CLIENT_EXTENSION
) + DriverObjectExtensionSize
);
1788 OldIrql
= KeRaiseIrqlToDpcLevel();
1790 /* Fill out the extension */
1791 NewDriverExtension
->ClientIdentificationAddress
= ClientIdentificationAddress
;
1793 /* Loop the current extensions */
1794 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->
1795 ClientDriverExtension
;
1796 while (DriverExtensions
)
1798 /* Check if the identifier matches */
1799 if (DriverExtensions
->ClientIdentificationAddress
==
1800 ClientIdentificationAddress
)
1802 /* We have a collision, break out */
1806 /* Go to the next one */
1807 DriverExtensions
= DriverExtensions
->NextExtension
;
1810 /* Check if we didn't collide */
1811 if (!DriverExtensions
)
1813 /* Link this one in */
1814 NewDriverExtension
->NextExtension
=
1815 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1816 IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
=
1821 /* Release the lock */
1822 KeLowerIrql(OldIrql
);
1824 /* Check if insertion failed */
1827 /* Free the entry and fail */
1828 ExFreePoolWithTag(NewDriverExtension
, TAG_DRIVER_EXTENSION
);
1829 return STATUS_OBJECT_NAME_COLLISION
;
1832 /* Otherwise, return the pointer */
1833 *DriverObjectExtension
= NewDriverExtension
+ 1;
1834 return STATUS_SUCCESS
;
1842 IoGetDriverObjectExtension(IN PDRIVER_OBJECT DriverObject
,
1843 IN PVOID ClientIdentificationAddress
)
1846 PIO_CLIENT_EXTENSION DriverExtensions
;
1849 OldIrql
= KeRaiseIrqlToDpcLevel();
1851 /* Loop the list until we find the right one */
1852 DriverExtensions
= IoGetDrvObjExtension(DriverObject
)->ClientDriverExtension
;
1853 while (DriverExtensions
)
1855 /* Check for a match */
1856 if (DriverExtensions
->ClientIdentificationAddress
==
1857 ClientIdentificationAddress
)
1864 DriverExtensions
= DriverExtensions
->NextExtension
;
1868 KeLowerIrql(OldIrql
);
1870 /* Return nothing or the extension */
1871 if (!DriverExtensions
) return NULL
;
1872 return DriverExtensions
+ 1;
1877 IopLoadUnloadDriverWorker(
1878 _Inout_ PVOID Parameter
)
1880 PLOAD_UNLOAD_PARAMS LoadParams
= Parameter
;
1882 ASSERT(PsGetCurrentProcess() == PsInitialSystemProcess
);
1883 LoadParams
->Status
= IopLoadUnloadDriver(LoadParams
->RegistryPath
,
1884 &LoadParams
->DriverObject
);
1885 KeSetEvent(&LoadParams
->Event
, 0, FALSE
);
1890 IopLoadUnloadDriver(
1891 _In_opt_ PCUNICODE_STRING RegistryPath
,
1892 _Inout_ PDRIVER_OBJECT
*DriverObject
)
1894 RTL_QUERY_REGISTRY_TABLE QueryTable
[3];
1895 UNICODE_STRING ImagePath
;
1896 UNICODE_STRING ServiceName
;
1899 PDEVICE_NODE DeviceNode
;
1900 PLDR_DATA_TABLE_ENTRY ModuleObject
;
1904 /* Load/Unload must be called from system process */
1905 if (PsGetCurrentProcess() != PsInitialSystemProcess
)
1907 LOAD_UNLOAD_PARAMS LoadParams
;
1909 /* Prepare parameters block */
1910 LoadParams
.RegistryPath
= RegistryPath
;
1911 LoadParams
.DriverObject
= *DriverObject
;
1912 KeInitializeEvent(&LoadParams
.Event
, NotificationEvent
, FALSE
);
1914 /* Initialize and queue a work item */
1915 ExInitializeWorkItem(&LoadParams
.WorkItem
,
1916 IopLoadUnloadDriverWorker
,
1918 ExQueueWorkItem(&LoadParams
.WorkItem
, DelayedWorkQueue
);
1920 /* And wait till it completes */
1921 KeWaitForSingleObject(&LoadParams
.Event
,
1926 return LoadParams
.Status
;
1929 /* Check if it's an unload request */
1932 (*DriverObject
)->DriverUnload(*DriverObject
);
1933 return STATUS_SUCCESS
;
1936 RtlInitUnicodeString(&ImagePath
, NULL
);
1939 * Get the service name from the registry key name.
1941 ASSERT(RegistryPath
->Length
>= sizeof(WCHAR
));
1943 ServiceName
= *RegistryPath
;
1944 cur
= RegistryPath
->Buffer
+ RegistryPath
->Length
/ sizeof(WCHAR
) - 1;
1945 while (RegistryPath
->Buffer
!= cur
)
1949 ServiceName
.Buffer
= cur
+ 1;
1950 ServiceName
.Length
= RegistryPath
->Length
-
1951 (USHORT
)((ULONG_PTR
)ServiceName
.Buffer
-
1952 (ULONG_PTR
)RegistryPath
->Buffer
);
1961 RtlZeroMemory(&QueryTable
, sizeof(QueryTable
));
1963 RtlInitUnicodeString(&ImagePath
, NULL
);
1965 QueryTable
[0].Name
= L
"Type";
1966 QueryTable
[0].Flags
= RTL_QUERY_REGISTRY_DIRECT
| RTL_QUERY_REGISTRY_REQUIRED
;
1967 QueryTable
[0].EntryContext
= &Type
;
1969 QueryTable
[1].Name
= L
"ImagePath";
1970 QueryTable
[1].Flags
= RTL_QUERY_REGISTRY_DIRECT
;
1971 QueryTable
[1].EntryContext
= &ImagePath
;
1973 Status
= RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE
,
1974 RegistryPath
->Buffer
,
1975 QueryTable
, NULL
, NULL
);
1976 if (!NT_SUCCESS(Status
))
1978 DPRINT("RtlQueryRegistryValues() failed (Status %lx)\n", Status
);
1979 if (ImagePath
.Buffer
) ExFreePool(ImagePath
.Buffer
);
1984 * Normalize the image path for all later processing.
1986 Status
= IopNormalizeImagePath(&ImagePath
, &ServiceName
);
1987 if (!NT_SUCCESS(Status
))
1989 DPRINT("IopNormalizeImagePath() failed (Status %x)\n", Status
);
1993 DPRINT("FullImagePath: '%wZ'\n", &ImagePath
);
1994 DPRINT("Type: %lx\n", Type
);
1996 KeEnterCriticalRegion();
1997 ExAcquireResourceExclusiveLite(&IopDriverLoadResource
, TRUE
);
1999 * Get existing DriverObject pointer (in case the driver
2000 * has already been loaded and initialized).
2002 Status
= IopGetDriverObject(DriverObject
,
2004 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
2005 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */));
2007 if (!NT_SUCCESS(Status
))
2010 * Load the driver module
2012 DPRINT("Loading module from %wZ\n", &ImagePath
);
2013 Status
= MmLoadSystemImage(&ImagePath
, NULL
, NULL
, 0, (PVOID
)&ModuleObject
, &BaseAddress
);
2014 if (!NT_SUCCESS(Status
))
2016 DPRINT("MmLoadSystemImage() failed (Status %lx)\n", Status
);
2017 ExReleaseResourceLite(&IopDriverLoadResource
);
2018 KeLeaveCriticalRegion();
2023 * Initialize the driver module if it's loaded for the first time
2025 Status
= IopCreateDeviceNode(IopRootDeviceNode
, NULL
, &ServiceName
, &DeviceNode
);
2026 if (!NT_SUCCESS(Status
))
2028 DPRINT1("IopCreateDeviceNode() failed (Status %lx)\n", Status
);
2029 ExReleaseResourceLite(&IopDriverLoadResource
);
2030 KeLeaveCriticalRegion();
2031 MmUnloadSystemImage(ModuleObject
);
2035 IopDisplayLoadingMessage(&DeviceNode
->ServiceName
);
2037 Status
= IopInitializeDriverModule(DeviceNode
,
2039 &DeviceNode
->ServiceName
,
2040 (Type
== 2 /* SERVICE_FILE_SYSTEM_DRIVER */ ||
2041 Type
== 8 /* SERVICE_RECOGNIZER_DRIVER */),
2043 if (!NT_SUCCESS(Status
))
2045 DPRINT1("IopInitializeDriverModule() failed (Status %lx)\n", Status
);
2046 ExReleaseResourceLite(&IopDriverLoadResource
);
2047 KeLeaveCriticalRegion();
2048 MmUnloadSystemImage(ModuleObject
);
2052 ExReleaseResourceLite(&IopDriverLoadResource
);
2053 KeLeaveCriticalRegion();
2055 /* Initialize and start device */
2056 IopInitializeDevice(DeviceNode
, *DriverObject
);
2057 Status
= IopStartDevice(DeviceNode
);
2061 ExReleaseResourceLite(&IopDriverLoadResource
);
2062 KeLeaveCriticalRegion();
2064 DPRINT("DriverObject already exist in ObjectManager\n");
2065 Status
= STATUS_IMAGE_ALREADY_LOADED
;
2067 /* IopGetDriverObject references the DriverObject, so dereference it */
2068 ObDereferenceObject(*DriverObject
);
2077 * Loads a device driver.
2081 * Name of the service to load (registry key).
2090 NtLoadDriver(IN PUNICODE_STRING DriverServiceName
)
2092 UNICODE_STRING CapturedDriverServiceName
= { 0, 0, NULL
};
2093 KPROCESSOR_MODE PreviousMode
;
2094 PDRIVER_OBJECT DriverObject
;
2099 PreviousMode
= KeGetPreviousMode();
2102 * Check security privileges
2105 /* FIXME: Uncomment when privileges will be correctly implemented. */
2107 if (!SeSinglePrivilegeCheck(SeLoadDriverPrivilege
, PreviousMode
))
2109 DPRINT("Privilege not held\n");
2110 return STATUS_PRIVILEGE_NOT_HELD
;
2114 Status
= ProbeAndCaptureUnicodeString(&CapturedDriverServiceName
,
2117 if (!NT_SUCCESS(Status
))
2122 DPRINT("NtLoadDriver('%wZ')\n", &CapturedDriverServiceName
);
2124 /* Load driver and call its entry point */
2125 DriverObject
= NULL
;
2126 Status
= IopLoadUnloadDriver(&CapturedDriverServiceName
, &DriverObject
);
2128 ReleaseCapturedUnicodeString(&CapturedDriverServiceName
,
2137 * Unloads a legacy device driver.
2141 * Name of the service to unload (registry key).
2151 NtUnloadDriver(IN PUNICODE_STRING DriverServiceName
)
2153 return IopUnloadDriver(DriverServiceName
, FALSE
);