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_ PWSTR LinkKeyName
,
44 _In_z_ PWSTR TargetKeyName
)
46 OBJECT_ATTRIBUTES ObjectAttributes
;
47 UNICODE_STRING LinkKeyName_U
;
48 HANDLE TargetKeyHandle
;
53 /* Initialize the object attributes */
54 RtlInitUnicodeString(&LinkKeyName_U
, LinkKeyName
);
55 InitializeObjectAttributes(&ObjectAttributes
,
57 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
61 /* Create the link key */
62 Status
= ZwCreateKey(&TargetKeyHandle
,
67 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
69 if (!NT_SUCCESS(Status
))
71 DPRINT1("CM: CmpLinkKeyToHive: couldn't create %S Status = 0x%lx\n",
76 /* Check if the new key was actually created */
77 if (Disposition
!= REG_CREATED_NEW_KEY
)
79 DPRINT1("CM: CmpLinkKeyToHive: %S already exists!\n", LinkKeyName
);
80 ZwClose(TargetKeyHandle
);
84 /* Set the target key name as link target */
85 Status
= ZwSetValueKey(TargetKeyHandle
,
86 &CmSymbolicLinkValueName
,
90 (ULONG
)wcslen(TargetKeyName
) * sizeof(WCHAR
));
92 /* Close the link key handle */
93 ObCloseHandle(TargetKeyHandle
, KernelMode
);
95 if (!NT_SUCCESS(Status
))
97 DPRINT1("CM: CmpLinkKeyToHive: couldn't create symbolic link for %S\n",
107 CmpDeleteKeyObject(PVOID DeletedObject
)
109 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)DeletedObject
;
110 PCM_KEY_CONTROL_BLOCK Kcb
;
111 REG_KEY_HANDLE_CLOSE_INFORMATION KeyHandleCloseInfo
;
112 REG_POST_OPERATION_INFORMATION PostOperationInfo
;
116 /* First off, prepare the handle close information callback */
117 PostOperationInfo
.Object
= KeyBody
;
118 KeyHandleCloseInfo
.Object
= KeyBody
;
119 Status
= CmiCallRegisteredCallbacks(RegNtPreKeyHandleClose
,
120 &KeyHandleCloseInfo
);
121 if (!NT_SUCCESS(Status
))
123 /* If we failed, notify the post routine */
124 PostOperationInfo
.Status
= Status
;
125 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
129 /* Acquire hive lock */
132 /* Make sure this is a valid key body */
133 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
136 Kcb
= KeyBody
->KeyControlBlock
;
140 DelistKeyBodyFromKCB(KeyBody
, FALSE
);
142 /* Dereference the KCB */
143 CmpDelayDerefKeyControlBlock(Kcb
);
147 /* Release the registry lock */
150 /* Do the post callback */
151 PostOperationInfo
.Status
= STATUS_SUCCESS
;
152 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
157 CmpCloseKeyObject(IN PEPROCESS Process OPTIONAL
,
159 IN ACCESS_MASK GrantedAccess
,
160 IN ULONG ProcessHandleCount
,
161 IN ULONG SystemHandleCount
)
163 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)Object
;
166 /* Don't do anything if we're not the last handle */
167 if (SystemHandleCount
> 1) return;
169 /* Make sure we're a valid key body */
170 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
172 /* Don't do anything if we don't have a notify block */
173 if (!KeyBody
->NotifyBlock
) return;
175 /* This shouldn't happen yet */
182 CmpQueryKeyName(IN PVOID ObjectBody
,
184 IN OUT POBJECT_NAME_INFORMATION ObjectNameInfo
,
186 OUT PULONG ReturnLength
,
187 IN KPROCESSOR_MODE PreviousMode
)
189 PUNICODE_STRING KeyName
;
191 NTSTATUS Status
= STATUS_SUCCESS
;
192 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)ObjectBody
;
193 PCM_KEY_CONTROL_BLOCK Kcb
= KeyBody
->KeyControlBlock
;
195 /* Acquire hive lock */
198 /* Lock KCB shared */
199 CmpAcquireKcbLockShared(Kcb
);
201 /* Check if it's a deleted block */
204 /* Release the locks */
205 CmpReleaseKcbLock(Kcb
);
208 /* Let the caller know it's deleted */
209 return STATUS_KEY_DELETED
;
213 KeyName
= CmpConstructName(Kcb
);
215 /* Release the locks */
216 CmpReleaseKcbLock(Kcb
);
219 /* Check if we got the name */
220 if (!KeyName
) return STATUS_INSUFFICIENT_RESOURCES
;
222 /* Set the returned length */
223 *ReturnLength
= KeyName
->Length
+ sizeof(OBJECT_NAME_INFORMATION
) + sizeof(WCHAR
);
225 /* Calculate amount of bytes to copy into the buffer */
226 BytesToCopy
= KeyName
->Length
+ sizeof(WCHAR
);
228 /* Check if the provided buffer is too small to fit even anything */
229 if ((Length
<= sizeof(OBJECT_NAME_INFORMATION
)) ||
230 ((Length
< (*ReturnLength
)) && (BytesToCopy
< sizeof(WCHAR
))))
232 /* Free the buffer allocated by CmpConstructName */
233 ExFreePoolWithTag(KeyName
, TAG_CM
);
235 /* Return buffer length failure without writing anything there because nothing fits */
236 return STATUS_INFO_LENGTH_MISMATCH
;
239 /* Check if the provided buffer can be partially written */
240 if (Length
< (*ReturnLength
))
242 /* Yes, indicate so in the return status */
243 Status
= STATUS_INFO_LENGTH_MISMATCH
;
245 /* Calculate amount of bytes which the provided buffer could handle */
246 BytesToCopy
= Length
- sizeof(OBJECT_NAME_INFORMATION
);
249 /* Remove the null termination character from the size */
250 BytesToCopy
-= sizeof(WCHAR
);
252 /* Fill in the result */
255 /* Return data to user */
256 ObjectNameInfo
->Name
.Buffer
= (PWCHAR
)(ObjectNameInfo
+ 1);
257 ObjectNameInfo
->Name
.MaximumLength
= KeyName
->Length
;
258 ObjectNameInfo
->Name
.Length
= KeyName
->Length
;
260 /* Copy string content*/
261 RtlCopyMemory(ObjectNameInfo
->Name
.Buffer
,
265 /* Null terminate it */
266 ObjectNameInfo
->Name
.Buffer
[BytesToCopy
/ sizeof(WCHAR
)] = 0;
268 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
271 Status
= _SEH2_GetExceptionCode();
275 /* Free the buffer allocated by CmpConstructName */
276 ExFreePoolWithTag(KeyName
, TAG_CM
);
284 CmpInitHiveFromFile(IN PCUNICODE_STRING HiveName
,
290 ULONG HiveDisposition
, LogDisposition
;
291 HANDLE FileHandle
= NULL
, LogHandle
= NULL
;
293 ULONG Operation
, FileType
;
300 /* Open or create the hive files */
301 Status
= CmpOpenHiveFiles(HiveName
,
311 if (!NT_SUCCESS(Status
)) return Status
;
313 /* Check if we have a log handle */
314 FileType
= (LogHandle
) ? HFILE_TYPE_LOG
: HFILE_TYPE_PRIMARY
;
316 /* Check if we created or opened the hive */
317 if (HiveDisposition
== FILE_CREATED
)
319 /* Do a create operation */
320 Operation
= HINIT_CREATE
;
325 /* Open it as a file */
326 Operation
= HINIT_FILE
;
330 /* Check if we're sharing hives */
331 if (CmpShareSystemHives
)
333 /* Then force using the primary hive */
334 FileType
= HFILE_TYPE_PRIMARY
;
337 /* Get rid of the log handle */
343 /* Check if we're too late */
344 if (HvShutdownComplete
)
348 if (LogHandle
) ZwClose(LogHandle
);
349 return STATUS_TOO_LATE
;
352 /* Initialize the hive */
353 Status
= CmpInitializeHive((PCMHIVE
*)&NewHive
,
363 if (!NT_SUCCESS(Status
))
367 if (LogHandle
) ZwClose(LogHandle
);
371 /* Success, return hive */
374 /* HACK: ROS: Init root key cell and prepare the hive */
375 if (Operation
== HINIT_CREATE
) CmCreateRootNode(&NewHive
->Hive
, L
"");
377 /* Duplicate the hive name */
378 NewHive
->FileFullPath
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
381 if (NewHive
->FileFullPath
.Buffer
)
383 /* Copy the string */
384 RtlCopyMemory(NewHive
->FileFullPath
.Buffer
,
387 NewHive
->FileFullPath
.Length
= HiveName
->Length
;
388 NewHive
->FileFullPath
.MaximumLength
= HiveName
->MaximumLength
;
392 return STATUS_SUCCESS
;
398 CmpSetSystemValues(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
400 OBJECT_ATTRIBUTES ObjectAttributes
;
401 UNICODE_STRING KeyName
, ValueName
= { 0, 0, NULL
};
402 HANDLE KeyHandle
= NULL
;
404 ASSERT(LoaderBlock
!= NULL
);
406 /* Setup attributes for loader options */
407 RtlInitUnicodeString(&KeyName
,
408 L
"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\"
410 InitializeObjectAttributes(&ObjectAttributes
,
412 OBJ_CASE_INSENSITIVE
,
415 Status
= NtOpenKey(&KeyHandle
, KEY_WRITE
, &ObjectAttributes
);
416 if (!NT_SUCCESS(Status
)) goto Quickie
;
418 /* Key opened, now write to the key */
419 RtlInitUnicodeString(&KeyName
, L
"SystemStartOptions");
420 Status
= NtSetValueKey(KeyHandle
,
424 CmpLoadOptions
.Buffer
,
425 CmpLoadOptions
.Length
);
426 if (!NT_SUCCESS(Status
)) goto Quickie
;
428 /* Setup value name for system boot device in ARC format */
429 RtlInitUnicodeString(&KeyName
, L
"SystemBootDevice");
430 RtlCreateUnicodeStringFromAsciiz(&ValueName
, LoaderBlock
->ArcBootDeviceName
);
431 Status
= NtSetValueKey(KeyHandle
,
439 /* Free the buffers */
440 RtlFreeUnicodeString(&ValueName
);
442 /* Close the key and return */
443 if (KeyHandle
) NtClose(KeyHandle
);
445 /* Return the status */
446 return (ExpInTextModeSetup
? STATUS_SUCCESS
: Status
);
452 CmpCreateControlSet(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
454 UNICODE_STRING ConfigName
= RTL_CONSTANT_STRING(L
"Control\\IDConfigDB");
455 UNICODE_STRING SelectName
=
456 RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\Select");
457 UNICODE_STRING KeyName
;
458 OBJECT_ATTRIBUTES ObjectAttributes
;
459 CHAR ValueInfoBuffer
[128];
460 PKEY_VALUE_FULL_INFORMATION ValueInfo
;
462 WCHAR UnicodeBuffer
[128];
463 HANDLE SelectHandle
, KeyHandle
, ConfigHandle
= NULL
, ProfileHandle
= NULL
;
464 HANDLE ParentHandle
= NULL
;
465 ULONG ControlSet
, HwProfile
;
466 ANSI_STRING TempString
;
468 ULONG ResultLength
, Disposition
;
469 PLOADER_PARAMETER_EXTENSION LoaderExtension
;
472 /* Open the select key */
473 InitializeObjectAttributes(&ObjectAttributes
,
475 OBJ_CASE_INSENSITIVE
,
478 Status
= NtOpenKey(&SelectHandle
, KEY_READ
, &ObjectAttributes
);
479 if (!NT_SUCCESS(Status
))
481 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
482 if (!LoaderBlock
->RegistryBase
)
484 /* Build the ControlSet001 key */
485 RtlInitUnicodeString(&KeyName
,
486 L
"\\Registry\\Machine\\System\\ControlSet001");
487 InitializeObjectAttributes(&ObjectAttributes
,
489 OBJ_CASE_INSENSITIVE
,
492 Status
= NtCreateKey(&KeyHandle
,
499 if (!NT_SUCCESS(Status
)) return Status
;
501 /* Don't need the handle */
504 /* Use hard-coded setting */
509 /* Fail for real boots */
513 /* Open the current value */
514 RtlInitUnicodeString(&KeyName
, L
"Current");
515 Status
= NtQueryValueKey(SelectHandle
,
517 KeyValueFullInformation
,
519 sizeof(ValueInfoBuffer
),
521 NtClose(SelectHandle
);
522 if (!NT_SUCCESS(Status
)) return Status
;
524 /* Get the actual value pointer, and get the control set ID */
525 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
526 ControlSet
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
528 /* Create the current control set key */
530 RtlInitUnicodeString(&KeyName
,
531 L
"\\Registry\\Machine\\System\\CurrentControlSet");
532 InitializeObjectAttributes(&ObjectAttributes
,
534 OBJ_CASE_INSENSITIVE
,
537 Status
= NtCreateKey(&KeyHandle
,
542 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
544 if (!NT_SUCCESS(Status
)) return Status
;
547 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
549 /* Initialize the symbolic link name */
551 "\\Registry\\Machine\\System\\ControlSet%03ld",
553 RtlInitAnsiString(&TempString
, Buffer
);
555 /* Create a Unicode string out of it */
556 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
557 KeyName
.Buffer
= UnicodeBuffer
;
558 Status
= RtlAnsiStringToUnicodeString(&KeyName
, &TempString
, FALSE
);
561 Status
= NtSetValueKey(KeyHandle
,
562 &CmSymbolicLinkValueName
,
567 if (!NT_SUCCESS(Status
)) return Status
;
569 /* Get the configuration database key */
570 InitializeObjectAttributes(&ObjectAttributes
,
572 OBJ_CASE_INSENSITIVE
,
575 Status
= NtOpenKey(&ConfigHandle
, KEY_READ
, &ObjectAttributes
);
578 /* Check if we don't have one */
579 if (!NT_SUCCESS(Status
))
581 /* Cleanup and exit */
586 /* Now get the current config */
587 RtlInitUnicodeString(&KeyName
, L
"CurrentConfig");
588 Status
= NtQueryValueKey(ConfigHandle
,
590 KeyValueFullInformation
,
592 sizeof(ValueInfoBuffer
),
595 /* Set pointer to buffer */
596 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
598 /* Check if we failed or got a non DWORD-value */
599 if (!(NT_SUCCESS(Status
)) || (ValueInfo
->Type
!= REG_DWORD
)) goto Cleanup
;
601 /* Get the hadware profile */
602 HwProfile
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
604 /* Open the hardware profile key */
605 RtlInitUnicodeString(&KeyName
,
606 L
"\\Registry\\Machine\\System\\CurrentControlSet"
607 L
"\\Hardware Profiles");
608 InitializeObjectAttributes(&ObjectAttributes
,
610 OBJ_CASE_INSENSITIVE
,
613 Status
= NtOpenKey(&ParentHandle
, KEY_READ
, &ObjectAttributes
);
614 if (!NT_SUCCESS(Status
))
616 /* Exit and clean up */
621 /* Build the profile name */
622 sprintf(Buffer
, "%04ld", HwProfile
);
623 RtlInitAnsiString(&TempString
, Buffer
);
625 /* Convert it to Unicode */
626 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
627 KeyName
.Buffer
= UnicodeBuffer
;
628 Status
= RtlAnsiStringToUnicodeString(&KeyName
,
631 ASSERT(Status
== STATUS_SUCCESS
);
633 /* Open the associated key */
634 InitializeObjectAttributes(&ObjectAttributes
,
636 OBJ_CASE_INSENSITIVE
,
639 Status
= NtOpenKey(&ProfileHandle
,
640 KEY_READ
| KEY_WRITE
,
642 if (!NT_SUCCESS (Status
))
644 /* Cleanup and exit */
649 /* Check if we have a loader block extension */
650 LoaderExtension
= LoaderBlock
->Extension
;
653 DPRINT("ReactOS doesn't support NTLDR Profiles yet!\n");
656 /* Create the current hardware profile key */
657 RtlInitUnicodeString(&KeyName
,
658 L
"\\Registry\\Machine\\System\\CurrentControlSet\\"
659 L
"Hardware Profiles\\Current");
660 InitializeObjectAttributes(&ObjectAttributes
,
662 OBJ_CASE_INSENSITIVE
,
665 Status
= NtCreateKey(&KeyHandle
,
670 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
672 if (NT_SUCCESS(Status
))
675 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
677 /* Create the profile name */
679 "\\Registry\\Machine\\System\\CurrentControlSet\\"
680 "Hardware Profiles\\%04ld",
682 RtlInitAnsiString(&TempString
, Buffer
);
684 /* Convert it to Unicode */
685 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
686 KeyName
.Buffer
= UnicodeBuffer
;
687 Status
= RtlAnsiStringToUnicodeString(&KeyName
,
690 ASSERT(STATUS_SUCCESS
== Status
);
693 Status
= NtSetValueKey(KeyHandle
,
694 &CmSymbolicLinkValueName
,
702 /* Close every opened handle */
704 if (ConfigHandle
) NtClose(ConfigHandle
);
705 if (ProfileHandle
) NtClose(ProfileHandle
);
706 if (ParentHandle
) NtClose(ParentHandle
);
709 return STATUS_SUCCESS
;
714 CmpLinkHiveToMaster(IN PUNICODE_STRING LinkName
,
715 IN HANDLE RootDirectory
,
716 IN PCMHIVE RegistryHive
,
718 IN PSECURITY_DESCRIPTOR SecurityDescriptor
)
720 OBJECT_ATTRIBUTES ObjectAttributes
;
722 CM_PARSE_CONTEXT ParseContext
= {0};
724 PCM_KEY_BODY KeyBody
;
727 /* Setup the object attributes */
728 InitializeObjectAttributes(&ObjectAttributes
,
730 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
734 /* Setup the parse context */
735 ParseContext
.CreateLink
= TRUE
;
736 ParseContext
.CreateOperation
= TRUE
;
737 ParseContext
.ChildHive
.KeyHive
= &RegistryHive
->Hive
;
739 /* Check if we have a root keycell or if we need to create it */
743 ParseContext
.ChildHive
.KeyCell
= HCELL_NIL
;
748 ParseContext
.ChildHive
.KeyCell
= RegistryHive
->Hive
.BaseBlock
->RootCell
;
751 /* Create the link node */
752 Status
= ObOpenObjectByName(&ObjectAttributes
,
756 KEY_READ
| KEY_WRITE
,
757 (PVOID
)&ParseContext
,
759 if (!NT_SUCCESS(Status
)) return Status
;
761 /* Mark the hive as clean */
762 RegistryHive
->Hive
.DirtyFlag
= FALSE
;
764 /* ReactOS Hack: Keep alive */
765 Status
= ObReferenceObjectByHandle(KeyHandle
,
771 ASSERT(NT_SUCCESS(Status
));
773 /* Close the extra handle */
775 return STATUS_SUCCESS
;
781 CmpInitializeSystemHive(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
784 ANSI_STRING LoadString
;
789 UNICODE_STRING KeyName
;
790 PCMHIVE SystemHive
= NULL
;
791 UNICODE_STRING HiveName
= RTL_CONSTANT_STRING(L
"SYSTEM");
792 PSECURITY_DESCRIPTOR SecurityDescriptor
;
795 /* Setup the ansi string */
796 RtlInitAnsiString(&LoadString
, LoaderBlock
->LoadOptions
);
798 /* Allocate the unicode buffer */
799 Length
= LoadString
.Length
* sizeof(WCHAR
) + sizeof(UNICODE_NULL
);
800 Buffer
= ExAllocatePoolWithTag(PagedPool
, Length
, TAG_CM
);
804 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 3, 1, (ULONG_PTR
)LoaderBlock
, 0);
807 /* Setup the unicode string */
808 RtlInitEmptyUnicodeString(&CmpLoadOptions
, Buffer
, (USHORT
)Length
);
810 /* Add the load options and null-terminate */
811 RtlAnsiStringToUnicodeString(&CmpLoadOptions
, &LoadString
, FALSE
);
812 CmpLoadOptions
.Buffer
[LoadString
.Length
] = UNICODE_NULL
;
813 CmpLoadOptions
.Length
+= sizeof(WCHAR
);
815 /* Get the System Hive base address */
816 HiveBase
= LoaderBlock
->RegistryBase
;
820 Status
= CmpInitializeHive((PCMHIVE
*)&SystemHive
,
830 if (!NT_SUCCESS(Status
)) return FALSE
;
832 /* Set the hive filename */
833 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
834 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
836 /* We imported, no need to create a new hive */
839 /* Manually set the hive as volatile, if in Live CD mode */
840 if (CmpShareSystemHives
) SystemHive
->Hive
.HiveFlags
= HIVE_VOLATILE
;
845 Status
= CmpInitializeHive(&SystemHive
,
855 if (!NT_SUCCESS(Status
)) return FALSE
;
857 /* Set the hive filename */
858 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
859 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
861 /* Tell CmpLinkHiveToMaster to allocate a hive */
865 /* Save the boot type */
866 CmpBootType
= SystemHive
->Hive
.BaseBlock
->BootType
;
868 /* Are we in self-healing mode? */
871 /* Disable self-healing internally and check if boot type wanted it */
875 /* We're disabled, so bugcheck */
876 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
,
879 (ULONG_PTR
)SystemHive
,
884 /* Create the default security descriptor */
885 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
887 /* Attach it to the system key */
888 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\SYSTEM");
889 Status
= CmpLinkHiveToMaster(&KeyName
,
895 /* Free the security descriptor */
896 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
897 if (!NT_SUCCESS(Status
)) return FALSE
;
899 /* Add the hive to the hive list */
900 CmpMachineHiveList
[3].CmHive
= (PCMHIVE
)SystemHive
;
909 CmpCreateObjectTypes(VOID
)
911 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer
;
913 GENERIC_MAPPING CmpKeyMapping
= {KEY_READ
,
919 /* Initialize the Key object type */
920 RtlZeroMemory(&ObjectTypeInitializer
, sizeof(ObjectTypeInitializer
));
921 RtlInitUnicodeString(&Name
, L
"Key");
922 ObjectTypeInitializer
.Length
= sizeof(ObjectTypeInitializer
);
923 ObjectTypeInitializer
.DefaultPagedPoolCharge
= sizeof(CM_KEY_BODY
);
924 ObjectTypeInitializer
.GenericMapping
= CmpKeyMapping
;
925 ObjectTypeInitializer
.PoolType
= PagedPool
;
926 ObjectTypeInitializer
.ValidAccessMask
= KEY_ALL_ACCESS
;
927 ObjectTypeInitializer
.UseDefaultObject
= TRUE
;
928 ObjectTypeInitializer
.DeleteProcedure
= CmpDeleteKeyObject
;
929 ObjectTypeInitializer
.ParseProcedure
= CmpParseKey
;
930 ObjectTypeInitializer
.SecurityProcedure
= CmpSecurityMethod
;
931 ObjectTypeInitializer
.QueryNameProcedure
= CmpQueryKeyName
;
932 ObjectTypeInitializer
.CloseProcedure
= CmpCloseKeyObject
;
933 ObjectTypeInitializer
.SecurityRequired
= TRUE
;
934 ObjectTypeInitializer
.InvalidAttributes
= OBJ_EXCLUSIVE
| OBJ_PERMANENT
;
937 return ObCreateObjectType(&Name
, &ObjectTypeInitializer
, NULL
, &CmpKeyObjectType
);
943 CmpCreateRootNode(IN PHHIVE Hive
,
945 OUT PHCELL_INDEX Index
)
947 UNICODE_STRING KeyName
;
948 PCM_KEY_NODE KeyCell
;
949 LARGE_INTEGER SystemTime
;
952 /* Initialize the node name and allocate it */
953 RtlInitUnicodeString(&KeyName
, Name
);
954 *Index
= HvAllocateCell(Hive
,
955 FIELD_OFFSET(CM_KEY_NODE
, Name
) +
956 CmpNameSize(Hive
, &KeyName
),
959 if (*Index
== HCELL_NIL
) return FALSE
;
961 /* Set the cell index and get the data */
962 Hive
->BaseBlock
->RootCell
= *Index
;
963 KeyCell
= (PCM_KEY_NODE
)HvGetCell(Hive
, *Index
);
964 if (!KeyCell
) return FALSE
;
967 KeyCell
->Signature
= (USHORT
)CM_KEY_NODE_SIGNATURE
;
968 KeyCell
->Flags
= KEY_HIVE_ENTRY
| KEY_NO_DELETE
;
969 KeQuerySystemTime(&SystemTime
);
970 KeyCell
->LastWriteTime
= SystemTime
;
971 KeyCell
->Parent
= HCELL_NIL
;
972 KeyCell
->SubKeyCounts
[Stable
] = 0;
973 KeyCell
->SubKeyCounts
[Volatile
] = 0;
974 KeyCell
->SubKeyLists
[Stable
] = HCELL_NIL
;
975 KeyCell
->SubKeyLists
[Volatile
] = HCELL_NIL
;
976 KeyCell
->ValueList
.Count
= 0;
977 KeyCell
->ValueList
.List
= HCELL_NIL
;
978 KeyCell
->Security
= HCELL_NIL
;
979 KeyCell
->Class
= HCELL_NIL
;
980 KeyCell
->ClassLength
= 0;
981 KeyCell
->MaxNameLen
= 0;
982 KeyCell
->MaxClassLen
= 0;
983 KeyCell
->MaxValueNameLen
= 0;
984 KeyCell
->MaxValueDataLen
= 0;
986 /* Copy the name (this will also set the length) */
987 KeyCell
->NameLength
= CmpCopyName(Hive
, (PWCHAR
)KeyCell
->Name
, &KeyName
);
989 /* Check if the name was compressed */
990 if (KeyCell
->NameLength
< KeyName
.Length
)
993 KeyCell
->Flags
|= KEY_COMP_NAME
;
997 HvReleaseCell(Hive
, *Index
);
1004 CmpCreateRegistryRoot(VOID
)
1006 UNICODE_STRING KeyName
;
1007 OBJECT_ATTRIBUTES ObjectAttributes
;
1008 PCM_KEY_BODY RootKey
;
1009 HCELL_INDEX RootIndex
;
1011 PCM_KEY_NODE KeyCell
;
1012 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1013 PCM_KEY_CONTROL_BLOCK Kcb
;
1016 /* Setup the root node */
1017 if (!CmpCreateRootNode(&CmiVolatileHive
->Hive
, L
"REGISTRY", &RootIndex
))
1023 /* Create '\Registry' key. */
1024 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1025 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1026 InitializeObjectAttributes(&ObjectAttributes
,
1028 OBJ_CASE_INSENSITIVE
,
1031 Status
= ObCreateObject(KernelMode
,
1036 sizeof(CM_KEY_BODY
),
1040 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1041 if (!NT_SUCCESS(Status
)) return FALSE
;
1043 /* Sanity check, and get the key cell */
1044 ASSERT((&CmiVolatileHive
->Hive
)->ReleaseCellRoutine
== NULL
);
1045 KeyCell
= (PCM_KEY_NODE
)HvGetCell(&CmiVolatileHive
->Hive
, RootIndex
);
1046 if (!KeyCell
) return FALSE
;
1048 /* Create the KCB */
1049 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1050 Kcb
= CmpCreateKeyControlBlock(&CmiVolatileHive
->Hive
,
1058 ObDereferenceObject(RootKey
);
1062 /* Initialize the object */
1063 RootKey
->KeyControlBlock
= Kcb
;
1064 RootKey
->Type
= CM_KEY_BODY_TYPE
;
1065 RootKey
->NotifyBlock
= NULL
;
1066 RootKey
->ProcessID
= PsGetCurrentProcessId();
1069 EnlistKeyBodyWithKCB(RootKey
, 0);
1071 /* Insert the key into the namespace */
1072 Status
= ObInsertObject(RootKey
,
1077 &CmpRegistryRootHandle
);
1078 if (!NT_SUCCESS(Status
))
1080 ObDereferenceObject(RootKey
);
1084 /* Reference the key again so that we never lose it */
1085 Status
= ObReferenceObjectByHandle(CmpRegistryRootHandle
,
1091 if (!NT_SUCCESS(Status
))
1093 ObDereferenceObject(RootKey
);
1097 /* Completely sucessful */
1103 CmpGetRegistryPath(IN PWCHAR ConfigPath
)
1105 OBJECT_ATTRIBUTES ObjectAttributes
;
1108 PKEY_VALUE_PARTIAL_INFORMATION ValueInfo
;
1109 UNICODE_STRING KeyName
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\HARDWARE");
1110 UNICODE_STRING ValueName
= RTL_CONSTANT_STRING(L
"InstallPath");
1111 ULONG BufferSize
, ResultSize
;
1113 /* Check if we are booted in setup */
1114 if (ExpInTextModeSetup
)
1116 /* Setup the object attributes */
1117 InitializeObjectAttributes(&ObjectAttributes
,
1119 OBJ_CASE_INSENSITIVE
,
1123 Status
= ZwOpenKey(&KeyHandle
,
1126 if (!NT_SUCCESS(Status
)) return Status
;
1128 /* Allocate the buffer */
1129 BufferSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 4096;
1130 ValueInfo
= ExAllocatePoolWithTag(PagedPool
, BufferSize
, TAG_CM
);
1135 return STATUS_INSUFFICIENT_RESOURCES
;
1138 /* Query the value */
1139 Status
= ZwQueryValueKey(KeyHandle
,
1141 KeyValuePartialInformation
,
1146 if (!NT_SUCCESS(Status
))
1149 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1153 /* Copy the config path and null-terminate it */
1154 RtlCopyMemory(ConfigPath
,
1156 ValueInfo
->DataLength
);
1157 ConfigPath
[ValueInfo
->DataLength
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1158 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1162 /* Just use default path */
1163 wcscpy(ConfigPath
, L
"\\SystemRoot");
1166 /* Add registry path */
1167 wcscat(ConfigPath
, L
"\\System32\\Config\\");
1170 return STATUS_SUCCESS
;
1175 CmpLoadHiveThread(IN PVOID StartContext
)
1177 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1178 UNICODE_STRING TempName
, FileName
, RegName
;
1179 ULONG i
, ErrorResponse
, WorkerCount
, Length
;
1182 ULONG PrimaryDisposition
, SecondaryDisposition
, ClusterSize
;
1184 HANDLE PrimaryHandle
= NULL
, LogHandle
= NULL
;
1185 NTSTATUS Status
= STATUS_SUCCESS
;
1186 PVOID ErrorParameters
;
1189 /* Get the hive index, make sure it makes sense */
1190 i
= PtrToUlong(StartContext
);
1191 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1193 /* We were started */
1194 CmpMachineHiveList
[i
].ThreadStarted
= TRUE
;
1196 /* Build the file name and registry name strings */
1197 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, MAX_PATH
);
1198 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, MAX_PATH
);
1200 /* Now build the system root path */
1201 CmpGetRegistryPath(ConfigPath
);
1202 RtlInitUnicodeString(&TempName
, ConfigPath
);
1203 RtlAppendStringToString((PSTRING
)&FileName
, (PSTRING
)&TempName
);
1204 FileStart
= FileName
.Length
;
1206 /* And build the registry root path */
1207 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1208 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1209 //RegStart = RegName.Length;
1211 /* Build the base name */
1212 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1213 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1215 /* Check if this is a child of the root */
1216 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == '\\')
1218 /* Then setup the whole name */
1219 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1220 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1223 /* Now add the rest of the file name */
1224 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1225 FileName
.Length
= FileStart
;
1226 RtlAppendStringToString((PSTRING
)&FileName
, (PSTRING
)&TempName
);
1227 if (!CmpMachineHiveList
[i
].CmHive
)
1229 /* We need to allocate a new hive structure */
1230 CmpMachineHiveList
[i
].Allocate
= TRUE
;
1232 /* Load the hive file */
1233 Status
= CmpInitHiveFromFile(&FileName
,
1234 CmpMachineHiveList
[i
].HHiveFlags
,
1236 &CmpMachineHiveList
[i
].Allocate
,
1238 if (!(NT_SUCCESS(Status
)) ||
1239 (!(CmHive
->FileHandles
[HFILE_TYPE_LOG
]) && !(CmpMiniNTBoot
))) // HACK
1241 /* We failed or couldn't get a log file, raise a hard error */
1242 ErrorParameters
= &FileName
;
1243 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1246 (PULONG_PTR
)&ErrorParameters
,
1251 /* Set the hive flags and newly allocated hive pointer */
1252 CmHive
->Flags
= CmpMachineHiveList
[i
].CmHiveFlags
;
1253 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1257 /* We already have a hive, is it volatile? */
1258 CmHive
= CmpMachineHiveList
[i
].CmHive
;
1259 if (!(CmHive
->Hive
.HiveFlags
& HIVE_VOLATILE
))
1261 /* It's now, open the hive file and log */
1262 Status
= CmpOpenHiveFiles(&FileName
,
1266 &PrimaryDisposition
,
1267 &SecondaryDisposition
,
1272 if (!(NT_SUCCESS(Status
)) || !(LogHandle
))
1274 /* Couldn't open the hive or its log file, raise a hard error */
1275 ErrorParameters
= &FileName
;
1276 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1279 (PULONG_PTR
)&ErrorParameters
,
1283 /* And bugcheck for posterity's sake */
1284 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 0, i
, Status
);
1287 /* Save the file handles. This should remove our sync hacks */
1288 CmHive
->FileHandles
[HFILE_TYPE_LOG
] = LogHandle
;
1289 CmHive
->FileHandles
[HFILE_TYPE_PRIMARY
] = PrimaryHandle
;
1291 /* Allow lazy flushing since the handles are there -- remove sync hacks */
1292 //ASSERT(CmHive->Hive.HiveFlags & HIVE_NOLAZYFLUSH);
1293 CmHive
->Hive
.HiveFlags
&= ~HIVE_NOLAZYFLUSH
;
1295 /* Get the real size of the hive */
1296 Length
= CmHive
->Hive
.Storage
[Stable
].Length
+ HBLOCK_SIZE
;
1298 /* Check if the cluster size doesn't match */
1299 if (CmHive
->Hive
.Cluster
!= ClusterSize
) ASSERT(FALSE
);
1301 /* Set the file size */
1302 DPRINT("FIXME: Should set file size: %lx\n", Length
);
1303 //if (!CmpFileSetSize((PHHIVE)CmHive, HFILE_TYPE_PRIMARY, Length, Length))
1305 /* This shouldn't fail */
1309 /* Another thing we don't support is NTLDR-recovery */
1310 if (CmHive
->Hive
.BaseBlock
->BootRecover
) ASSERT(FALSE
);
1312 /* Finally, set our allocated hive to the same hive we've had */
1313 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1314 ASSERT(CmpMachineHiveList
[i
].CmHive
== CmpMachineHiveList
[i
].CmHive2
);
1319 CmpMachineHiveList
[i
].ThreadFinished
= TRUE
;
1321 /* Check if we're the last worker */
1322 WorkerCount
= InterlockedIncrement(&CmpLoadWorkerIncrement
);
1323 if (WorkerCount
== CM_NUMBER_OF_MACHINE_HIVES
)
1325 /* Signal the event */
1326 KeSetEvent(&CmpLoadWorkerEvent
, 0, FALSE
);
1329 /* Kill the thread */
1330 PsTerminateSystemThread(Status
);
1335 CmpInitializeHiveList(IN USHORT Flag
)
1337 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1338 UNICODE_STRING TempName
, FileName
, RegName
;
1343 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1346 /* Allow writing for now */
1349 /* Build the file name and registry name strings */
1350 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, MAX_PATH
);
1351 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, MAX_PATH
);
1353 /* Now build the system root path */
1354 CmpGetRegistryPath(ConfigPath
);
1355 RtlInitUnicodeString(&TempName
, ConfigPath
);
1356 RtlAppendStringToString((PSTRING
)&FileName
, (PSTRING
)&TempName
);
1358 /* And build the registry root path */
1359 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1360 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1361 RegStart
= RegName
.Length
;
1363 /* Setup the event to synchronize workers */
1364 KeInitializeEvent(&CmpLoadWorkerEvent
, SynchronizationEvent
, FALSE
);
1366 /* Enter special boot condition */
1367 CmpSpecialBootCondition
= TRUE
;
1369 /* Create the SD for the root hives */
1370 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1372 /* Loop every hive we care about */
1373 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1375 /* Make sure the list is setup */
1376 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1378 /* Create a thread to handle this hive */
1379 Status
= PsCreateSystemThread(&Thread
,
1386 if (NT_SUCCESS(Status
))
1388 /* We don't care about the handle -- the thread self-terminates */
1393 /* Can't imagine this happening */
1394 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 3, i
, Status
);
1398 /* Make sure we've reached the end of the list */
1399 ASSERT(CmpMachineHiveList
[i
].Name
== NULL
);
1401 /* Wait for hive loading to finish */
1402 KeWaitForSingleObject(&CmpLoadWorkerEvent
,
1408 /* Exit the special boot condition and make sure all workers completed */
1409 CmpSpecialBootCondition
= FALSE
;
1410 ASSERT(CmpLoadWorkerIncrement
== CM_NUMBER_OF_MACHINE_HIVES
);
1412 /* Loop hives again */
1413 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1415 /* Make sure the thread ran and finished */
1416 ASSERT(CmpMachineHiveList
[i
].ThreadFinished
== TRUE
);
1417 ASSERT(CmpMachineHiveList
[i
].ThreadStarted
== TRUE
);
1419 /* Check if this was a new hive */
1420 if (!CmpMachineHiveList
[i
].CmHive
)
1422 /* Make sure we allocated something */
1423 ASSERT(CmpMachineHiveList
[i
].CmHive2
!= NULL
);
1425 /* Build the base name */
1426 RegName
.Length
= RegStart
;
1427 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1428 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1430 /* Check if this is a child of the root */
1431 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == '\\')
1433 /* Then setup the whole name */
1434 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1435 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1438 /* Now link the hive to its master */
1439 Status
= CmpLinkHiveToMaster(&RegName
,
1441 CmpMachineHiveList
[i
].CmHive2
,
1442 CmpMachineHiveList
[i
].Allocate
,
1443 SecurityDescriptor
);
1444 if (Status
!= STATUS_SUCCESS
)
1446 /* Linking needs to work */
1447 KeBugCheckEx(CONFIG_LIST_FAILED
, 11, Status
, i
, (ULONG_PTR
)&RegName
);
1450 /* Check if we had to allocate a new hive */
1451 if (CmpMachineHiveList
[i
].Allocate
)
1453 /* Sync the new hive */
1454 //HvSyncHive((PHHIVE)(CmpMachineHiveList[i].CmHive2));
1458 /* Check if we created a new hive */
1459 if (CmpMachineHiveList
[i
].CmHive2
)
1461 /* Add to HiveList key */
1462 CmpAddToHiveFileList(CmpMachineHiveList
[i
].CmHive2
);
1466 /* Get rid of the SD */
1467 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1469 /* Link SECURITY to SAM */
1470 CmpLinkKeyToHive(L
"\\Registry\\Machine\\Security\\SAM",
1471 L
"\\Registry\\Machine\\SAM\\SAM");
1473 /* Link S-1-5-18 to .Default */
1474 CmpNoVolatileCreates
= FALSE
;
1475 CmpLinkKeyToHive(L
"\\Registry\\User\\S-1-5-18",
1476 L
"\\Registry\\User\\.Default");
1477 CmpNoVolatileCreates
= TRUE
;
1485 OBJECT_ATTRIBUTES ObjectAttributes
;
1486 UNICODE_STRING KeyName
;
1489 PCMHIVE HardwareHive
;
1490 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1493 /* Check if this is PE-boot */
1494 if (InitIsWinPEMode
)
1496 /* Set registry to PE mode */
1497 CmpMiniNTBoot
= TRUE
;
1498 CmpShareSystemHives
= TRUE
;
1501 /* Initialize the hive list and lock */
1502 InitializeListHead(&CmpHiveListHead
);
1503 ExInitializePushLock(&CmpHiveListHeadLock
);
1504 ExInitializePushLock(&CmpLoadHiveLock
);
1506 /* Initialize registry lock */
1507 ExInitializeResourceLite(&CmpRegistryLock
);
1509 /* Initialize the cache */
1510 CmpInitializeCache();
1512 /* Initialize allocation and delayed dereferencing */
1513 CmpInitCmPrivateAlloc();
1514 CmpInitCmPrivateDelayAlloc();
1515 CmpInitDelayDerefKCBEngine();
1517 /* Initialize callbacks */
1520 /* Initialize self healing */
1521 KeInitializeGuardedMutex(&CmpSelfHealQueueLock
);
1522 InitializeListHead(&CmpSelfHealQueueListHead
);
1524 /* Save the current process and lock the registry */
1525 CmpSystemProcess
= PsGetCurrentProcess();
1527 /* Create the key object types */
1528 Status
= CmpCreateObjectTypes();
1529 if (!NT_SUCCESS(Status
))
1532 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 1, Status
, 0);
1535 /* Build the master hive */
1536 Status
= CmpInitializeHive(&CmiVolatileHive
,
1546 if (!NT_SUCCESS(Status
))
1549 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 2, Status
, 0);
1552 /* Create the \REGISTRY key node */
1553 if (!CmpCreateRegistryRoot())
1556 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 3, 0, 0);
1559 /* Create the default security descriptor */
1560 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1562 /* Create '\Registry\Machine' key. */
1563 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE");
1564 InitializeObjectAttributes(&ObjectAttributes
,
1566 OBJ_CASE_INSENSITIVE
,
1568 SecurityDescriptor
);
1569 Status
= NtCreateKey(&KeyHandle
,
1570 KEY_READ
| KEY_WRITE
,
1576 if (!NT_SUCCESS(Status
))
1579 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 5, Status
, 0);
1582 /* Close the handle */
1585 /* Create '\Registry\User' key. */
1586 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\USER");
1587 InitializeObjectAttributes(&ObjectAttributes
,
1589 OBJ_CASE_INSENSITIVE
,
1591 SecurityDescriptor
);
1592 Status
= NtCreateKey(&KeyHandle
,
1593 KEY_READ
| KEY_WRITE
,
1599 if (!NT_SUCCESS(Status
))
1602 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 6, Status
, 0);
1605 /* Close the handle */
1608 /* After this point, do not allow creating keys in the master hive */
1609 CmpNoVolatileCreates
= TRUE
;
1611 /* Initialize the system hive */
1612 if (!CmpInitializeSystemHive(KeLoaderBlock
))
1615 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 7, 0, 0);
1618 /* Create the 'CurrentControlSet' link. */
1619 Status
= CmpCreateControlSet(KeLoaderBlock
);
1620 if (!NT_SUCCESS(Status
))
1623 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 8, Status
, 0);
1626 /* Create the hardware hive */
1627 Status
= CmpInitializeHive((PCMHIVE
*)&HardwareHive
,
1637 if (!NT_SUCCESS(Status
))
1640 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 11, Status
, 0);
1643 /* Add the hive to the hive list */
1644 CmpMachineHiveList
[0].CmHive
= (PCMHIVE
)HardwareHive
;
1646 /* Attach it to the machine key */
1647 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\HARDWARE");
1648 Status
= CmpLinkHiveToMaster(&KeyName
,
1650 (PCMHIVE
)HardwareHive
,
1652 SecurityDescriptor
);
1653 if (!NT_SUCCESS(Status
))
1656 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 12, Status
, 0);
1659 /* Add to HiveList key */
1660 CmpAddToHiveFileList(HardwareHive
);
1662 /* Free the security descriptor */
1663 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1665 /* Fill out the Hardware key with the ARC Data from the Loader */
1666 Status
= CmpInitializeHardwareConfiguration(KeLoaderBlock
);
1667 if (!NT_SUCCESS(Status
))
1670 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 13, Status
, 0);
1673 /* Initialize machine-dependent information into the registry */
1674 Status
= CmpInitializeMachineDependentConfiguration(KeLoaderBlock
);
1675 if (!NT_SUCCESS(Status
))
1678 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 14, Status
, 0);
1681 /* Initialize volatile registry settings */
1682 Status
= CmpSetSystemValues(KeLoaderBlock
);
1683 if (!NT_SUCCESS(Status
))
1686 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 15, Status
, 0);
1689 /* Free the load options */
1690 ExFreePoolWithTag(CmpLoadOptions
.Buffer
, TAG_CM
);
1692 /* If we got here, all went well */
1699 CmpFreeDriverList(IN PHHIVE Hive
,
1700 IN PLIST_ENTRY DriverList
)
1702 PLIST_ENTRY NextEntry
, OldEntry
;
1703 PBOOT_DRIVER_NODE DriverNode
;
1706 /* Parse the current list */
1707 NextEntry
= DriverList
->Flink
;
1708 while (NextEntry
!= DriverList
)
1710 /* Get the driver node */
1711 DriverNode
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_NODE
, ListEntry
.Link
);
1713 /* Get the next entry now, since we're going to free it later */
1714 OldEntry
= NextEntry
;
1715 NextEntry
= NextEntry
->Flink
;
1717 /* Was there a name? */
1718 if (DriverNode
->Name
.Buffer
)
1721 CmpFree(DriverNode
->Name
.Buffer
, DriverNode
->Name
.Length
);
1724 /* Was there a registry path? */
1725 if (DriverNode
->ListEntry
.RegistryPath
.Buffer
)
1728 CmpFree(DriverNode
->ListEntry
.RegistryPath
.Buffer
,
1729 DriverNode
->ListEntry
.RegistryPath
.MaximumLength
);
1732 /* Was there a file path? */
1733 if (DriverNode
->ListEntry
.FilePath
.Buffer
)
1736 CmpFree(DriverNode
->ListEntry
.FilePath
.Buffer
,
1737 DriverNode
->ListEntry
.FilePath
.MaximumLength
);
1740 /* Now free the node, and move on */
1741 CmpFree(OldEntry
, sizeof(BOOT_DRIVER_NODE
));
1748 CmGetSystemDriverList(VOID
)
1750 LIST_ENTRY DriverList
;
1751 OBJECT_ATTRIBUTES ObjectAttributes
;
1753 PCM_KEY_BODY KeyBody
;
1755 HCELL_INDEX RootCell
, ControlCell
;
1757 UNICODE_STRING KeyName
;
1758 PLIST_ENTRY NextEntry
;
1760 PUNICODE_STRING
* ServicePath
= NULL
;
1761 BOOLEAN Success
, AutoSelect
;
1762 PBOOT_DRIVER_LIST_ENTRY DriverEntry
;
1765 /* Initialize the driver list */
1766 InitializeListHead(&DriverList
);
1768 /* Open the system hive key */
1769 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\System");
1770 InitializeObjectAttributes(&ObjectAttributes
,
1772 OBJ_CASE_INSENSITIVE
,
1775 Status
= NtOpenKey(&KeyHandle
, KEY_READ
, &ObjectAttributes
);
1776 if (!NT_SUCCESS(Status
)) return NULL
;
1778 /* Reference the key object to get the root hive/cell to access directly */
1779 Status
= ObReferenceObjectByHandle(KeyHandle
,
1785 if (!NT_SUCCESS(Status
))
1792 /* Do all this under the registry lock */
1793 CmpLockRegistryExclusive();
1795 /* Get the hive and key cell */
1796 Hive
= KeyBody
->KeyControlBlock
->KeyHive
;
1797 RootCell
= KeyBody
->KeyControlBlock
->KeyCell
;
1799 /* Open the current control set key */
1800 RtlInitUnicodeString(&KeyName
, L
"Current");
1801 ControlCell
= CmpFindControlSet(Hive
, RootCell
, &KeyName
, &AutoSelect
);
1802 if (ControlCell
== HCELL_NIL
) goto EndPath
;
1804 /* Find all system drivers */
1805 Success
= CmpFindDrivers(Hive
, ControlCell
, SystemLoad
, NULL
, &DriverList
);
1806 if (!Success
) goto EndPath
;
1808 /* Sort by group/tag */
1809 if (!CmpSortDriverList(Hive
, ControlCell
, &DriverList
)) goto EndPath
;
1811 /* Remove circular dependencies (cycles) and sort */
1812 if (!CmpResolveDriverDependencies(&DriverList
)) goto EndPath
;
1814 /* Loop the list to count drivers */
1815 for (i
= 0, NextEntry
= DriverList
.Flink
;
1816 NextEntry
!= &DriverList
;
1817 i
++, NextEntry
= NextEntry
->Flink
);
1819 /* Allocate the array */
1820 ServicePath
= ExAllocatePool(NonPagedPool
, (i
+ 1) * sizeof(PUNICODE_STRING
));
1821 if (!ServicePath
) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 2, 1, 0, 0);
1823 /* Loop the driver list */
1824 for (i
= 0, NextEntry
= DriverList
.Flink
;
1825 NextEntry
!= &DriverList
;
1826 i
++, NextEntry
= NextEntry
->Flink
)
1829 DriverEntry
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_LIST_ENTRY
, Link
);
1831 /* Allocate the path for the caller and duplicate the registry path */
1832 ServicePath
[i
] = ExAllocatePool(NonPagedPool
, sizeof(UNICODE_STRING
));
1833 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1834 &DriverEntry
->RegistryPath
,
1838 /* Terminate the list */
1839 ServicePath
[i
] = NULL
;
1842 /* Free the driver list if we had one */
1843 if (!IsListEmpty(&DriverList
)) CmpFreeDriverList(Hive
, &DriverList
);
1845 /* Unlock the registry */
1846 CmpUnlockRegistry();
1848 /* Close the key handle and dereference the object, then return the path */
1849 ObDereferenceObject(KeyBody
);
1856 CmpLockRegistryExclusive(VOID
)
1858 /* Enter a critical region and lock the registry */
1859 KeEnterCriticalRegion();
1860 ExAcquireResourceExclusiveLite(&CmpRegistryLock
, TRUE
);
1863 ASSERT(CmpFlushStarveWriters
== 0);
1864 RtlGetCallersAddress(&CmpRegistryLockCaller
, &CmpRegistryLockCallerCaller
);
1869 CmpLockRegistry(VOID
)
1871 /* Enter a critical region */
1872 KeEnterCriticalRegion();
1874 /* Check if we have to starve writers */
1875 if (CmpFlushStarveWriters
)
1877 /* Starve exlusive waiters */
1878 ExAcquireSharedStarveExclusive(&CmpRegistryLock
, TRUE
);
1882 /* Just grab the lock */
1883 ExAcquireResourceSharedLite(&CmpRegistryLock
, TRUE
);
1889 CmpTestRegistryLock(VOID
)
1892 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1897 CmpTestRegistryLockExclusive(VOID
)
1900 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1905 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive
)
1907 /* Lock the flusher. We should already be in a critical section */
1908 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1909 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1910 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1911 ExAcquireResourceExclusiveLite(Hive
->FlusherLock
, TRUE
);
1916 CmpLockHiveFlusherShared(IN PCMHIVE Hive
)
1918 /* Lock the flusher. We should already be in a critical section */
1919 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1920 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1921 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1922 ExAcquireResourceSharedLite(Hive
->FlusherLock
, TRUE
);
1927 CmpUnlockHiveFlusher(IN PCMHIVE Hive
)
1930 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1931 CMP_ASSERT_FLUSH_LOCK(Hive
);
1933 /* Release the lock */
1934 ExReleaseResourceLite(Hive
->FlusherLock
);
1939 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive
)
1942 return !ExIsResourceAcquiredSharedLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
1947 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive
)
1950 return !ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
1955 CmpUnlockRegistry(VOID
)
1958 CMP_ASSERT_REGISTRY_LOCK();
1960 /* Check if we should flush the registry */
1961 if (CmpFlushOnLockRelease
)
1963 /* The registry should be exclusively locked for this */
1964 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
1966 /* Flush the registry */
1967 CmpDoFlushAll(TRUE
);
1968 CmpFlushOnLockRelease
= FALSE
;
1972 /* Lazy flush the registry */
1976 /* Release the lock and leave the critical region */
1977 ExReleaseResourceLite(&CmpRegistryLock
);
1978 KeLeaveCriticalRegion();
1983 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1
,
1986 ULONG Index1
, Index2
;
1989 CMP_ASSERT_REGISTRY_LOCK();
1991 /* Get hash indexes */
1992 Index1
= GET_HASH_INDEX(ConvKey1
);
1993 Index2
= GET_HASH_INDEX(ConvKey2
);
1995 /* See which one is highest */
1996 if (Index1
< Index2
)
1998 /* Grab them in the proper order */
1999 CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2000 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2004 /* Grab the second one first, then the first */
2005 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2006 if (Index1
!= Index2
) CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2012 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1
,
2015 ULONG Index1
, Index2
;
2018 CMP_ASSERT_REGISTRY_LOCK();
2020 /* Get hash indexes */
2021 Index1
= GET_HASH_INDEX(ConvKey1
);
2022 Index2
= GET_HASH_INDEX(ConvKey2
);
2023 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey2
).Owner
== KeGetCurrentThread()) ||
2024 (CmpTestRegistryLockExclusive()));
2026 /* See which one is highest */
2027 if (Index1
< Index2
)
2029 /* Grab them in the proper order */
2030 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2031 (CmpTestRegistryLockExclusive()));
2032 CmpReleaseKcbLockByKey(ConvKey2
);
2033 CmpReleaseKcbLockByKey(ConvKey1
);
2037 /* Release the first one first, then the second */
2038 if (Index1
!= Index2
)
2040 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2041 (CmpTestRegistryLockExclusive()));
2042 CmpReleaseKcbLockByKey(ConvKey1
);
2044 CmpReleaseKcbLockByKey(ConvKey2
);
2050 CmShutdownSystem(VOID
)
2052 PLIST_ENTRY ListEntry
;
2056 /* Kill the workers */
2057 if (!CmFirstTime
) CmpShutdownWorkers();
2059 /* Flush all hives */
2060 CmpLockRegistryExclusive();
2061 CmpDoFlushAll(TRUE
);
2063 /* Close all hive files */
2064 ListEntry
= CmpHiveListHead
.Flink
;
2065 while (ListEntry
!= &CmpHiveListHead
)
2067 Hive
= CONTAINING_RECORD(ListEntry
, CMHIVE
, HiveList
);
2069 for (i
= 0; i
< HFILE_TYPE_MAX
; i
++)
2071 if (Hive
->FileHandles
[i
] != NULL
)
2073 ZwClose(Hive
->FileHandles
[i
]);
2074 Hive
->FileHandles
[i
] = NULL
;
2078 ListEntry
= ListEntry
->Flink
;
2081 CmpUnlockRegistry();
2086 CmpSetVersionData(VOID
)
2089 OBJECT_ATTRIBUTES ObjectAttributes
;
2090 UNICODE_STRING KeyName
;
2091 UNICODE_STRING ValueName
;
2092 UNICODE_STRING ValueData
;
2093 ANSI_STRING TempString
;
2094 HANDLE SoftwareKeyHandle
= NULL
;
2095 HANDLE MicrosoftKeyHandle
= NULL
;
2096 HANDLE WindowsNtKeyHandle
= NULL
;
2097 HANDLE CurrentVersionKeyHandle
= NULL
;
2098 WCHAR Buffer
[128]; // Buffer large enough to contain a full ULONG in decimal representation,
2099 // and the full 'CurrentType' string.
2102 * Open the 'HKLM\Software\Microsoft\Windows NT\CurrentVersion' key
2103 * (create the intermediate subkeys if needed).
2106 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE\\SOFTWARE");
2107 InitializeObjectAttributes(&ObjectAttributes
,
2109 OBJ_CASE_INSENSITIVE
,
2112 Status
= NtCreateKey(&SoftwareKeyHandle
,
2119 if (!NT_SUCCESS(Status
))
2121 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2125 RtlInitUnicodeString(&KeyName
, L
"Microsoft");
2126 InitializeObjectAttributes(&ObjectAttributes
,
2128 OBJ_CASE_INSENSITIVE
,
2131 Status
= NtCreateKey(&MicrosoftKeyHandle
,
2138 if (!NT_SUCCESS(Status
))
2140 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2144 RtlInitUnicodeString(&KeyName
, L
"Windows NT");
2145 InitializeObjectAttributes(&ObjectAttributes
,
2147 OBJ_CASE_INSENSITIVE
,
2150 Status
= NtCreateKey(&WindowsNtKeyHandle
,
2157 if (!NT_SUCCESS(Status
))
2159 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2163 RtlInitUnicodeString(&KeyName
, L
"CurrentVersion");
2164 InitializeObjectAttributes(&ObjectAttributes
,
2166 OBJ_CASE_INSENSITIVE
,
2169 Status
= NtCreateKey(&CurrentVersionKeyHandle
,
2170 KEY_CREATE_SUB_KEY
| KEY_SET_VALUE
,
2176 if (!NT_SUCCESS(Status
))
2178 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2182 /* Set the 'CurrentVersion' value */
2183 RtlInitUnicodeString(&ValueName
, L
"CurrentVersion");
2184 NtSetValueKey(CurrentVersionKeyHandle
,
2188 CmVersionString
.Buffer
,
2189 CmVersionString
.Length
+ sizeof(WCHAR
));
2191 /* Set the 'CurrentBuildNumber' value */
2192 RtlInitUnicodeString(&ValueName
, L
"CurrentBuildNumber");
2193 RtlInitEmptyUnicodeString(&ValueData
, Buffer
, sizeof(Buffer
));
2194 RtlIntegerToUnicodeString(NtBuildNumber
& 0xFFFF, 10, &ValueData
);
2195 NtSetValueKey(CurrentVersionKeyHandle
,
2200 ValueData
.Length
+ sizeof(WCHAR
));
2202 /* Set the 'BuildLab' value */
2203 RtlInitUnicodeString(&ValueName
, L
"BuildLab");
2204 RtlInitAnsiString(&TempString
, NtBuildLab
);
2205 Status
= RtlAnsiStringToUnicodeString(&ValueData
, &TempString
, FALSE
);
2206 if (NT_SUCCESS(Status
))
2208 NtSetValueKey(CurrentVersionKeyHandle
,
2213 ValueData
.Length
+ sizeof(WCHAR
));
2216 /* Set the 'CurrentType' value */
2217 RtlInitUnicodeString(&ValueName
, L
"CurrentType");
2219 swprintf(Buffer
, L
"%s %s",
2232 RtlInitUnicodeString(&ValueData
, Buffer
);
2233 NtSetValueKey(CurrentVersionKeyHandle
,
2238 ValueData
.Length
+ sizeof(WCHAR
));
2240 /* Set the 'CSDVersion' value */
2241 RtlInitUnicodeString(&ValueName
, L
"CSDVersion");
2242 if (CmCSDVersionString
.Length
!= 0)
2244 NtSetValueKey(CurrentVersionKeyHandle
,
2248 CmCSDVersionString
.Buffer
,
2249 CmCSDVersionString
.Length
+ sizeof(WCHAR
));
2253 NtDeleteValueKey(CurrentVersionKeyHandle
, &ValueName
);
2256 /* Set the 'CSDBuildNumber' value */
2257 RtlInitUnicodeString(&ValueName
, L
"CSDBuildNumber");
2258 if (CmNtSpBuildNumber
!= 0)
2260 RtlInitEmptyUnicodeString(&ValueData
, Buffer
, sizeof(Buffer
));
2261 RtlIntegerToUnicodeString(CmNtSpBuildNumber
, 10, &ValueData
);
2262 NtSetValueKey(CurrentVersionKeyHandle
,
2267 ValueData
.Length
+ sizeof(WCHAR
));
2271 NtDeleteValueKey(CurrentVersionKeyHandle
, &ValueName
);
2274 /* Set the 'SystemRoot' value */
2275 RtlInitUnicodeString(&ValueName
, L
"SystemRoot");
2276 NtSetValueKey(CurrentVersionKeyHandle
,
2280 NtSystemRoot
.Buffer
,
2281 NtSystemRoot
.Length
+ sizeof(WCHAR
));
2284 /* Close the keys */
2285 if (CurrentVersionKeyHandle
!= NULL
)
2286 NtClose(CurrentVersionKeyHandle
);
2288 if (WindowsNtKeyHandle
!= NULL
)
2289 NtClose(WindowsNtKeyHandle
);
2291 if (MicrosoftKeyHandle
!= NULL
)
2292 NtClose(MicrosoftKeyHandle
);
2294 if (SoftwareKeyHandle
!= NULL
)
2295 NtClose(SoftwareKeyHandle
);