2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/config/cmsysini.c
5 * PURPOSE: Configuration Manager - System Initialization Code
6 * PROGRAMMERS: ReactOS Portable Systems Group
7 * Alex Ionescu (alex.ionescu@reactos.org)
10 /* INCLUDES *******************************************************************/
16 POBJECT_TYPE CmpKeyObjectType
;
17 PCMHIVE CmiVolatileHive
;
18 LIST_ENTRY CmpHiveListHead
;
19 ERESOURCE CmpRegistryLock
;
20 KGUARDED_MUTEX CmpSelfHealQueueLock
;
21 LIST_ENTRY CmpSelfHealQueueListHead
;
22 KEVENT CmpLoadWorkerEvent
;
23 LONG CmpLoadWorkerIncrement
;
24 PEPROCESS CmpSystemProcess
;
25 BOOLEAN HvShutdownComplete
;
26 PVOID CmpRegistryLockCallerCaller
, CmpRegistryLockCaller
;
27 BOOLEAN CmpFlushOnLockRelease
;
28 BOOLEAN CmpSpecialBootCondition
;
30 BOOLEAN CmpWasSetupBoot
;
31 BOOLEAN CmpProfileLoaded
;
32 BOOLEAN CmpNoVolatileCreates
;
33 ULONG CmpTraceLevel
= 0;
35 extern LONG CmpFlushStarveWriters
;
36 extern BOOLEAN CmFirstTime
;
38 /* FUNCTIONS ******************************************************************/
43 _In_z_ PCWSTR LinkKeyName
,
44 _In_z_ PCWSTR TargetKeyName
)
47 OBJECT_ATTRIBUTES ObjectAttributes
;
48 UNICODE_STRING KeyName
;
54 /* Initialize the object attributes */
55 RtlInitUnicodeString(&KeyName
, LinkKeyName
);
56 InitializeObjectAttributes(&ObjectAttributes
,
58 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
62 /* Create the link key */
63 Status
= ZwCreateKey(&LinkKeyHandle
,
68 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
70 if (!NT_SUCCESS(Status
))
72 DPRINT1("CM: CmpLinkKeyToHive: couldn't create %S, Status = 0x%lx\n",
77 /* Check if the new key was actually created */
78 if (Disposition
!= REG_CREATED_NEW_KEY
)
80 DPRINT1("CM: CmpLinkKeyToHive: %S already exists!\n", LinkKeyName
);
81 ZwClose(LinkKeyHandle
);
85 /* Set the target key name as link target */
86 RtlInitUnicodeString(&KeyName
, TargetKeyName
);
87 Status
= ZwSetValueKey(LinkKeyHandle
,
88 &CmSymbolicLinkValueName
,
94 /* Close the link key handle */
95 ObCloseHandle(LinkKeyHandle
, KernelMode
);
97 if (!NT_SUCCESS(Status
))
99 DPRINT1("CM: CmpLinkKeyToHive: couldn't create symbolic link for %S, Status = 0x%lx\n",
100 TargetKeyName
, Status
);
109 CmpDeleteKeyObject(PVOID DeletedObject
)
111 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)DeletedObject
;
112 PCM_KEY_CONTROL_BLOCK Kcb
;
113 REG_KEY_HANDLE_CLOSE_INFORMATION KeyHandleCloseInfo
;
114 REG_POST_OPERATION_INFORMATION PostOperationInfo
;
118 /* First off, prepare the handle close information callback */
119 PostOperationInfo
.Object
= KeyBody
;
120 KeyHandleCloseInfo
.Object
= KeyBody
;
121 Status
= CmiCallRegisteredCallbacks(RegNtPreKeyHandleClose
,
122 &KeyHandleCloseInfo
);
123 if (!NT_SUCCESS(Status
))
125 /* If we failed, notify the post routine */
126 PostOperationInfo
.Status
= Status
;
127 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
131 /* Acquire hive lock */
134 /* Make sure this is a valid key body */
135 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
138 Kcb
= KeyBody
->KeyControlBlock
;
142 DelistKeyBodyFromKCB(KeyBody
, FALSE
);
144 /* Dereference the KCB */
145 CmpDelayDerefKeyControlBlock(Kcb
);
149 /* Release the registry lock */
152 /* Do the post callback */
153 PostOperationInfo
.Status
= STATUS_SUCCESS
;
154 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
159 CmpCloseKeyObject(IN PEPROCESS Process OPTIONAL
,
161 IN ACCESS_MASK GrantedAccess
,
162 IN ULONG ProcessHandleCount
,
163 IN ULONG SystemHandleCount
)
165 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)Object
;
168 /* Don't do anything if we're not the last handle */
169 if (SystemHandleCount
> 1) return;
171 /* Make sure we're a valid key body */
172 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
174 /* Don't do anything if we don't have a notify block */
175 if (!KeyBody
->NotifyBlock
) return;
177 /* This shouldn't happen yet */
184 CmpQueryKeyName(IN PVOID ObjectBody
,
186 IN OUT POBJECT_NAME_INFORMATION ObjectNameInfo
,
188 OUT PULONG ReturnLength
,
189 IN KPROCESSOR_MODE PreviousMode
)
191 PUNICODE_STRING KeyName
;
193 NTSTATUS Status
= STATUS_SUCCESS
;
194 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)ObjectBody
;
195 PCM_KEY_CONTROL_BLOCK Kcb
= KeyBody
->KeyControlBlock
;
197 /* Acquire hive lock */
200 /* Lock KCB shared */
201 CmpAcquireKcbLockShared(Kcb
);
203 /* Check if it's a deleted block */
206 /* Release the locks */
207 CmpReleaseKcbLock(Kcb
);
210 /* Let the caller know it's deleted */
211 return STATUS_KEY_DELETED
;
215 KeyName
= CmpConstructName(Kcb
);
217 /* Release the locks */
218 CmpReleaseKcbLock(Kcb
);
221 /* Check if we got the name */
222 if (!KeyName
) return STATUS_INSUFFICIENT_RESOURCES
;
224 /* Set the returned length */
225 *ReturnLength
= KeyName
->Length
+ sizeof(OBJECT_NAME_INFORMATION
) + sizeof(WCHAR
);
227 /* Calculate amount of bytes to copy into the buffer */
228 BytesToCopy
= KeyName
->Length
+ sizeof(WCHAR
);
230 /* Check if the provided buffer is too small to fit even anything */
231 if ((Length
<= sizeof(OBJECT_NAME_INFORMATION
)) ||
232 ((Length
< (*ReturnLength
)) && (BytesToCopy
< sizeof(WCHAR
))))
234 /* Free the buffer allocated by CmpConstructName */
235 ExFreePoolWithTag(KeyName
, TAG_CM
);
237 /* Return buffer length failure without writing anything there because nothing fits */
238 return STATUS_INFO_LENGTH_MISMATCH
;
241 /* Check if the provided buffer can be partially written */
242 if (Length
< (*ReturnLength
))
244 /* Yes, indicate so in the return status */
245 Status
= STATUS_INFO_LENGTH_MISMATCH
;
247 /* Calculate amount of bytes which the provided buffer could handle */
248 BytesToCopy
= Length
- sizeof(OBJECT_NAME_INFORMATION
);
251 /* Remove the null termination character from the size */
252 BytesToCopy
-= sizeof(WCHAR
);
254 /* Fill in the result */
257 /* Return data to user */
258 ObjectNameInfo
->Name
.Buffer
= (PWCHAR
)(ObjectNameInfo
+ 1);
259 ObjectNameInfo
->Name
.MaximumLength
= KeyName
->Length
;
260 ObjectNameInfo
->Name
.Length
= KeyName
->Length
;
262 /* Copy string content*/
263 RtlCopyMemory(ObjectNameInfo
->Name
.Buffer
,
267 /* Null terminate it */
268 ObjectNameInfo
->Name
.Buffer
[BytesToCopy
/ sizeof(WCHAR
)] = UNICODE_NULL
;
270 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
273 Status
= _SEH2_GetExceptionCode();
277 /* Free the buffer allocated by CmpConstructName */
278 ExFreePoolWithTag(KeyName
, TAG_CM
);
286 CmpInitHiveFromFile(IN PCUNICODE_STRING HiveName
,
292 ULONG HiveDisposition
, LogDisposition
;
293 HANDLE FileHandle
= NULL
, LogHandle
= NULL
;
295 ULONG Operation
, FileType
;
302 /* Open or create the hive files */
303 Status
= CmpOpenHiveFiles(HiveName
,
313 if (!NT_SUCCESS(Status
)) return Status
;
315 /* Check if we have a log handle */
316 FileType
= (LogHandle
) ? HFILE_TYPE_LOG
: HFILE_TYPE_PRIMARY
;
318 /* Check if we created or opened the hive */
319 if (HiveDisposition
== FILE_CREATED
)
321 /* Do a create operation */
322 Operation
= HINIT_CREATE
;
327 /* Open it as a file */
328 Operation
= HINIT_FILE
;
332 /* Check if we're sharing hives */
333 if (CmpShareSystemHives
)
335 /* Then force using the primary hive */
336 FileType
= HFILE_TYPE_PRIMARY
;
339 /* Get rid of the log handle */
345 /* Check if we're too late */
346 if (HvShutdownComplete
)
350 if (LogHandle
) ZwClose(LogHandle
);
351 return STATUS_TOO_LATE
;
354 /* Initialize the hive */
355 Status
= CmpInitializeHive(&NewHive
,
365 if (!NT_SUCCESS(Status
))
369 if (LogHandle
) ZwClose(LogHandle
);
373 /* Success, return hive */
376 /* Duplicate the hive name */
377 NewHive
->FileFullPath
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
380 if (NewHive
->FileFullPath
.Buffer
)
382 /* Copy the string */
383 RtlCopyMemory(NewHive
->FileFullPath
.Buffer
,
386 NewHive
->FileFullPath
.Length
= HiveName
->Length
;
387 NewHive
->FileFullPath
.MaximumLength
= HiveName
->Length
;
391 return STATUS_SUCCESS
;
397 CmpSetSystemValues(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
399 OBJECT_ATTRIBUTES ObjectAttributes
;
400 UNICODE_STRING KeyName
, ValueName
= { 0, 0, NULL
};
401 HANDLE KeyHandle
= NULL
;
403 ASSERT(LoaderBlock
!= NULL
);
405 /* Setup attributes for loader options */
406 RtlInitUnicodeString(&KeyName
,
407 L
"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\"
409 InitializeObjectAttributes(&ObjectAttributes
,
411 OBJ_CASE_INSENSITIVE
,
414 Status
= NtOpenKey(&KeyHandle
, KEY_WRITE
, &ObjectAttributes
);
415 if (!NT_SUCCESS(Status
)) goto Quickie
;
417 /* Key opened, now write to the key */
418 RtlInitUnicodeString(&KeyName
, L
"SystemStartOptions");
419 Status
= NtSetValueKey(KeyHandle
,
423 CmpLoadOptions
.Buffer
,
424 CmpLoadOptions
.Length
);
425 if (!NT_SUCCESS(Status
)) goto Quickie
;
427 /* Setup value name for system boot device in ARC format */
428 RtlInitUnicodeString(&KeyName
, L
"SystemBootDevice");
429 RtlCreateUnicodeStringFromAsciiz(&ValueName
, LoaderBlock
->ArcBootDeviceName
);
430 Status
= NtSetValueKey(KeyHandle
,
438 /* Free the buffers */
439 RtlFreeUnicodeString(&ValueName
);
441 /* Close the key and return */
442 if (KeyHandle
) NtClose(KeyHandle
);
444 /* Return the status */
445 return (ExpInTextModeSetup
? STATUS_SUCCESS
: Status
);
451 CmpCreateHardwareProfile(HANDLE ControlSetHandle
)
453 OBJECT_ATTRIBUTES ObjectAttributes
;
454 UNICODE_STRING KeyName
;
455 HANDLE ProfilesHandle
= NULL
;
456 HANDLE ProfileHandle
= NULL
;
460 DPRINT("CmpCreateHardwareProfile()\n");
462 /* Create the Hardware Profiles key */
463 RtlInitUnicodeString(&KeyName
, L
"Hardware Profiles");
464 InitializeObjectAttributes(&ObjectAttributes
,
466 OBJ_CASE_INSENSITIVE
,
469 Status
= NtCreateKey(&ProfilesHandle
,
476 if (!NT_SUCCESS(Status
))
478 DPRINT1("Creating the Hardware Profile key failed\n");
483 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
485 /* Create the 0000 key */
486 RtlInitUnicodeString(&KeyName
, L
"0000");
487 InitializeObjectAttributes(&ObjectAttributes
,
489 OBJ_CASE_INSENSITIVE
,
492 Status
= NtCreateKey(&ProfileHandle
,
499 if (!NT_SUCCESS(Status
))
501 DPRINT1("Creating the Hardware Profile\\0000 key failed\n");
506 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
510 NtClose(ProfilesHandle
);
513 NtClose(ProfileHandle
);
515 DPRINT("CmpCreateHardwareProfile() done\n");
523 CmpCreateControlSet(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
525 UNICODE_STRING ConfigName
= RTL_CONSTANT_STRING(L
"Control\\IDConfigDB");
526 UNICODE_STRING SelectName
=
527 RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\Select");
528 UNICODE_STRING KeyName
;
529 OBJECT_ATTRIBUTES ObjectAttributes
;
530 CHAR ValueInfoBuffer
[128];
531 PKEY_VALUE_FULL_INFORMATION ValueInfo
;
532 WCHAR UnicodeBuffer
[128];
533 HANDLE SelectHandle
, KeyHandle
, ConfigHandle
= NULL
, ProfileHandle
= NULL
;
534 HANDLE ParentHandle
= NULL
;
535 ULONG ControlSet
, HwProfile
;
537 ULONG ResultLength
, Disposition
;
538 PLOADER_PARAMETER_EXTENSION LoaderExtension
;
541 /* Open the select key */
542 InitializeObjectAttributes(&ObjectAttributes
,
544 OBJ_CASE_INSENSITIVE
,
547 Status
= NtOpenKey(&SelectHandle
, KEY_READ
, &ObjectAttributes
);
548 if (!NT_SUCCESS(Status
))
550 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
551 if (!LoaderBlock
->RegistryBase
)
553 /* Build the ControlSet001 key */
554 RtlInitUnicodeString(&KeyName
,
555 L
"\\Registry\\Machine\\System\\ControlSet001");
556 InitializeObjectAttributes(&ObjectAttributes
,
558 OBJ_CASE_INSENSITIVE
,
561 Status
= NtCreateKey(&KeyHandle
,
568 if (!NT_SUCCESS(Status
)) return Status
;
570 /* Create the Hardware Profile keys */
571 Status
= CmpCreateHardwareProfile(KeyHandle
);
572 if (!NT_SUCCESS(Status
))
575 /* Don't need the handle */
578 /* Use hard-coded setting */
583 /* Fail for real boots */
587 /* Open the current value */
588 RtlInitUnicodeString(&KeyName
, L
"Current");
589 Status
= NtQueryValueKey(SelectHandle
,
591 KeyValueFullInformation
,
593 sizeof(ValueInfoBuffer
),
595 NtClose(SelectHandle
);
596 if (!NT_SUCCESS(Status
)) return Status
;
598 /* Get the actual value pointer, and get the control set ID */
599 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
600 ControlSet
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
602 /* Create the current control set key */
604 RtlInitUnicodeString(&KeyName
,
605 L
"\\Registry\\Machine\\System\\CurrentControlSet");
606 InitializeObjectAttributes(&ObjectAttributes
,
608 OBJ_CASE_INSENSITIVE
,
611 Status
= NtCreateKey(&KeyHandle
,
616 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
618 if (!NT_SUCCESS(Status
)) return Status
;
621 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
623 /* Initialize the target link name */
624 RtlStringCbPrintfW(UnicodeBuffer
, sizeof(UnicodeBuffer
),
625 L
"\\Registry\\Machine\\System\\ControlSet%03ld",
627 RtlInitUnicodeString(&KeyName
, UnicodeBuffer
);
630 Status
= NtSetValueKey(KeyHandle
,
631 &CmSymbolicLinkValueName
,
636 if (!NT_SUCCESS(Status
)) return Status
;
638 /* Get the configuration database key */
639 InitializeObjectAttributes(&ObjectAttributes
,
641 OBJ_CASE_INSENSITIVE
,
644 Status
= NtOpenKey(&ConfigHandle
, KEY_READ
, &ObjectAttributes
);
647 /* Check if we don't have one */
648 if (!NT_SUCCESS(Status
))
650 /* Cleanup and exit */
655 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
656 if (!LoaderBlock
->RegistryBase
)
662 /* Now get the current config */
663 RtlInitUnicodeString(&KeyName
, L
"CurrentConfig");
664 Status
= NtQueryValueKey(ConfigHandle
,
666 KeyValueFullInformation
,
668 sizeof(ValueInfoBuffer
),
671 /* Set pointer to buffer */
672 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
674 /* Check if we failed or got a non DWORD-value */
675 if (!(NT_SUCCESS(Status
)) || (ValueInfo
->Type
!= REG_DWORD
)) goto Cleanup
;
677 /* Get the hadware profile */
678 HwProfile
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
681 /* Open the hardware profile key */
682 RtlInitUnicodeString(&KeyName
,
683 L
"\\Registry\\Machine\\System\\CurrentControlSet"
684 L
"\\Hardware Profiles");
685 InitializeObjectAttributes(&ObjectAttributes
,
687 OBJ_CASE_INSENSITIVE
,
690 Status
= NtOpenKey(&ParentHandle
, KEY_READ
, &ObjectAttributes
);
691 if (!NT_SUCCESS(Status
))
693 /* Exit and clean up */
698 /* Build the profile name */
699 RtlStringCbPrintfW(UnicodeBuffer
, sizeof(UnicodeBuffer
),
700 L
"%04ld", HwProfile
);
701 RtlInitUnicodeString(&KeyName
, UnicodeBuffer
);
703 /* Open the associated key */
704 InitializeObjectAttributes(&ObjectAttributes
,
706 OBJ_CASE_INSENSITIVE
,
709 Status
= NtOpenKey(&ProfileHandle
,
710 KEY_READ
| KEY_WRITE
,
712 if (!NT_SUCCESS (Status
))
714 /* Cleanup and exit */
719 /* Check if we have a loader block extension */
720 LoaderExtension
= LoaderBlock
->Extension
;
723 DPRINT("ReactOS doesn't support NTLDR Profiles yet!\n");
726 /* Create the current hardware profile key */
727 RtlInitUnicodeString(&KeyName
,
728 L
"\\Registry\\Machine\\System\\CurrentControlSet\\"
729 L
"Hardware Profiles\\Current");
730 InitializeObjectAttributes(&ObjectAttributes
,
732 OBJ_CASE_INSENSITIVE
,
735 Status
= NtCreateKey(&KeyHandle
,
740 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
742 if (NT_SUCCESS(Status
))
745 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
747 /* Create the profile name */
748 RtlStringCbPrintfW(UnicodeBuffer
, sizeof(UnicodeBuffer
),
749 L
"\\Registry\\Machine\\System\\CurrentControlSet\\"
750 L
"Hardware Profiles\\%04ld",
752 RtlInitUnicodeString(&KeyName
, UnicodeBuffer
);
755 Status
= NtSetValueKey(KeyHandle
,
756 &CmSymbolicLinkValueName
,
764 /* Close every opened handle */
766 if (ConfigHandle
) NtClose(ConfigHandle
);
767 if (ProfileHandle
) NtClose(ProfileHandle
);
768 if (ParentHandle
) NtClose(ParentHandle
);
770 DPRINT("CmpCreateControlSet() done\n");
773 return STATUS_SUCCESS
;
778 CmpLinkHiveToMaster(IN PUNICODE_STRING LinkName
,
779 IN HANDLE RootDirectory
,
780 IN PCMHIVE RegistryHive
,
782 IN PSECURITY_DESCRIPTOR SecurityDescriptor
)
784 OBJECT_ATTRIBUTES ObjectAttributes
;
786 CM_PARSE_CONTEXT ParseContext
= {0};
788 PCM_KEY_BODY KeyBody
;
791 /* Setup the object attributes */
792 InitializeObjectAttributes(&ObjectAttributes
,
794 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
798 /* Setup the parse context */
799 ParseContext
.CreateLink
= TRUE
;
800 ParseContext
.CreateOperation
= TRUE
;
801 ParseContext
.ChildHive
.KeyHive
= &RegistryHive
->Hive
;
803 /* Check if we have a root keycell or if we need to create it */
807 ParseContext
.ChildHive
.KeyCell
= HCELL_NIL
;
812 ParseContext
.ChildHive
.KeyCell
= RegistryHive
->Hive
.BaseBlock
->RootCell
;
815 /* Create the link node */
816 Status
= ObOpenObjectByName(&ObjectAttributes
,
820 KEY_READ
| KEY_WRITE
,
821 (PVOID
)&ParseContext
,
823 if (!NT_SUCCESS(Status
)) return Status
;
825 /* Mark the hive as clean */
826 RegistryHive
->Hive
.DirtyFlag
= FALSE
;
828 /* ReactOS Hack: Keep alive */
829 Status
= ObReferenceObjectByHandle(KeyHandle
,
835 ASSERT(NT_SUCCESS(Status
));
837 /* Close the extra handle */
839 return STATUS_SUCCESS
;
845 CmpInitializeSystemHive(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
848 ANSI_STRING LoadString
;
853 UNICODE_STRING KeyName
;
854 PCMHIVE SystemHive
= NULL
;
855 UNICODE_STRING HiveName
= RTL_CONSTANT_STRING(L
"SYSTEM");
856 PSECURITY_DESCRIPTOR SecurityDescriptor
;
859 /* Setup the ansi string */
860 RtlInitAnsiString(&LoadString
, LoaderBlock
->LoadOptions
);
862 /* Allocate the unicode buffer */
863 Length
= LoadString
.Length
* sizeof(WCHAR
) + sizeof(UNICODE_NULL
);
864 Buffer
= ExAllocatePoolWithTag(PagedPool
, Length
, TAG_CM
);
868 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 3, 1, (ULONG_PTR
)LoaderBlock
, 0);
871 /* Setup the unicode string */
872 RtlInitEmptyUnicodeString(&CmpLoadOptions
, Buffer
, (USHORT
)Length
);
874 /* Add the load options and null-terminate */
875 RtlAnsiStringToUnicodeString(&CmpLoadOptions
, &LoadString
, FALSE
);
876 CmpLoadOptions
.Buffer
[LoadString
.Length
] = UNICODE_NULL
;
877 CmpLoadOptions
.Length
+= sizeof(WCHAR
);
879 /* Get the System Hive base address */
880 HiveBase
= LoaderBlock
->RegistryBase
;
884 Status
= CmpInitializeHive(&SystemHive
,
894 if (!NT_SUCCESS(Status
)) return FALSE
;
896 /* Set the hive filename */
897 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
898 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
900 /* We imported, no need to create a new hive */
903 /* Manually set the hive as volatile, if in LiveCD mode */
904 if (CmpShareSystemHives
) SystemHive
->Hive
.HiveFlags
= HIVE_VOLATILE
;
909 Status
= CmpInitializeHive(&SystemHive
,
919 if (!NT_SUCCESS(Status
)) return FALSE
;
921 /* Set the hive filename */
922 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
923 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
925 /* Tell CmpLinkHiveToMaster to allocate a hive */
929 /* Save the boot type */
930 CmpBootType
= SystemHive
->Hive
.BaseBlock
->BootType
;
932 /* Are we in self-healing mode? */
935 /* Disable self-healing internally and check if boot type wanted it */
939 /* We're disabled, so bugcheck */
940 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
,
943 (ULONG_PTR
)SystemHive
,
948 /* Create the default security descriptor */
949 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
951 /* Attach it to the system key */
952 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\SYSTEM");
953 Status
= CmpLinkHiveToMaster(&KeyName
,
959 /* Free the security descriptor */
960 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
961 if (!NT_SUCCESS(Status
)) return FALSE
;
963 /* Add the hive to the hive list */
964 CmpMachineHiveList
[3].CmHive
= SystemHive
;
973 CmpCreateObjectTypes(VOID
)
975 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer
;
977 GENERIC_MAPPING CmpKeyMapping
= {KEY_READ
,
983 /* Initialize the Key object type */
984 RtlZeroMemory(&ObjectTypeInitializer
, sizeof(ObjectTypeInitializer
));
985 RtlInitUnicodeString(&Name
, L
"Key");
986 ObjectTypeInitializer
.Length
= sizeof(ObjectTypeInitializer
);
987 ObjectTypeInitializer
.DefaultPagedPoolCharge
= sizeof(CM_KEY_BODY
);
988 ObjectTypeInitializer
.GenericMapping
= CmpKeyMapping
;
989 ObjectTypeInitializer
.PoolType
= PagedPool
;
990 ObjectTypeInitializer
.ValidAccessMask
= KEY_ALL_ACCESS
;
991 ObjectTypeInitializer
.UseDefaultObject
= TRUE
;
992 ObjectTypeInitializer
.DeleteProcedure
= CmpDeleteKeyObject
;
993 ObjectTypeInitializer
.ParseProcedure
= CmpParseKey
;
994 ObjectTypeInitializer
.SecurityProcedure
= CmpSecurityMethod
;
995 ObjectTypeInitializer
.QueryNameProcedure
= CmpQueryKeyName
;
996 ObjectTypeInitializer
.CloseProcedure
= CmpCloseKeyObject
;
997 ObjectTypeInitializer
.SecurityRequired
= TRUE
;
998 ObjectTypeInitializer
.InvalidAttributes
= OBJ_EXCLUSIVE
| OBJ_PERMANENT
;
1001 return ObCreateObjectType(&Name
, &ObjectTypeInitializer
, NULL
, &CmpKeyObjectType
);
1007 CmpCreateRootNode(IN PHHIVE Hive
,
1009 OUT PHCELL_INDEX Index
)
1011 UNICODE_STRING KeyName
;
1012 PCM_KEY_NODE KeyCell
;
1015 /* Initialize the node name and allocate it */
1016 RtlInitUnicodeString(&KeyName
, Name
);
1017 *Index
= HvAllocateCell(Hive
,
1018 FIELD_OFFSET(CM_KEY_NODE
, Name
) +
1019 CmpNameSize(Hive
, &KeyName
),
1022 if (*Index
== HCELL_NIL
) return FALSE
;
1024 /* Set the cell index and get the data */
1025 Hive
->BaseBlock
->RootCell
= *Index
;
1026 KeyCell
= (PCM_KEY_NODE
)HvGetCell(Hive
, *Index
);
1027 if (!KeyCell
) return FALSE
;
1029 /* Setup the cell */
1030 KeyCell
->Signature
= CM_KEY_NODE_SIGNATURE
;
1031 KeyCell
->Flags
= KEY_HIVE_ENTRY
| KEY_NO_DELETE
;
1032 KeQuerySystemTime(&KeyCell
->LastWriteTime
);
1033 KeyCell
->Parent
= HCELL_NIL
;
1034 KeyCell
->SubKeyCounts
[Stable
] = 0;
1035 KeyCell
->SubKeyCounts
[Volatile
] = 0;
1036 KeyCell
->SubKeyLists
[Stable
] = HCELL_NIL
;
1037 KeyCell
->SubKeyLists
[Volatile
] = HCELL_NIL
;
1038 KeyCell
->ValueList
.Count
= 0;
1039 KeyCell
->ValueList
.List
= HCELL_NIL
;
1040 KeyCell
->Security
= HCELL_NIL
;
1041 KeyCell
->Class
= HCELL_NIL
;
1042 KeyCell
->ClassLength
= 0;
1043 KeyCell
->MaxNameLen
= 0;
1044 KeyCell
->MaxClassLen
= 0;
1045 KeyCell
->MaxValueNameLen
= 0;
1046 KeyCell
->MaxValueDataLen
= 0;
1048 /* Copy the name (this will also set the length) */
1049 KeyCell
->NameLength
= CmpCopyName(Hive
, KeyCell
->Name
, &KeyName
);
1051 /* Check if the name was compressed and set the flag if so */
1052 if (KeyCell
->NameLength
< KeyName
.Length
)
1053 KeyCell
->Flags
|= KEY_COMP_NAME
;
1055 /* Return success */
1056 HvReleaseCell(Hive
, *Index
);
1063 CmpCreateRegistryRoot(VOID
)
1065 UNICODE_STRING KeyName
;
1066 OBJECT_ATTRIBUTES ObjectAttributes
;
1067 PCM_KEY_BODY RootKey
;
1068 HCELL_INDEX RootIndex
;
1070 PCM_KEY_NODE KeyCell
;
1071 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1072 PCM_KEY_CONTROL_BLOCK Kcb
;
1075 /* Setup the root node */
1076 if (!CmpCreateRootNode(&CmiVolatileHive
->Hive
, L
"REGISTRY", &RootIndex
))
1082 /* Create '\Registry' key. */
1083 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1084 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1085 InitializeObjectAttributes(&ObjectAttributes
,
1087 OBJ_CASE_INSENSITIVE
,
1089 SecurityDescriptor
);
1090 Status
= ObCreateObject(KernelMode
,
1095 sizeof(CM_KEY_BODY
),
1099 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
1100 if (!NT_SUCCESS(Status
)) return FALSE
;
1102 /* Sanity check, and get the key cell */
1103 ASSERT((&CmiVolatileHive
->Hive
)->ReleaseCellRoutine
== NULL
);
1104 KeyCell
= (PCM_KEY_NODE
)HvGetCell(&CmiVolatileHive
->Hive
, RootIndex
);
1105 if (!KeyCell
) return FALSE
;
1107 /* Create the KCB */
1108 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1109 Kcb
= CmpCreateKeyControlBlock(&CmiVolatileHive
->Hive
,
1117 ObDereferenceObject(RootKey
);
1121 /* Initialize the object */
1122 RootKey
->KeyControlBlock
= Kcb
;
1123 RootKey
->Type
= CM_KEY_BODY_TYPE
;
1124 RootKey
->NotifyBlock
= NULL
;
1125 RootKey
->ProcessID
= PsGetCurrentProcessId();
1128 EnlistKeyBodyWithKCB(RootKey
, 0);
1130 /* Insert the key into the namespace */
1131 Status
= ObInsertObject(RootKey
,
1136 &CmpRegistryRootHandle
);
1137 if (!NT_SUCCESS(Status
))
1139 ObDereferenceObject(RootKey
);
1143 /* Reference the key again so that we never lose it */
1144 Status
= ObReferenceObjectByHandle(CmpRegistryRootHandle
,
1150 if (!NT_SUCCESS(Status
))
1152 ObDereferenceObject(RootKey
);
1156 /* Completely sucessful */
1162 CmpGetRegistryPath(OUT PWCHAR ConfigPath
)
1164 OBJECT_ATTRIBUTES ObjectAttributes
;
1167 PKEY_VALUE_PARTIAL_INFORMATION ValueInfo
;
1168 UNICODE_STRING KeyName
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\HARDWARE");
1169 UNICODE_STRING ValueName
= RTL_CONSTANT_STRING(L
"InstallPath");
1170 ULONG BufferSize
, ResultSize
;
1172 /* Check if we are booted in setup */
1173 if (ExpInTextModeSetup
)
1175 DPRINT1("CmpGetRegistryPath TextMode setup HACK!!\n");
1177 /* Setup the object attributes */
1178 InitializeObjectAttributes(&ObjectAttributes
,
1180 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1184 Status
= ZwOpenKey(&KeyHandle
,
1187 if (!NT_SUCCESS(Status
)) return Status
;
1189 /* Allocate the buffer */
1190 BufferSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 4096;
1191 ValueInfo
= ExAllocatePoolWithTag(PagedPool
, BufferSize
, TAG_CM
);
1196 return STATUS_INSUFFICIENT_RESOURCES
;
1199 /* Query the value */
1200 Status
= ZwQueryValueKey(KeyHandle
,
1202 KeyValuePartialInformation
,
1207 if (!NT_SUCCESS(Status
))
1210 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1214 /* Copy the config path and null-terminate it */
1215 RtlCopyMemory(ConfigPath
,
1217 ValueInfo
->DataLength
);
1218 ConfigPath
[ValueInfo
->DataLength
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1219 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1223 /* Just use default path */
1224 wcscpy(ConfigPath
, L
"\\SystemRoot");
1227 /* Add registry path */
1228 wcscat(ConfigPath
, L
"\\System32\\Config\\");
1230 DPRINT1("CmpGetRegistryPath: ConfigPath = '%S'\n", ConfigPath
);
1233 return STATUS_SUCCESS
;
1238 CmpLoadHiveThread(IN PVOID StartContext
)
1240 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1241 UNICODE_STRING TempName
, FileName
, RegName
;
1242 ULONG i
, ErrorResponse
, WorkerCount
, Length
;
1244 ULONG PrimaryDisposition
, SecondaryDisposition
, ClusterSize
;
1246 HANDLE PrimaryHandle
= NULL
, LogHandle
= NULL
;
1247 NTSTATUS Status
= STATUS_SUCCESS
;
1248 PVOID ErrorParameters
;
1251 /* Get the hive index, make sure it makes sense */
1252 i
= PtrToUlong(StartContext
);
1253 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1255 /* We were started */
1256 CmpMachineHiveList
[i
].ThreadStarted
= TRUE
;
1258 /* Build the file name and registry name strings */
1259 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, sizeof(FileBuffer
));
1260 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, sizeof(RegBuffer
));
1262 /* Now build the system root path */
1263 CmpGetRegistryPath(ConfigPath
);
1264 RtlInitUnicodeString(&TempName
, ConfigPath
);
1265 RtlAppendUnicodeStringToString(&FileName
, &TempName
);
1266 FileStart
= FileName
.Length
;
1268 /* And build the registry root path */
1269 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1270 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1272 /* Build the base name */
1273 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1274 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1276 /* Check if this is a child of the root */
1277 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == OBJ_NAME_PATH_SEPARATOR
)
1279 /* Then setup the whole name */
1280 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1281 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1284 /* Now add the rest of the file name */
1285 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1286 FileName
.Length
= FileStart
;
1287 RtlAppendUnicodeStringToString(&FileName
, &TempName
);
1288 if (!CmpMachineHiveList
[i
].CmHive
)
1290 /* We need to allocate a new hive structure */
1291 CmpMachineHiveList
[i
].Allocate
= TRUE
;
1293 /* Load the hive file */
1294 Status
= CmpInitHiveFromFile(&FileName
,
1295 CmpMachineHiveList
[i
].HHiveFlags
,
1297 &CmpMachineHiveList
[i
].Allocate
,
1299 if (!(NT_SUCCESS(Status
)) ||
1300 (!(CmHive
->FileHandles
[HFILE_TYPE_LOG
]) && !(CmpMiniNTBoot
))) // HACK
1302 /* We failed or couldn't get a log file, raise a hard error */
1303 ErrorParameters
= &FileName
;
1304 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1307 (PULONG_PTR
)&ErrorParameters
,
1312 /* Set the hive flags and newly allocated hive pointer */
1313 CmHive
->Flags
= CmpMachineHiveList
[i
].CmHiveFlags
;
1314 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1318 /* We already have a hive, is it volatile? */
1319 CmHive
= CmpMachineHiveList
[i
].CmHive
;
1320 if (!(CmHive
->Hive
.HiveFlags
& HIVE_VOLATILE
))
1322 /* It's now, open the hive file and log */
1323 Status
= CmpOpenHiveFiles(&FileName
,
1327 &PrimaryDisposition
,
1328 &SecondaryDisposition
,
1333 if (!(NT_SUCCESS(Status
)) || !(LogHandle
))
1335 /* Couldn't open the hive or its log file, raise a hard error */
1336 ErrorParameters
= &FileName
;
1337 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1340 (PULONG_PTR
)&ErrorParameters
,
1344 /* And bugcheck for posterity's sake */
1345 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 0, i
, Status
);
1348 /* Save the file handles. This should remove our sync hacks */
1349 CmHive
->FileHandles
[HFILE_TYPE_LOG
] = LogHandle
;
1350 CmHive
->FileHandles
[HFILE_TYPE_PRIMARY
] = PrimaryHandle
;
1352 /* Allow lazy flushing since the handles are there -- remove sync hacks */
1353 //ASSERT(CmHive->Hive.HiveFlags & HIVE_NOLAZYFLUSH);
1354 CmHive
->Hive
.HiveFlags
&= ~HIVE_NOLAZYFLUSH
;
1356 /* Get the real size of the hive */
1357 Length
= CmHive
->Hive
.Storage
[Stable
].Length
+ HBLOCK_SIZE
;
1359 /* Check if the cluster size doesn't match */
1360 if (CmHive
->Hive
.Cluster
!= ClusterSize
) ASSERT(FALSE
);
1362 /* Set the file size */
1363 DPRINT("FIXME: Should set file size: %lx\n", Length
);
1364 //if (!CmpFileSetSize((PHHIVE)CmHive, HFILE_TYPE_PRIMARY, Length, Length))
1366 /* This shouldn't fail */
1370 /* Another thing we don't support is NTLDR-recovery */
1371 if (CmHive
->Hive
.BaseBlock
->BootRecover
) ASSERT(FALSE
);
1373 /* Finally, set our allocated hive to the same hive we've had */
1374 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1375 ASSERT(CmpMachineHiveList
[i
].CmHive
== CmpMachineHiveList
[i
].CmHive2
);
1380 CmpMachineHiveList
[i
].ThreadFinished
= TRUE
;
1382 /* Check if we're the last worker */
1383 WorkerCount
= InterlockedIncrement(&CmpLoadWorkerIncrement
);
1384 if (WorkerCount
== CM_NUMBER_OF_MACHINE_HIVES
)
1386 /* Signal the event */
1387 KeSetEvent(&CmpLoadWorkerEvent
, 0, FALSE
);
1390 /* Kill the thread */
1391 PsTerminateSystemThread(Status
);
1396 CmpInitializeHiveList(IN USHORT Flag
)
1398 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1399 UNICODE_STRING TempName
, FileName
, RegName
;
1404 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1407 /* Allow writing for now */
1410 /* Build the file name and registry name strings */
1411 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, sizeof(FileBuffer
));
1412 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, sizeof(RegBuffer
));
1414 /* Now build the system root path */
1415 CmpGetRegistryPath(ConfigPath
);
1416 RtlInitUnicodeString(&TempName
, ConfigPath
);
1417 RtlAppendUnicodeStringToString(&FileName
, &TempName
);
1419 /* And build the registry root path */
1420 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1421 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1422 RegStart
= RegName
.Length
;
1424 /* Setup the event to synchronize workers */
1425 KeInitializeEvent(&CmpLoadWorkerEvent
, SynchronizationEvent
, FALSE
);
1427 /* Enter special boot condition */
1428 CmpSpecialBootCondition
= TRUE
;
1430 /* Create the SD for the root hives */
1431 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1433 /* Loop every hive we care about */
1434 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1436 /* Make sure the list is set up */
1437 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1439 /* Load the hive as volatile, if in LiveCD mode */
1440 if (CmpShareSystemHives
)
1441 CmpMachineHiveList
[i
].HHiveFlags
|= HIVE_VOLATILE
;
1443 /* Create a thread to handle this hive */
1444 Status
= PsCreateSystemThread(&Thread
,
1451 if (NT_SUCCESS(Status
))
1453 /* We don't care about the handle -- the thread self-terminates */
1458 /* Can't imagine this happening */
1459 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 3, i
, Status
);
1463 /* Make sure we've reached the end of the list */
1464 ASSERT(CmpMachineHiveList
[i
].Name
== NULL
);
1466 /* Wait for hive loading to finish */
1467 KeWaitForSingleObject(&CmpLoadWorkerEvent
,
1473 /* Exit the special boot condition and make sure all workers completed */
1474 CmpSpecialBootCondition
= FALSE
;
1475 ASSERT(CmpLoadWorkerIncrement
== CM_NUMBER_OF_MACHINE_HIVES
);
1477 /* Loop hives again */
1478 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1480 /* Make sure the thread ran and finished */
1481 ASSERT(CmpMachineHiveList
[i
].ThreadFinished
== TRUE
);
1482 ASSERT(CmpMachineHiveList
[i
].ThreadStarted
== TRUE
);
1484 /* Check if this was a new hive */
1485 if (!CmpMachineHiveList
[i
].CmHive
)
1487 /* Make sure we allocated something */
1488 ASSERT(CmpMachineHiveList
[i
].CmHive2
!= NULL
);
1490 /* Build the base name */
1491 RegName
.Length
= RegStart
;
1492 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1493 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1495 /* Check if this is a child of the root */
1496 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == OBJ_NAME_PATH_SEPARATOR
)
1498 /* Then setup the whole name */
1499 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1500 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1503 /* Now link the hive to its master */
1504 Status
= CmpLinkHiveToMaster(&RegName
,
1506 CmpMachineHiveList
[i
].CmHive2
,
1507 CmpMachineHiveList
[i
].Allocate
,
1508 SecurityDescriptor
);
1509 if (Status
!= STATUS_SUCCESS
)
1511 /* Linking needs to work */
1512 KeBugCheckEx(CONFIG_LIST_FAILED
, 11, Status
, i
, (ULONG_PTR
)&RegName
);
1515 /* Check if we had to allocate a new hive */
1516 if (CmpMachineHiveList
[i
].Allocate
)
1518 /* Sync the new hive */
1519 //HvSyncHive((PHHIVE)(CmpMachineHiveList[i].CmHive2));
1523 /* Check if we created a new hive */
1524 if (CmpMachineHiveList
[i
].CmHive2
)
1526 /* Add to HiveList key */
1527 CmpAddToHiveFileList(CmpMachineHiveList
[i
].CmHive2
);
1531 /* Get rid of the SD */
1532 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
1534 /* Link SECURITY to SAM */
1535 CmpLinkKeyToHive(L
"\\Registry\\Machine\\Security\\SAM",
1536 L
"\\Registry\\Machine\\SAM\\SAM");
1538 /* Link S-1-5-18 to .Default */
1539 CmpNoVolatileCreates
= FALSE
;
1540 CmpLinkKeyToHive(L
"\\Registry\\User\\S-1-5-18",
1541 L
"\\Registry\\User\\.Default");
1542 CmpNoVolatileCreates
= TRUE
;
1550 OBJECT_ATTRIBUTES ObjectAttributes
;
1551 UNICODE_STRING KeyName
;
1554 PCMHIVE HardwareHive
;
1555 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1558 /* Check if this is PE-boot */
1559 if (InitIsWinPEMode
)
1561 /* Set registry to PE mode */
1562 CmpMiniNTBoot
= TRUE
;
1563 CmpShareSystemHives
= TRUE
;
1566 /* Initialize the hive list and lock */
1567 InitializeListHead(&CmpHiveListHead
);
1568 ExInitializePushLock(&CmpHiveListHeadLock
);
1569 ExInitializePushLock(&CmpLoadHiveLock
);
1571 /* Initialize registry lock */
1572 ExInitializeResourceLite(&CmpRegistryLock
);
1574 /* Initialize the cache */
1575 CmpInitializeCache();
1577 /* Initialize allocation and delayed dereferencing */
1578 CmpInitCmPrivateAlloc();
1579 CmpInitCmPrivateDelayAlloc();
1580 CmpInitDelayDerefKCBEngine();
1582 /* Initialize callbacks */
1585 /* Initialize self healing */
1586 KeInitializeGuardedMutex(&CmpSelfHealQueueLock
);
1587 InitializeListHead(&CmpSelfHealQueueListHead
);
1589 /* Save the current process and lock the registry */
1590 CmpSystemProcess
= PsGetCurrentProcess();
1592 /* Create the key object types */
1593 Status
= CmpCreateObjectTypes();
1594 if (!NT_SUCCESS(Status
))
1597 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 1, Status
, 0);
1600 /* Build the master hive */
1601 Status
= CmpInitializeHive(&CmiVolatileHive
,
1611 if (!NT_SUCCESS(Status
))
1614 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 2, Status
, 0);
1617 /* Create the \REGISTRY key node */
1618 if (!CmpCreateRegistryRoot())
1621 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 3, 0, 0);
1624 /* Create the default security descriptor */
1625 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1627 /* Create '\Registry\Machine' key */
1628 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE");
1629 InitializeObjectAttributes(&ObjectAttributes
,
1631 OBJ_CASE_INSENSITIVE
,
1633 SecurityDescriptor
);
1634 Status
= NtCreateKey(&KeyHandle
,
1635 KEY_READ
| KEY_WRITE
,
1641 if (!NT_SUCCESS(Status
))
1644 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 5, Status
, 0);
1647 /* Close the handle */
1650 /* Create '\Registry\User' key */
1651 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\USER");
1652 InitializeObjectAttributes(&ObjectAttributes
,
1654 OBJ_CASE_INSENSITIVE
,
1656 SecurityDescriptor
);
1657 Status
= NtCreateKey(&KeyHandle
,
1658 KEY_READ
| KEY_WRITE
,
1664 if (!NT_SUCCESS(Status
))
1667 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 6, Status
, 0);
1670 /* Close the handle */
1673 /* After this point, do not allow creating keys in the master hive */
1674 CmpNoVolatileCreates
= TRUE
;
1676 /* Initialize the system hive */
1677 if (!CmpInitializeSystemHive(KeLoaderBlock
))
1680 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 7, 0, 0);
1683 /* Create the 'CurrentControlSet' link */
1684 Status
= CmpCreateControlSet(KeLoaderBlock
);
1685 if (!NT_SUCCESS(Status
))
1688 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 8, Status
, 0);
1691 /* Create the hardware hive */
1692 Status
= CmpInitializeHive(&HardwareHive
,
1702 if (!NT_SUCCESS(Status
))
1705 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 11, Status
, 0);
1708 /* Add the hive to the hive list */
1709 CmpMachineHiveList
[0].CmHive
= HardwareHive
;
1711 /* Attach it to the machine key */
1712 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\HARDWARE");
1713 Status
= CmpLinkHiveToMaster(&KeyName
,
1717 SecurityDescriptor
);
1718 if (!NT_SUCCESS(Status
))
1721 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 12, Status
, 0);
1724 /* Add to HiveList key */
1725 CmpAddToHiveFileList(HardwareHive
);
1727 /* Free the security descriptor */
1728 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
1730 /* Fill out the Hardware key with the ARC Data from the Loader */
1731 Status
= CmpInitializeHardwareConfiguration(KeLoaderBlock
);
1732 if (!NT_SUCCESS(Status
))
1735 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 13, Status
, 0);
1738 /* Initialize machine-dependent information into the registry */
1739 Status
= CmpInitializeMachineDependentConfiguration(KeLoaderBlock
);
1740 if (!NT_SUCCESS(Status
))
1743 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 14, Status
, 0);
1746 /* Initialize volatile registry settings */
1747 Status
= CmpSetSystemValues(KeLoaderBlock
);
1748 if (!NT_SUCCESS(Status
))
1751 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 15, Status
, 0);
1754 /* Free the load options */
1755 ExFreePoolWithTag(CmpLoadOptions
.Buffer
, TAG_CM
);
1757 /* If we got here, all went well */
1764 CmpFreeDriverList(IN PHHIVE Hive
,
1765 IN PLIST_ENTRY DriverList
)
1767 PLIST_ENTRY NextEntry
, OldEntry
;
1768 PBOOT_DRIVER_NODE DriverNode
;
1771 /* Parse the current list */
1772 NextEntry
= DriverList
->Flink
;
1773 while (NextEntry
!= DriverList
)
1775 /* Get the driver node */
1776 DriverNode
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_NODE
, ListEntry
.Link
);
1778 /* Get the next entry now, since we're going to free it later */
1779 OldEntry
= NextEntry
;
1780 NextEntry
= NextEntry
->Flink
;
1782 /* Was there a name? */
1783 if (DriverNode
->Name
.Buffer
)
1786 CmpFree(DriverNode
->Name
.Buffer
, DriverNode
->Name
.Length
);
1789 /* Was there a registry path? */
1790 if (DriverNode
->ListEntry
.RegistryPath
.Buffer
)
1793 CmpFree(DriverNode
->ListEntry
.RegistryPath
.Buffer
,
1794 DriverNode
->ListEntry
.RegistryPath
.MaximumLength
);
1797 /* Was there a file path? */
1798 if (DriverNode
->ListEntry
.FilePath
.Buffer
)
1801 CmpFree(DriverNode
->ListEntry
.FilePath
.Buffer
,
1802 DriverNode
->ListEntry
.FilePath
.MaximumLength
);
1805 /* Now free the node, and move on */
1806 CmpFree(OldEntry
, sizeof(BOOT_DRIVER_NODE
));
1813 CmGetSystemDriverList(VOID
)
1815 LIST_ENTRY DriverList
;
1816 OBJECT_ATTRIBUTES ObjectAttributes
;
1818 PCM_KEY_BODY KeyBody
;
1820 HCELL_INDEX RootCell
, ControlCell
;
1822 UNICODE_STRING KeyName
;
1823 PLIST_ENTRY NextEntry
;
1825 PUNICODE_STRING
* ServicePath
= NULL
;
1826 BOOLEAN Success
, AutoSelect
;
1827 PBOOT_DRIVER_LIST_ENTRY DriverEntry
;
1830 /* Initialize the driver list */
1831 InitializeListHead(&DriverList
);
1833 /* Open the system hive key */
1834 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\System");
1835 InitializeObjectAttributes(&ObjectAttributes
,
1837 OBJ_CASE_INSENSITIVE
,
1840 Status
= NtOpenKey(&KeyHandle
, KEY_READ
, &ObjectAttributes
);
1841 if (!NT_SUCCESS(Status
)) return NULL
;
1843 /* Reference the key object to get the root hive/cell to access directly */
1844 Status
= ObReferenceObjectByHandle(KeyHandle
,
1850 if (!NT_SUCCESS(Status
))
1857 /* Do all this under the registry lock */
1858 CmpLockRegistryExclusive();
1860 /* Get the hive and key cell */
1861 Hive
= KeyBody
->KeyControlBlock
->KeyHive
;
1862 RootCell
= KeyBody
->KeyControlBlock
->KeyCell
;
1864 /* Open the current control set key */
1865 RtlInitUnicodeString(&KeyName
, L
"Current");
1866 ControlCell
= CmpFindControlSet(Hive
, RootCell
, &KeyName
, &AutoSelect
);
1867 if (ControlCell
== HCELL_NIL
) goto EndPath
;
1869 /* Find all system drivers */
1870 Success
= CmpFindDrivers(Hive
, ControlCell
, SystemLoad
, NULL
, &DriverList
);
1871 if (!Success
) goto EndPath
;
1873 /* Sort by group/tag */
1874 if (!CmpSortDriverList(Hive
, ControlCell
, &DriverList
)) goto EndPath
;
1876 /* Remove circular dependencies (cycles) and sort */
1877 if (!CmpResolveDriverDependencies(&DriverList
)) goto EndPath
;
1879 /* Loop the list to count drivers */
1880 for (i
= 0, NextEntry
= DriverList
.Flink
;
1881 NextEntry
!= &DriverList
;
1882 i
++, NextEntry
= NextEntry
->Flink
);
1884 /* Allocate the array */
1885 ServicePath
= ExAllocatePool(NonPagedPool
, (i
+ 1) * sizeof(PUNICODE_STRING
));
1886 if (!ServicePath
) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 2, 1, 0, 0);
1888 /* Loop the driver list */
1889 for (i
= 0, NextEntry
= DriverList
.Flink
;
1890 NextEntry
!= &DriverList
;
1891 i
++, NextEntry
= NextEntry
->Flink
)
1894 DriverEntry
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_LIST_ENTRY
, Link
);
1896 /* Allocate the path for the caller and duplicate the registry path */
1897 ServicePath
[i
] = ExAllocatePool(NonPagedPool
, sizeof(UNICODE_STRING
));
1898 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1899 &DriverEntry
->RegistryPath
,
1903 /* Terminate the list */
1904 ServicePath
[i
] = NULL
;
1907 /* Free the driver list if we had one */
1908 if (!IsListEmpty(&DriverList
)) CmpFreeDriverList(Hive
, &DriverList
);
1910 /* Unlock the registry */
1911 CmpUnlockRegistry();
1913 /* Close the key handle and dereference the object, then return the path */
1914 ObDereferenceObject(KeyBody
);
1921 CmpLockRegistryExclusive(VOID
)
1923 /* Enter a critical region and lock the registry */
1924 KeEnterCriticalRegion();
1925 ExAcquireResourceExclusiveLite(&CmpRegistryLock
, TRUE
);
1928 ASSERT(CmpFlushStarveWriters
== 0);
1929 RtlGetCallersAddress(&CmpRegistryLockCaller
, &CmpRegistryLockCallerCaller
);
1934 CmpLockRegistry(VOID
)
1936 /* Enter a critical region */
1937 KeEnterCriticalRegion();
1939 /* Check if we have to starve writers */
1940 if (CmpFlushStarveWriters
)
1942 /* Starve exlusive waiters */
1943 ExAcquireSharedStarveExclusive(&CmpRegistryLock
, TRUE
);
1947 /* Just grab the lock */
1948 ExAcquireResourceSharedLite(&CmpRegistryLock
, TRUE
);
1954 CmpTestRegistryLock(VOID
)
1957 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1962 CmpTestRegistryLockExclusive(VOID
)
1965 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1970 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive
)
1972 /* Lock the flusher. We should already be in a critical section */
1973 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1974 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1975 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1976 ExAcquireResourceExclusiveLite(Hive
->FlusherLock
, TRUE
);
1981 CmpLockHiveFlusherShared(IN PCMHIVE Hive
)
1983 /* Lock the flusher. We should already be in a critical section */
1984 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1985 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1986 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1987 ExAcquireResourceSharedLite(Hive
->FlusherLock
, TRUE
);
1992 CmpUnlockHiveFlusher(IN PCMHIVE Hive
)
1995 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1996 CMP_ASSERT_FLUSH_LOCK(Hive
);
1998 /* Release the lock */
1999 ExReleaseResourceLite(Hive
->FlusherLock
);
2004 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive
)
2007 return !ExIsResourceAcquiredSharedLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
2012 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive
)
2015 return !ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
2020 CmpUnlockRegistry(VOID
)
2023 CMP_ASSERT_REGISTRY_LOCK();
2025 /* Check if we should flush the registry */
2026 if (CmpFlushOnLockRelease
)
2028 /* The registry should be exclusively locked for this */
2029 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
2031 /* Flush the registry */
2032 CmpDoFlushAll(TRUE
);
2033 CmpFlushOnLockRelease
= FALSE
;
2037 /* Lazy flush the registry */
2041 /* Release the lock and leave the critical region */
2042 ExReleaseResourceLite(&CmpRegistryLock
);
2043 KeLeaveCriticalRegion();
2048 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1
,
2051 ULONG Index1
, Index2
;
2054 CMP_ASSERT_REGISTRY_LOCK();
2056 /* Get hash indexes */
2057 Index1
= GET_HASH_INDEX(ConvKey1
);
2058 Index2
= GET_HASH_INDEX(ConvKey2
);
2060 /* See which one is highest */
2061 if (Index1
< Index2
)
2063 /* Grab them in the proper order */
2064 CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2065 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2069 /* Grab the second one first, then the first */
2070 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2071 if (Index1
!= Index2
) CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2077 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1
,
2080 ULONG Index1
, Index2
;
2083 CMP_ASSERT_REGISTRY_LOCK();
2085 /* Get hash indexes */
2086 Index1
= GET_HASH_INDEX(ConvKey1
);
2087 Index2
= GET_HASH_INDEX(ConvKey2
);
2088 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey2
)->Owner
== KeGetCurrentThread()) ||
2089 (CmpTestRegistryLockExclusive()));
2091 /* See which one is highest */
2092 if (Index1
< Index2
)
2094 /* Grab them in the proper order */
2095 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
)->Owner
== KeGetCurrentThread()) ||
2096 (CmpTestRegistryLockExclusive()));
2097 CmpReleaseKcbLockByKey(ConvKey2
);
2098 CmpReleaseKcbLockByKey(ConvKey1
);
2102 /* Release the first one first, then the second */
2103 if (Index1
!= Index2
)
2105 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
)->Owner
== KeGetCurrentThread()) ||
2106 (CmpTestRegistryLockExclusive()));
2107 CmpReleaseKcbLockByKey(ConvKey1
);
2109 CmpReleaseKcbLockByKey(ConvKey2
);
2115 CmShutdownSystem(VOID
)
2117 PLIST_ENTRY ListEntry
;
2120 /* Kill the workers */
2121 if (!CmFirstTime
) CmpShutdownWorkers();
2123 /* Flush all hives */
2124 CmpLockRegistryExclusive();
2125 CmpDoFlushAll(TRUE
);
2127 /* Close all hive files */
2128 ListEntry
= CmpHiveListHead
.Flink
;
2129 while (ListEntry
!= &CmpHiveListHead
)
2131 Hive
= CONTAINING_RECORD(ListEntry
, CMHIVE
, HiveList
);
2133 CmpCloseHiveFiles(Hive
);
2135 ListEntry
= ListEntry
->Flink
;
2138 CmpUnlockRegistry();
2143 CmpSetVersionData(VOID
)
2146 OBJECT_ATTRIBUTES ObjectAttributes
;
2147 UNICODE_STRING KeyName
;
2148 UNICODE_STRING ValueName
;
2149 UNICODE_STRING ValueData
;
2150 ANSI_STRING TempString
;
2151 HANDLE SoftwareKeyHandle
= NULL
;
2152 HANDLE MicrosoftKeyHandle
= NULL
;
2153 HANDLE WindowsNtKeyHandle
= NULL
;
2154 HANDLE CurrentVersionKeyHandle
= NULL
;
2155 WCHAR Buffer
[128]; // Buffer large enough to contain a full ULONG in decimal
2156 // representation, and the full 'CurrentType' string.
2159 * Open the 'HKLM\Software\Microsoft\Windows NT\CurrentVersion' key
2160 * (create the intermediate subkeys if needed).
2163 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE\\SOFTWARE");
2164 InitializeObjectAttributes(&ObjectAttributes
,
2166 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2169 Status
= NtCreateKey(&SoftwareKeyHandle
,
2176 if (!NT_SUCCESS(Status
))
2178 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2182 RtlInitUnicodeString(&KeyName
, L
"Microsoft");
2183 InitializeObjectAttributes(&ObjectAttributes
,
2185 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2188 Status
= NtCreateKey(&MicrosoftKeyHandle
,
2195 if (!NT_SUCCESS(Status
))
2197 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2201 RtlInitUnicodeString(&KeyName
, L
"Windows NT");
2202 InitializeObjectAttributes(&ObjectAttributes
,
2204 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2207 Status
= NtCreateKey(&WindowsNtKeyHandle
,
2214 if (!NT_SUCCESS(Status
))
2216 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2220 RtlInitUnicodeString(&KeyName
, L
"CurrentVersion");
2221 InitializeObjectAttributes(&ObjectAttributes
,
2223 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2226 Status
= NtCreateKey(&CurrentVersionKeyHandle
,
2227 KEY_CREATE_SUB_KEY
| KEY_SET_VALUE
,
2233 if (!NT_SUCCESS(Status
))
2235 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2239 /* Set the 'CurrentVersion' value */
2240 RtlInitUnicodeString(&ValueName
, L
"CurrentVersion");
2241 NtSetValueKey(CurrentVersionKeyHandle
,
2245 CmVersionString
.Buffer
,
2246 CmVersionString
.Length
+ sizeof(WCHAR
));
2248 /* Set the 'CurrentBuildNumber' value */
2249 RtlInitUnicodeString(&ValueName
, L
"CurrentBuildNumber");
2250 RtlInitEmptyUnicodeString(&ValueData
, Buffer
, sizeof(Buffer
));
2251 RtlIntegerToUnicodeString(NtBuildNumber
& 0xFFFF, 10, &ValueData
);
2252 NtSetValueKey(CurrentVersionKeyHandle
,
2257 ValueData
.Length
+ sizeof(WCHAR
));
2259 /* Set the 'BuildLab' value */
2260 RtlInitUnicodeString(&ValueName
, L
"BuildLab");
2261 RtlInitAnsiString(&TempString
, NtBuildLab
);
2262 Status
= RtlAnsiStringToUnicodeString(&ValueData
, &TempString
, FALSE
);
2263 if (NT_SUCCESS(Status
))
2265 NtSetValueKey(CurrentVersionKeyHandle
,
2270 ValueData
.Length
+ sizeof(WCHAR
));
2273 /* Set the 'CurrentType' value */
2274 RtlInitUnicodeString(&ValueName
, L
"CurrentType");
2275 RtlStringCbPrintfW(Buffer
, sizeof(Buffer
),
2289 RtlInitUnicodeString(&ValueData
, Buffer
);
2290 NtSetValueKey(CurrentVersionKeyHandle
,
2295 ValueData
.Length
+ sizeof(WCHAR
));
2297 /* Set the 'CSDVersion' value */
2298 RtlInitUnicodeString(&ValueName
, L
"CSDVersion");
2299 if (CmCSDVersionString
.Length
!= 0)
2301 NtSetValueKey(CurrentVersionKeyHandle
,
2305 CmCSDVersionString
.Buffer
,
2306 CmCSDVersionString
.Length
+ sizeof(WCHAR
));
2310 NtDeleteValueKey(CurrentVersionKeyHandle
, &ValueName
);
2313 /* Set the 'CSDBuildNumber' value */
2314 RtlInitUnicodeString(&ValueName
, L
"CSDBuildNumber");
2315 if (CmNtSpBuildNumber
!= 0)
2317 RtlInitEmptyUnicodeString(&ValueData
, Buffer
, sizeof(Buffer
));
2318 RtlIntegerToUnicodeString(CmNtSpBuildNumber
, 10, &ValueData
);
2319 NtSetValueKey(CurrentVersionKeyHandle
,
2324 ValueData
.Length
+ sizeof(WCHAR
));
2328 NtDeleteValueKey(CurrentVersionKeyHandle
, &ValueName
);
2331 /* Set the 'SystemRoot' value */
2332 RtlInitUnicodeString(&ValueName
, L
"SystemRoot");
2333 NtSetValueKey(CurrentVersionKeyHandle
,
2337 NtSystemRoot
.Buffer
,
2338 NtSystemRoot
.Length
+ sizeof(WCHAR
));
2341 /* Close the keys */
2342 if (CurrentVersionKeyHandle
!= NULL
)
2343 NtClose(CurrentVersionKeyHandle
);
2345 if (WindowsNtKeyHandle
!= NULL
)
2346 NtClose(WindowsNtKeyHandle
);
2348 if (MicrosoftKeyHandle
!= NULL
)
2349 NtClose(MicrosoftKeyHandle
);
2351 if (SoftwareKeyHandle
!= NULL
)
2352 NtClose(SoftwareKeyHandle
);