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 ULONG CmpTraceLevel
= 0;
34 extern LONG CmpFlushStarveWriters
;
35 extern BOOLEAN CmFirstTime
;
37 /* FUNCTIONS ******************************************************************/
42 _In_z_ PWSTR LinkKeyName
,
43 _In_z_ PWSTR TargetKeyName
)
45 OBJECT_ATTRIBUTES ObjectAttributes
;
46 UNICODE_STRING LinkKeyName_U
;
47 HANDLE TargetKeyHandle
;
52 /* Initialize the object attributes */
53 RtlInitUnicodeString(&LinkKeyName_U
, LinkKeyName
);
54 InitializeObjectAttributes(&ObjectAttributes
,
56 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
60 /* Create the link key */
61 Status
= ZwCreateKey(&TargetKeyHandle
,
66 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
68 if (!NT_SUCCESS(Status
))
70 DPRINT1("CM: CmpLinkKeyToHive: couldn't create %S Status = 0x%lx\n",
75 /* Check if the new key was actually created */
76 if (Disposition
!= REG_CREATED_NEW_KEY
)
78 DPRINT1("CM: CmpLinkKeyToHive: %S already exists!\n", LinkKeyName
);
79 ZwClose(TargetKeyHandle
);
83 /* Set the target key name as link target */
84 Status
= ZwSetValueKey(TargetKeyHandle
,
85 &CmSymbolicLinkValueName
,
89 wcslen(TargetKeyName
) * sizeof(WCHAR
));
91 /* Close the link key handle */
92 ObCloseHandle(TargetKeyHandle
, KernelMode
);
94 if (!NT_SUCCESS(Status
))
96 DPRINT1("CM: CmpLinkKeyToHive: couldn't create symbolic link for %S\n",
106 CmpDeleteKeyObject(PVOID DeletedObject
)
108 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)DeletedObject
;
109 PCM_KEY_CONTROL_BLOCK Kcb
;
110 REG_KEY_HANDLE_CLOSE_INFORMATION KeyHandleCloseInfo
;
111 REG_POST_OPERATION_INFORMATION PostOperationInfo
;
115 /* First off, prepare the handle close information callback */
116 PostOperationInfo
.Object
= KeyBody
;
117 KeyHandleCloseInfo
.Object
= KeyBody
;
118 Status
= CmiCallRegisteredCallbacks(RegNtPreKeyHandleClose
,
119 &KeyHandleCloseInfo
);
120 if (!NT_SUCCESS(Status
))
122 /* If we failed, notify the post routine */
123 PostOperationInfo
.Status
= Status
;
124 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
128 /* Acquire hive lock */
131 /* Make sure this is a valid key body */
132 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
135 Kcb
= KeyBody
->KeyControlBlock
;
139 DelistKeyBodyFromKCB(KeyBody
, FALSE
);
141 /* Dereference the KCB */
142 CmpDelayDerefKeyControlBlock(Kcb
);
146 /* Release the registry lock */
149 /* Do the post callback */
150 PostOperationInfo
.Status
= STATUS_SUCCESS
;
151 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
156 CmpCloseKeyObject(IN PEPROCESS Process OPTIONAL
,
158 IN ACCESS_MASK GrantedAccess
,
159 IN ULONG ProcessHandleCount
,
160 IN ULONG SystemHandleCount
)
162 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)Object
;
165 /* Don't do anything if we're not the last handle */
166 if (SystemHandleCount
> 1) return;
168 /* Make sure we're a valid key body */
169 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
171 /* Don't do anything if we don't have a notify block */
172 if (!KeyBody
->NotifyBlock
) return;
174 /* This shouldn't happen yet */
181 CmpQueryKeyName(IN PVOID ObjectBody
,
183 IN OUT POBJECT_NAME_INFORMATION ObjectNameInfo
,
185 OUT PULONG ReturnLength
,
186 IN KPROCESSOR_MODE PreviousMode
)
188 PUNICODE_STRING KeyName
;
190 NTSTATUS Status
= STATUS_SUCCESS
;
191 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)ObjectBody
;
192 PCM_KEY_CONTROL_BLOCK Kcb
= KeyBody
->KeyControlBlock
;
194 /* Acquire hive lock */
197 /* Lock KCB shared */
198 CmpAcquireKcbLockShared(Kcb
);
200 /* Check if it's a deleted block */
203 /* Release the locks */
204 CmpReleaseKcbLock(Kcb
);
207 /* Let the caller know it's deleted */
208 return STATUS_KEY_DELETED
;
212 KeyName
= CmpConstructName(Kcb
);
214 /* Release the locks */
215 CmpReleaseKcbLock(Kcb
);
218 /* Check if we got the name */
219 if (!KeyName
) return STATUS_INSUFFICIENT_RESOURCES
;
221 /* Set the returned length */
222 *ReturnLength
= KeyName
->Length
+ sizeof(OBJECT_NAME_INFORMATION
) + sizeof(WCHAR
);
224 /* Calculate amount of bytes to copy into the buffer */
225 BytesToCopy
= KeyName
->Length
+ sizeof(WCHAR
);
227 /* Check if the provided buffer is too small to fit even anything */
228 if ((Length
<= sizeof(OBJECT_NAME_INFORMATION
)) ||
229 ((Length
< (*ReturnLength
)) && (BytesToCopy
< sizeof(WCHAR
))))
231 /* Free the buffer allocated by CmpConstructName */
232 ExFreePoolWithTag(KeyName
, TAG_CM
);
234 /* Return buffer length failure without writing anything there because nothing fits */
235 return STATUS_INFO_LENGTH_MISMATCH
;
238 /* Check if the provided buffer can be partially written */
239 if (Length
< (*ReturnLength
))
241 /* Yes, indicate so in the return status */
242 Status
= STATUS_INFO_LENGTH_MISMATCH
;
244 /* Calculate amount of bytes which the provided buffer could handle */
245 BytesToCopy
= Length
- sizeof(OBJECT_NAME_INFORMATION
);
248 /* Remove the null termination character from the size */
249 BytesToCopy
-= sizeof(WCHAR
);
251 /* Fill in the result */
254 /* Return data to user */
255 ObjectNameInfo
->Name
.Buffer
= (PWCHAR
)(ObjectNameInfo
+ 1);
256 ObjectNameInfo
->Name
.MaximumLength
= KeyName
->Length
;
257 ObjectNameInfo
->Name
.Length
= KeyName
->Length
;
259 /* Copy string content*/
260 RtlCopyMemory(ObjectNameInfo
->Name
.Buffer
,
264 /* Null terminate it */
265 ObjectNameInfo
->Name
.Buffer
[BytesToCopy
/ sizeof(WCHAR
)] = 0;
267 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
270 Status
= _SEH2_GetExceptionCode();
274 /* Free the buffer allocated by CmpConstructName */
275 ExFreePoolWithTag(KeyName
, TAG_CM
);
283 CmpInitHiveFromFile(IN PCUNICODE_STRING HiveName
,
289 ULONG HiveDisposition
, LogDisposition
;
290 HANDLE FileHandle
= NULL
, LogHandle
= NULL
;
292 ULONG Operation
, FileType
;
299 /* Open or create the hive files */
300 Status
= CmpOpenHiveFiles(HiveName
,
310 if (!NT_SUCCESS(Status
)) return Status
;
312 /* Check if we have a log handle */
313 FileType
= (LogHandle
) ? HFILE_TYPE_LOG
: HFILE_TYPE_PRIMARY
;
315 /* Check if we created or opened the hive */
316 if (HiveDisposition
== FILE_CREATED
)
318 /* Do a create operation */
319 Operation
= HINIT_CREATE
;
324 /* Open it as a file */
325 Operation
= HINIT_FILE
;
329 /* Check if we're sharing hives */
330 if (CmpShareSystemHives
)
332 /* Then force using the primary hive */
333 FileType
= HFILE_TYPE_PRIMARY
;
336 /* Get rid of the log handle */
342 /* Check if we're too late */
343 if (HvShutdownComplete
)
347 if (LogHandle
) ZwClose(LogHandle
);
348 return STATUS_TOO_LATE
;
351 /* Initialize the hive */
352 Status
= CmpInitializeHive((PCMHIVE
*)&NewHive
,
362 if (!NT_SUCCESS(Status
))
366 if (LogHandle
) ZwClose(LogHandle
);
370 /* Success, return hive */
373 /* HACK: ROS: Init root key cell and prepare the hive */
374 if (Operation
== HINIT_CREATE
) CmCreateRootNode(&NewHive
->Hive
, L
"");
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
->MaximumLength
;
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
= ZwSetValueKey(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
= ZwSetValueKey(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 CmpCreateControlSet(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
453 UNICODE_STRING ConfigName
= RTL_CONSTANT_STRING(L
"Control\\IDConfigDB");
454 UNICODE_STRING SelectName
=
455 RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\Select");
456 UNICODE_STRING KeyName
;
457 OBJECT_ATTRIBUTES ObjectAttributes
;
458 CHAR ValueInfoBuffer
[128];
459 PKEY_VALUE_FULL_INFORMATION ValueInfo
;
461 WCHAR UnicodeBuffer
[128];
462 HANDLE SelectHandle
, KeyHandle
, ConfigHandle
= NULL
, ProfileHandle
= NULL
;
463 HANDLE ParentHandle
= NULL
;
464 ULONG ControlSet
, HwProfile
;
465 ANSI_STRING TempString
;
467 ULONG ResultLength
, Disposition
;
468 PLOADER_PARAMETER_EXTENSION LoaderExtension
;
471 /* Open the select key */
472 InitializeObjectAttributes(&ObjectAttributes
,
474 OBJ_CASE_INSENSITIVE
,
477 Status
= ZwOpenKey(&SelectHandle
, KEY_READ
, &ObjectAttributes
);
478 if (!NT_SUCCESS(Status
))
480 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
481 if (!LoaderBlock
->RegistryBase
)
483 /* Build the ControlSet001 key */
484 RtlInitUnicodeString(&KeyName
,
485 L
"\\Registry\\Machine\\System\\ControlSet001");
486 InitializeObjectAttributes(&ObjectAttributes
,
488 OBJ_CASE_INSENSITIVE
,
491 Status
= ZwCreateKey(&KeyHandle
,
498 if (!NT_SUCCESS(Status
))
501 /* We 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
= ZwCreateKey(&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
= ZwSetValueKey(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
= ZwSetValueKey(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 CmpLinkKeyToHive(L
"\\Registry\\User\\S-1-5-18",
1475 L
"\\Registry\\User\\.Default");
1483 OBJECT_ATTRIBUTES ObjectAttributes
;
1484 UNICODE_STRING KeyName
;
1487 PCMHIVE HardwareHive
;
1488 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1491 /* Check if this is PE-boot */
1492 if (InitIsWinPEMode
)
1494 /* Set registry to PE mode */
1495 CmpMiniNTBoot
= TRUE
;
1496 CmpShareSystemHives
= TRUE
;
1499 /* Initialize the hive list and lock */
1500 InitializeListHead(&CmpHiveListHead
);
1501 ExInitializePushLock(&CmpHiveListHeadLock
);
1502 ExInitializePushLock(&CmpLoadHiveLock
);
1504 /* Initialize registry lock */
1505 ExInitializeResourceLite(&CmpRegistryLock
);
1507 /* Initialize the cache */
1508 CmpInitializeCache();
1510 /* Initialize allocation and delayed dereferencing */
1511 CmpInitCmPrivateAlloc();
1512 CmpInitCmPrivateDelayAlloc();
1513 CmpInitDelayDerefKCBEngine();
1515 /* Initialize callbacks */
1518 /* Initialize self healing */
1519 KeInitializeGuardedMutex(&CmpSelfHealQueueLock
);
1520 InitializeListHead(&CmpSelfHealQueueListHead
);
1522 /* Save the current process and lock the registry */
1523 CmpSystemProcess
= PsGetCurrentProcess();
1525 /* Create the key object types */
1526 Status
= CmpCreateObjectTypes();
1527 if (!NT_SUCCESS(Status
))
1530 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 1, Status
, 0);
1533 /* Build the master hive */
1534 Status
= CmpInitializeHive((PCMHIVE
*)&CmiVolatileHive
,
1544 if (!NT_SUCCESS(Status
))
1547 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 2, Status
, 0);
1550 /* Create the \REGISTRY key node */
1551 if (!CmpCreateRegistryRoot())
1554 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 3, 0, 0);
1557 /* Create the default security descriptor */
1558 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1560 /* Create '\Registry\Machine' key. */
1561 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE");
1562 InitializeObjectAttributes(&ObjectAttributes
,
1564 OBJ_CASE_INSENSITIVE
,
1566 SecurityDescriptor
);
1567 Status
= NtCreateKey(&KeyHandle
,
1568 KEY_READ
| KEY_WRITE
,
1574 if (!NT_SUCCESS(Status
))
1577 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 5, Status
, 0);
1580 /* Close the handle */
1583 /* Create '\Registry\User' key. */
1584 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\USER");
1585 InitializeObjectAttributes(&ObjectAttributes
,
1587 OBJ_CASE_INSENSITIVE
,
1589 SecurityDescriptor
);
1590 Status
= NtCreateKey(&KeyHandle
,
1591 KEY_READ
| KEY_WRITE
,
1597 if (!NT_SUCCESS(Status
))
1600 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 6, Status
, 0);
1603 /* Close the handle */
1606 /* Initialize the system hive */
1607 if (!CmpInitializeSystemHive(KeLoaderBlock
))
1610 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 7, 0, 0);
1613 /* Create the 'CurrentControlSet' link. */
1614 Status
= CmpCreateControlSet(KeLoaderBlock
);
1615 if (!NT_SUCCESS(Status
))
1618 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 8, Status
, 0);
1621 /* Create the hardware hive */
1622 Status
= CmpInitializeHive((PCMHIVE
*)&HardwareHive
,
1632 if (!NT_SUCCESS(Status
))
1635 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 11, Status
, 0);
1638 /* Add the hive to the hive list */
1639 CmpMachineHiveList
[0].CmHive
= (PCMHIVE
)HardwareHive
;
1641 /* Attach it to the machine key */
1642 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\HARDWARE");
1643 Status
= CmpLinkHiveToMaster(&KeyName
,
1645 (PCMHIVE
)HardwareHive
,
1647 SecurityDescriptor
);
1648 if (!NT_SUCCESS(Status
))
1651 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 12, Status
, 0);
1654 /* Add to HiveList key */
1655 CmpAddToHiveFileList(HardwareHive
);
1657 /* Free the security descriptor */
1658 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1660 /* Fill out the Hardware key with the ARC Data from the Loader */
1661 Status
= CmpInitializeHardwareConfiguration(KeLoaderBlock
);
1662 if (!NT_SUCCESS(Status
))
1665 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 13, Status
, 0);
1668 /* Initialize machine-dependent information into the registry */
1669 Status
= CmpInitializeMachineDependentConfiguration(KeLoaderBlock
);
1670 if (!NT_SUCCESS(Status
))
1673 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 14, Status
, 0);
1676 /* Initialize volatile registry settings */
1677 Status
= CmpSetSystemValues(KeLoaderBlock
);
1678 if (!NT_SUCCESS(Status
))
1681 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 15, Status
, 0);
1684 /* Free the load options */
1685 ExFreePoolWithTag(CmpLoadOptions
.Buffer
, TAG_CM
);
1687 /* If we got here, all went well */
1694 CmpFreeDriverList(IN PHHIVE Hive
,
1695 IN PLIST_ENTRY DriverList
)
1697 PLIST_ENTRY NextEntry
, OldEntry
;
1698 PBOOT_DRIVER_NODE DriverNode
;
1701 /* Parse the current list */
1702 NextEntry
= DriverList
->Flink
;
1703 while (NextEntry
!= DriverList
)
1705 /* Get the driver node */
1706 DriverNode
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_NODE
, ListEntry
.Link
);
1708 /* Get the next entry now, since we're going to free it later */
1709 OldEntry
= NextEntry
;
1710 NextEntry
= NextEntry
->Flink
;
1712 /* Was there a name? */
1713 if (DriverNode
->Name
.Buffer
)
1716 CmpFree(DriverNode
->Name
.Buffer
, DriverNode
->Name
.Length
);
1719 /* Was there a registry path? */
1720 if (DriverNode
->ListEntry
.RegistryPath
.Buffer
)
1723 CmpFree(DriverNode
->ListEntry
.RegistryPath
.Buffer
,
1724 DriverNode
->ListEntry
.RegistryPath
.MaximumLength
);
1727 /* Was there a file path? */
1728 if (DriverNode
->ListEntry
.FilePath
.Buffer
)
1731 CmpFree(DriverNode
->ListEntry
.FilePath
.Buffer
,
1732 DriverNode
->ListEntry
.FilePath
.MaximumLength
);
1735 /* Now free the node, and move on */
1736 CmpFree(OldEntry
, sizeof(BOOT_DRIVER_NODE
));
1743 CmGetSystemDriverList(VOID
)
1745 LIST_ENTRY DriverList
;
1746 OBJECT_ATTRIBUTES ObjectAttributes
;
1748 PCM_KEY_BODY KeyBody
;
1750 HCELL_INDEX RootCell
, ControlCell
;
1752 UNICODE_STRING KeyName
;
1753 PLIST_ENTRY NextEntry
;
1755 PUNICODE_STRING
* ServicePath
= NULL
;
1756 BOOLEAN Success
, AutoSelect
;
1757 PBOOT_DRIVER_LIST_ENTRY DriverEntry
;
1760 /* Initialize the driver list */
1761 InitializeListHead(&DriverList
);
1763 /* Open the system hive key */
1764 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\System");
1765 InitializeObjectAttributes(&ObjectAttributes
,
1767 OBJ_CASE_INSENSITIVE
,
1770 Status
= NtOpenKey(&KeyHandle
, KEY_READ
, &ObjectAttributes
);
1771 if (!NT_SUCCESS(Status
)) return NULL
;
1773 /* Reference the key object to get the root hive/cell to access directly */
1774 Status
= ObReferenceObjectByHandle(KeyHandle
,
1780 if (!NT_SUCCESS(Status
))
1787 /* Do all this under the registry lock */
1788 CmpLockRegistryExclusive();
1790 /* Get the hive and key cell */
1791 Hive
= KeyBody
->KeyControlBlock
->KeyHive
;
1792 RootCell
= KeyBody
->KeyControlBlock
->KeyCell
;
1794 /* Open the current control set key */
1795 RtlInitUnicodeString(&KeyName
, L
"Current");
1796 ControlCell
= CmpFindControlSet(Hive
, RootCell
, &KeyName
, &AutoSelect
);
1797 if (ControlCell
== HCELL_NIL
) goto EndPath
;
1799 /* Find all system drivers */
1800 Success
= CmpFindDrivers(Hive
, ControlCell
, SystemLoad
, NULL
, &DriverList
);
1801 if (!Success
) goto EndPath
;
1803 /* Sort by group/tag */
1804 if (!CmpSortDriverList(Hive
, ControlCell
, &DriverList
)) goto EndPath
;
1806 /* Remove circular dependencies (cycles) and sort */
1807 if (!CmpResolveDriverDependencies(&DriverList
)) goto EndPath
;
1809 /* Loop the list to count drivers */
1810 for (i
= 0, NextEntry
= DriverList
.Flink
;
1811 NextEntry
!= &DriverList
;
1812 i
++, NextEntry
= NextEntry
->Flink
);
1814 /* Allocate the array */
1815 ServicePath
= ExAllocatePool(NonPagedPool
, (i
+ 1) * sizeof(PUNICODE_STRING
));
1816 if (!ServicePath
) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 2, 1, 0, 0);
1818 /* Loop the driver list */
1819 for (i
= 0, NextEntry
= DriverList
.Flink
;
1820 NextEntry
!= &DriverList
;
1821 i
++, NextEntry
= NextEntry
->Flink
)
1824 DriverEntry
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_LIST_ENTRY
, Link
);
1826 /* Allocate the path for the caller and duplicate the registry path */
1827 ServicePath
[i
] = ExAllocatePool(NonPagedPool
, sizeof(UNICODE_STRING
));
1828 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1829 &DriverEntry
->RegistryPath
,
1833 /* Terminate the list */
1834 ServicePath
[i
] = NULL
;
1837 /* Free the driver list if we had one */
1838 if (!IsListEmpty(&DriverList
)) CmpFreeDriverList(Hive
, &DriverList
);
1840 /* Unlock the registry */
1841 CmpUnlockRegistry();
1843 /* Close the key handle and dereference the object, then return the path */
1844 ObDereferenceObject(KeyBody
);
1851 CmpLockRegistryExclusive(VOID
)
1853 /* Enter a critical region and lock the registry */
1854 KeEnterCriticalRegion();
1855 ExAcquireResourceExclusiveLite(&CmpRegistryLock
, TRUE
);
1858 ASSERT(CmpFlushStarveWriters
== 0);
1859 RtlGetCallersAddress(&CmpRegistryLockCaller
, &CmpRegistryLockCallerCaller
);
1864 CmpLockRegistry(VOID
)
1866 /* Enter a critical region */
1867 KeEnterCriticalRegion();
1869 /* Check if we have to starve writers */
1870 if (CmpFlushStarveWriters
)
1872 /* Starve exlusive waiters */
1873 ExAcquireSharedStarveExclusive(&CmpRegistryLock
, TRUE
);
1877 /* Just grab the lock */
1878 ExAcquireResourceSharedLite(&CmpRegistryLock
, TRUE
);
1884 CmpTestRegistryLock(VOID
)
1887 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1892 CmpTestRegistryLockExclusive(VOID
)
1895 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1900 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive
)
1902 /* Lock the flusher. We should already be in a critical section */
1903 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1904 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1905 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1906 ExAcquireResourceExclusiveLite(Hive
->FlusherLock
, TRUE
);
1911 CmpLockHiveFlusherShared(IN PCMHIVE Hive
)
1913 /* Lock the flusher. We should already be in a critical section */
1914 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1915 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1916 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1917 ExAcquireResourceSharedLite(Hive
->FlusherLock
, TRUE
);
1922 CmpUnlockHiveFlusher(IN PCMHIVE Hive
)
1925 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1926 CMP_ASSERT_FLUSH_LOCK(Hive
);
1928 /* Release the lock */
1929 ExReleaseResourceLite(Hive
->FlusherLock
);
1934 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive
)
1937 return !ExIsResourceAcquiredSharedLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
1942 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive
)
1945 return !ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
1950 CmpUnlockRegistry(VOID
)
1953 CMP_ASSERT_REGISTRY_LOCK();
1955 /* Check if we should flush the registry */
1956 if (CmpFlushOnLockRelease
)
1958 /* The registry should be exclusively locked for this */
1959 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
1961 /* Flush the registry */
1962 CmpDoFlushAll(TRUE
);
1963 CmpFlushOnLockRelease
= FALSE
;
1967 /* Lazy flush the registry */
1971 /* Release the lock and leave the critical region */
1972 ExReleaseResourceLite(&CmpRegistryLock
);
1973 KeLeaveCriticalRegion();
1978 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1
,
1981 ULONG Index1
, Index2
;
1984 CMP_ASSERT_REGISTRY_LOCK();
1986 /* Get hash indexes */
1987 Index1
= GET_HASH_INDEX(ConvKey1
);
1988 Index2
= GET_HASH_INDEX(ConvKey2
);
1990 /* See which one is highest */
1991 if (Index1
< Index2
)
1993 /* Grab them in the proper order */
1994 CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
1995 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
1999 /* Grab the second one first, then the first */
2000 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2001 if (Index1
!= Index2
) CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2007 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1
,
2010 ULONG Index1
, Index2
;
2013 CMP_ASSERT_REGISTRY_LOCK();
2015 /* Get hash indexes */
2016 Index1
= GET_HASH_INDEX(ConvKey1
);
2017 Index2
= GET_HASH_INDEX(ConvKey2
);
2018 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey2
).Owner
== KeGetCurrentThread()) ||
2019 (CmpTestRegistryLockExclusive()));
2021 /* See which one is highest */
2022 if (Index1
< Index2
)
2024 /* Grab them in the proper order */
2025 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2026 (CmpTestRegistryLockExclusive()));
2027 CmpReleaseKcbLockByKey(ConvKey2
);
2028 CmpReleaseKcbLockByKey(ConvKey1
);
2032 /* Release the first one first, then the second */
2033 if (Index1
!= Index2
)
2035 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2036 (CmpTestRegistryLockExclusive()));
2037 CmpReleaseKcbLockByKey(ConvKey1
);
2039 CmpReleaseKcbLockByKey(ConvKey2
);
2045 CmShutdownSystem(VOID
)
2047 /* Kill the workers */
2048 if (!CmFirstTime
) CmpShutdownWorkers();
2050 /* Flush all hives */
2051 CmpLockRegistryExclusive();
2052 CmpDoFlushAll(TRUE
);
2053 CmpUnlockRegistry();
2058 CmpSetVersionData(VOID
)
2060 OBJECT_ATTRIBUTES ObjectAttributes
;
2061 UNICODE_STRING KeyName
;
2062 UNICODE_STRING ValueName
;
2063 UNICODE_STRING ValueData
;
2064 HANDLE SoftwareKeyHandle
= NULL
;
2065 HANDLE MicrosoftKeyHandle
= NULL
;
2066 HANDLE WindowsNtKeyHandle
= NULL
;
2067 HANDLE CurrentVersionKeyHandle
= NULL
;
2071 /* Open the 'CurrentVersion' key */
2072 RtlInitUnicodeString(&KeyName
,
2073 L
"\\REGISTRY\\MACHINE\\SOFTWARE");
2075 InitializeObjectAttributes(&ObjectAttributes
,
2077 OBJ_CASE_INSENSITIVE
,
2081 Status
= NtCreateKey(&SoftwareKeyHandle
,
2088 if (!NT_SUCCESS(Status
))
2090 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2094 /* Open the 'CurrentVersion' key */
2095 RtlInitUnicodeString(&KeyName
,
2098 InitializeObjectAttributes(&ObjectAttributes
,
2100 OBJ_CASE_INSENSITIVE
,
2104 Status
= NtCreateKey(&MicrosoftKeyHandle
,
2111 if (!NT_SUCCESS(Status
))
2113 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2117 /* Open the 'CurrentVersion' key */
2118 RtlInitUnicodeString(&KeyName
,
2121 InitializeObjectAttributes(&ObjectAttributes
,
2123 OBJ_CASE_INSENSITIVE
,
2127 Status
= NtCreateKey(&WindowsNtKeyHandle
,
2134 if (!NT_SUCCESS(Status
))
2136 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2140 /* Open the 'CurrentVersion' key */
2141 RtlInitUnicodeString(&KeyName
,
2144 InitializeObjectAttributes(&ObjectAttributes
,
2146 OBJ_CASE_INSENSITIVE
,
2150 Status
= NtCreateKey(&CurrentVersionKeyHandle
,
2151 KEY_CREATE_SUB_KEY
| KEY_SET_VALUE
,
2157 if (!NT_SUCCESS(Status
))
2159 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2163 /* Set the 'CurrentType' value */
2164 RtlInitUnicodeString(&ValueName
,
2168 wcscpy(Buffer
, L
"Multiprocessor");
2170 wcscpy(Buffer
, L
"Uniprocessor");
2173 wcscat(Buffer
, L
" ");
2176 wcscat(Buffer
, L
"Checked");
2178 wcscat(Buffer
, L
"Free");
2181 RtlInitUnicodeString(&ValueData
,
2184 ZwSetValueKey(CurrentVersionKeyHandle
,
2189 ValueData
.Length
+ sizeof(WCHAR
));
2192 /* Close the keys */
2193 if (CurrentVersionKeyHandle
!= NULL
)
2194 NtClose(CurrentVersionKeyHandle
);
2196 if (WindowsNtKeyHandle
!= NULL
)
2197 NtClose(WindowsNtKeyHandle
);
2199 if (MicrosoftKeyHandle
!= NULL
)
2200 NtClose(MicrosoftKeyHandle
);
2202 if (SoftwareKeyHandle
!= NULL
)
2203 NtClose(SoftwareKeyHandle
);