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
== '20yk')
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
== '20yk')
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 /* 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
= NtSetValueKey(KeyHandle
,
423 CmpLoadOptions
.Buffer
,
424 CmpLoadOptions
.Length
);
425 if (!NT_SUCCESS(Status
)) goto Quickie
;
427 /* Setup value name for system boot device in ARC format */
428 RtlInitUnicodeString(&KeyName
, L
"SystemBootDevice");
429 RtlCreateUnicodeStringFromAsciiz(&ValueName
, LoaderBlock
->ArcBootDeviceName
);
430 Status
= NtSetValueKey(KeyHandle
,
438 /* Free the buffers */
439 RtlFreeUnicodeString(&ValueName
);
441 /* Close the key and return */
442 if (KeyHandle
) NtClose(KeyHandle
);
444 /* Return the status */
445 return (ExpInTextModeSetup
? STATUS_SUCCESS
: Status
);
451 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
= NtOpenKey(&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
= NtCreateKey(&KeyHandle
,
498 if (!NT_SUCCESS(Status
)) return Status
;
500 /* Don't need the handle */
503 /* Use hard-coded setting */
508 /* Fail for real boots */
512 /* Open the current value */
513 RtlInitUnicodeString(&KeyName
, L
"Current");
514 Status
= NtQueryValueKey(SelectHandle
,
516 KeyValueFullInformation
,
518 sizeof(ValueInfoBuffer
),
520 NtClose(SelectHandle
);
521 if (!NT_SUCCESS(Status
)) return Status
;
523 /* Get the actual value pointer, and get the control set ID */
524 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
525 ControlSet
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
527 /* Create the current control set key */
529 RtlInitUnicodeString(&KeyName
,
530 L
"\\Registry\\Machine\\System\\CurrentControlSet");
531 InitializeObjectAttributes(&ObjectAttributes
,
533 OBJ_CASE_INSENSITIVE
,
536 Status
= NtCreateKey(&KeyHandle
,
541 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
543 if (!NT_SUCCESS(Status
)) return Status
;
546 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
548 /* Initialize the symbolic link name */
550 "\\Registry\\Machine\\System\\ControlSet%03ld",
552 RtlInitAnsiString(&TempString
, Buffer
);
554 /* Create a Unicode string out of it */
555 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
556 KeyName
.Buffer
= UnicodeBuffer
;
557 Status
= RtlAnsiStringToUnicodeString(&KeyName
, &TempString
, FALSE
);
560 Status
= NtSetValueKey(KeyHandle
,
561 &CmSymbolicLinkValueName
,
566 if (!NT_SUCCESS(Status
)) return Status
;
568 /* Get the configuration database key */
569 InitializeObjectAttributes(&ObjectAttributes
,
571 OBJ_CASE_INSENSITIVE
,
574 Status
= NtOpenKey(&ConfigHandle
, KEY_READ
, &ObjectAttributes
);
577 /* Check if we don't have one */
578 if (!NT_SUCCESS(Status
))
580 /* Cleanup and exit */
585 /* Now get the current config */
586 RtlInitUnicodeString(&KeyName
, L
"CurrentConfig");
587 Status
= NtQueryValueKey(ConfigHandle
,
589 KeyValueFullInformation
,
591 sizeof(ValueInfoBuffer
),
594 /* Set pointer to buffer */
595 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
597 /* Check if we failed or got a non DWORD-value */
598 if (!(NT_SUCCESS(Status
)) || (ValueInfo
->Type
!= REG_DWORD
)) goto Cleanup
;
600 /* Get the hadware profile */
601 HwProfile
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
603 /* Open the hardware profile key */
604 RtlInitUnicodeString(&KeyName
,
605 L
"\\Registry\\Machine\\System\\CurrentControlSet"
606 L
"\\Hardware Profiles");
607 InitializeObjectAttributes(&ObjectAttributes
,
609 OBJ_CASE_INSENSITIVE
,
612 Status
= NtOpenKey(&ParentHandle
, KEY_READ
, &ObjectAttributes
);
613 if (!NT_SUCCESS(Status
))
615 /* Exit and clean up */
620 /* Build the profile name */
621 sprintf(Buffer
, "%04ld", HwProfile
);
622 RtlInitAnsiString(&TempString
, Buffer
);
624 /* Convert it to Unicode */
625 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
626 KeyName
.Buffer
= UnicodeBuffer
;
627 Status
= RtlAnsiStringToUnicodeString(&KeyName
,
630 ASSERT(Status
== STATUS_SUCCESS
);
632 /* Open the associated key */
633 InitializeObjectAttributes(&ObjectAttributes
,
635 OBJ_CASE_INSENSITIVE
,
638 Status
= NtOpenKey(&ProfileHandle
,
639 KEY_READ
| KEY_WRITE
,
641 if (!NT_SUCCESS (Status
))
643 /* Cleanup and exit */
648 /* Check if we have a loader block extension */
649 LoaderExtension
= LoaderBlock
->Extension
;
652 DPRINT("ReactOS doesn't support NTLDR Profiles yet!\n");
655 /* Create the current hardware profile key */
656 RtlInitUnicodeString(&KeyName
,
657 L
"\\Registry\\Machine\\System\\CurrentControlSet\\"
658 L
"Hardware Profiles\\Current");
659 InitializeObjectAttributes(&ObjectAttributes
,
661 OBJ_CASE_INSENSITIVE
,
664 Status
= NtCreateKey(&KeyHandle
,
669 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
671 if (NT_SUCCESS(Status
))
674 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
676 /* Create the profile name */
678 "\\Registry\\Machine\\System\\CurrentControlSet\\"
679 "Hardware Profiles\\%04ld",
681 RtlInitAnsiString(&TempString
, Buffer
);
683 /* Convert it to Unicode */
684 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
685 KeyName
.Buffer
= UnicodeBuffer
;
686 Status
= RtlAnsiStringToUnicodeString(&KeyName
,
689 ASSERT(STATUS_SUCCESS
== Status
);
692 Status
= NtSetValueKey(KeyHandle
,
693 &CmSymbolicLinkValueName
,
701 /* Close every opened handle */
703 if (ConfigHandle
) NtClose(ConfigHandle
);
704 if (ProfileHandle
) NtClose(ProfileHandle
);
705 if (ParentHandle
) NtClose(ParentHandle
);
708 return STATUS_SUCCESS
;
713 CmpLinkHiveToMaster(IN PUNICODE_STRING LinkName
,
714 IN HANDLE RootDirectory
,
715 IN PCMHIVE RegistryHive
,
717 IN PSECURITY_DESCRIPTOR SecurityDescriptor
)
719 OBJECT_ATTRIBUTES ObjectAttributes
;
721 CM_PARSE_CONTEXT ParseContext
= {0};
723 PCM_KEY_BODY KeyBody
;
726 /* Setup the object attributes */
727 InitializeObjectAttributes(&ObjectAttributes
,
729 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
733 /* Setup the parse context */
734 ParseContext
.CreateLink
= TRUE
;
735 ParseContext
.CreateOperation
= TRUE
;
736 ParseContext
.ChildHive
.KeyHive
= &RegistryHive
->Hive
;
738 /* Check if we have a root keycell or if we need to create it */
742 ParseContext
.ChildHive
.KeyCell
= HCELL_NIL
;
747 ParseContext
.ChildHive
.KeyCell
= RegistryHive
->Hive
.BaseBlock
->RootCell
;
750 /* Create the link node */
751 Status
= ObOpenObjectByName(&ObjectAttributes
,
755 KEY_READ
| KEY_WRITE
,
756 (PVOID
)&ParseContext
,
758 if (!NT_SUCCESS(Status
)) return Status
;
760 /* Mark the hive as clean */
761 RegistryHive
->Hive
.DirtyFlag
= FALSE
;
763 /* ReactOS Hack: Keep alive */
764 Status
= ObReferenceObjectByHandle(KeyHandle
,
770 ASSERT(NT_SUCCESS(Status
));
772 /* Close the extra handle */
774 return STATUS_SUCCESS
;
780 CmpInitializeSystemHive(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
783 ANSI_STRING LoadString
;
788 UNICODE_STRING KeyName
;
789 PCMHIVE SystemHive
= NULL
;
790 UNICODE_STRING HiveName
= RTL_CONSTANT_STRING(L
"SYSTEM");
791 PSECURITY_DESCRIPTOR SecurityDescriptor
;
794 /* Setup the ansi string */
795 RtlInitAnsiString(&LoadString
, LoaderBlock
->LoadOptions
);
797 /* Allocate the unicode buffer */
798 Length
= LoadString
.Length
* sizeof(WCHAR
) + sizeof(UNICODE_NULL
);
799 Buffer
= ExAllocatePoolWithTag(PagedPool
, Length
, TAG_CM
);
803 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 3, 1, (ULONG_PTR
)LoaderBlock
, 0);
806 /* Setup the unicode string */
807 RtlInitEmptyUnicodeString(&CmpLoadOptions
, Buffer
, (USHORT
)Length
);
809 /* Add the load options and null-terminate */
810 RtlAnsiStringToUnicodeString(&CmpLoadOptions
, &LoadString
, FALSE
);
811 CmpLoadOptions
.Buffer
[LoadString
.Length
] = UNICODE_NULL
;
812 CmpLoadOptions
.Length
+= sizeof(WCHAR
);
814 /* Get the System Hive base address */
815 HiveBase
= LoaderBlock
->RegistryBase
;
819 Status
= CmpInitializeHive((PCMHIVE
*)&SystemHive
,
829 if (!NT_SUCCESS(Status
)) return FALSE
;
831 /* Set the hive filename */
832 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
833 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
835 /* We imported, no need to create a new hive */
838 /* Manually set the hive as volatile, if in Live CD mode */
839 if (CmpShareSystemHives
) SystemHive
->Hive
.HiveFlags
= HIVE_VOLATILE
;
844 Status
= CmpInitializeHive(&SystemHive
,
854 if (!NT_SUCCESS(Status
)) return FALSE
;
856 /* Set the hive filename */
857 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
858 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
860 /* Tell CmpLinkHiveToMaster to allocate a hive */
864 /* Save the boot type */
865 CmpBootType
= SystemHive
->Hive
.BaseBlock
->BootType
;
867 /* Are we in self-healing mode? */
870 /* Disable self-healing internally and check if boot type wanted it */
874 /* We're disabled, so bugcheck */
875 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
,
878 (ULONG_PTR
)SystemHive
,
883 /* Create the default security descriptor */
884 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
886 /* Attach it to the system key */
887 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\SYSTEM");
888 Status
= CmpLinkHiveToMaster(&KeyName
,
894 /* Free the security descriptor */
895 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
896 if (!NT_SUCCESS(Status
)) return FALSE
;
898 /* Add the hive to the hive list */
899 CmpMachineHiveList
[3].CmHive
= (PCMHIVE
)SystemHive
;
908 CmpCreateObjectTypes(VOID
)
910 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer
;
912 GENERIC_MAPPING CmpKeyMapping
= {KEY_READ
,
918 /* Initialize the Key object type */
919 RtlZeroMemory(&ObjectTypeInitializer
, sizeof(ObjectTypeInitializer
));
920 RtlInitUnicodeString(&Name
, L
"Key");
921 ObjectTypeInitializer
.Length
= sizeof(ObjectTypeInitializer
);
922 ObjectTypeInitializer
.DefaultPagedPoolCharge
= sizeof(CM_KEY_BODY
);
923 ObjectTypeInitializer
.GenericMapping
= CmpKeyMapping
;
924 ObjectTypeInitializer
.PoolType
= PagedPool
;
925 ObjectTypeInitializer
.ValidAccessMask
= KEY_ALL_ACCESS
;
926 ObjectTypeInitializer
.UseDefaultObject
= TRUE
;
927 ObjectTypeInitializer
.DeleteProcedure
= CmpDeleteKeyObject
;
928 ObjectTypeInitializer
.ParseProcedure
= CmpParseKey
;
929 ObjectTypeInitializer
.SecurityProcedure
= CmpSecurityMethod
;
930 ObjectTypeInitializer
.QueryNameProcedure
= CmpQueryKeyName
;
931 ObjectTypeInitializer
.CloseProcedure
= CmpCloseKeyObject
;
932 ObjectTypeInitializer
.SecurityRequired
= TRUE
;
933 ObjectTypeInitializer
.InvalidAttributes
= OBJ_EXCLUSIVE
| OBJ_PERMANENT
;
936 return ObCreateObjectType(&Name
, &ObjectTypeInitializer
, NULL
, &CmpKeyObjectType
);
942 CmpCreateRootNode(IN PHHIVE Hive
,
944 OUT PHCELL_INDEX Index
)
946 UNICODE_STRING KeyName
;
947 PCM_KEY_NODE KeyCell
;
948 LARGE_INTEGER SystemTime
;
951 /* Initialize the node name and allocate it */
952 RtlInitUnicodeString(&KeyName
, Name
);
953 *Index
= HvAllocateCell(Hive
,
954 FIELD_OFFSET(CM_KEY_NODE
, Name
) +
955 CmpNameSize(Hive
, &KeyName
),
958 if (*Index
== HCELL_NIL
) return FALSE
;
960 /* Set the cell index and get the data */
961 Hive
->BaseBlock
->RootCell
= *Index
;
962 KeyCell
= (PCM_KEY_NODE
)HvGetCell(Hive
, *Index
);
963 if (!KeyCell
) return FALSE
;
966 KeyCell
->Signature
= (USHORT
)CM_KEY_NODE_SIGNATURE
;
967 KeyCell
->Flags
= KEY_HIVE_ENTRY
| KEY_NO_DELETE
;
968 KeQuerySystemTime(&SystemTime
);
969 KeyCell
->LastWriteTime
= SystemTime
;
970 KeyCell
->Parent
= HCELL_NIL
;
971 KeyCell
->SubKeyCounts
[Stable
] = 0;
972 KeyCell
->SubKeyCounts
[Volatile
] = 0;
973 KeyCell
->SubKeyLists
[Stable
] = HCELL_NIL
;
974 KeyCell
->SubKeyLists
[Volatile
] = HCELL_NIL
;
975 KeyCell
->ValueList
.Count
= 0;
976 KeyCell
->ValueList
.List
= HCELL_NIL
;
977 KeyCell
->Security
= HCELL_NIL
;
978 KeyCell
->Class
= HCELL_NIL
;
979 KeyCell
->ClassLength
= 0;
980 KeyCell
->MaxNameLen
= 0;
981 KeyCell
->MaxClassLen
= 0;
982 KeyCell
->MaxValueNameLen
= 0;
983 KeyCell
->MaxValueDataLen
= 0;
985 /* Copy the name (this will also set the length) */
986 KeyCell
->NameLength
= CmpCopyName(Hive
, (PWCHAR
)KeyCell
->Name
, &KeyName
);
988 /* Check if the name was compressed */
989 if (KeyCell
->NameLength
< KeyName
.Length
)
992 KeyCell
->Flags
|= KEY_COMP_NAME
;
996 HvReleaseCell(Hive
, *Index
);
1003 CmpCreateRegistryRoot(VOID
)
1005 UNICODE_STRING KeyName
;
1006 OBJECT_ATTRIBUTES ObjectAttributes
;
1007 PCM_KEY_BODY RootKey
;
1008 HCELL_INDEX RootIndex
;
1010 PCM_KEY_NODE KeyCell
;
1011 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1012 PCM_KEY_CONTROL_BLOCK Kcb
;
1015 /* Setup the root node */
1016 if (!CmpCreateRootNode(&CmiVolatileHive
->Hive
, L
"REGISTRY", &RootIndex
))
1022 /* Create '\Registry' key. */
1023 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1024 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1025 InitializeObjectAttributes(&ObjectAttributes
,
1027 OBJ_CASE_INSENSITIVE
,
1030 Status
= ObCreateObject(KernelMode
,
1035 sizeof(CM_KEY_BODY
),
1039 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1040 if (!NT_SUCCESS(Status
)) return FALSE
;
1042 /* Sanity check, and get the key cell */
1043 ASSERT((&CmiVolatileHive
->Hive
)->ReleaseCellRoutine
== NULL
);
1044 KeyCell
= (PCM_KEY_NODE
)HvGetCell(&CmiVolatileHive
->Hive
, RootIndex
);
1045 if (!KeyCell
) return FALSE
;
1047 /* Create the KCB */
1048 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1049 Kcb
= CmpCreateKeyControlBlock(&CmiVolatileHive
->Hive
,
1055 if (!Kcb
) return FALSE
;
1057 /* Initialize the object */
1058 RootKey
->KeyControlBlock
= Kcb
;
1059 RootKey
->Type
= '20yk';
1060 RootKey
->NotifyBlock
= NULL
;
1061 RootKey
->ProcessID
= PsGetCurrentProcessId();
1064 EnlistKeyBodyWithKCB(RootKey
, 0);
1066 /* Insert the key into the namespace */
1067 Status
= ObInsertObject(RootKey
,
1072 &CmpRegistryRootHandle
);
1073 if (!NT_SUCCESS(Status
)) return FALSE
;
1075 /* Reference the key again so that we never lose it */
1076 Status
= ObReferenceObjectByHandle(CmpRegistryRootHandle
,
1082 if (!NT_SUCCESS(Status
)) return FALSE
;
1084 /* Completely sucessful */
1090 CmpGetRegistryPath(IN PWCHAR ConfigPath
)
1092 OBJECT_ATTRIBUTES ObjectAttributes
;
1095 PKEY_VALUE_PARTIAL_INFORMATION ValueInfo
;
1096 UNICODE_STRING KeyName
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\HARDWARE");
1097 UNICODE_STRING ValueName
= RTL_CONSTANT_STRING(L
"InstallPath");
1098 ULONG BufferSize
, ResultSize
;
1100 /* Check if we are booted in setup */
1101 if (ExpInTextModeSetup
)
1103 /* Setup the object attributes */
1104 InitializeObjectAttributes(&ObjectAttributes
,
1106 OBJ_CASE_INSENSITIVE
,
1110 Status
= ZwOpenKey(&KeyHandle
,
1113 if (!NT_SUCCESS(Status
)) return Status
;
1115 /* Allocate the buffer */
1116 BufferSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 4096;
1117 ValueInfo
= ExAllocatePoolWithTag(PagedPool
, BufferSize
, TAG_CM
);
1122 return STATUS_INSUFFICIENT_RESOURCES
;
1125 /* Query the value */
1126 Status
= ZwQueryValueKey(KeyHandle
,
1128 KeyValuePartialInformation
,
1133 if (!NT_SUCCESS(Status
))
1136 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1140 /* Copy the config path and null-terminate it */
1141 RtlCopyMemory(ConfigPath
,
1143 ValueInfo
->DataLength
);
1144 ConfigPath
[ValueInfo
->DataLength
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1145 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1149 /* Just use default path */
1150 wcscpy(ConfigPath
, L
"\\SystemRoot");
1153 /* Add registry path */
1154 wcscat(ConfigPath
, L
"\\System32\\Config\\");
1157 return STATUS_SUCCESS
;
1162 CmpLoadHiveThread(IN PVOID StartContext
)
1164 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1165 UNICODE_STRING TempName
, FileName
, RegName
;
1166 ULONG i
, ErrorResponse
, WorkerCount
, Length
;
1169 ULONG PrimaryDisposition
, SecondaryDisposition
, ClusterSize
;
1171 HANDLE PrimaryHandle
= NULL
, LogHandle
= NULL
;
1172 NTSTATUS Status
= STATUS_SUCCESS
;
1173 PVOID ErrorParameters
;
1176 /* Get the hive index, make sure it makes sense */
1177 i
= PtrToUlong(StartContext
);
1178 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1180 /* We were started */
1181 CmpMachineHiveList
[i
].ThreadStarted
= TRUE
;
1183 /* Build the file name and registry name strings */
1184 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, MAX_PATH
);
1185 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, MAX_PATH
);
1187 /* Now build the system root path */
1188 CmpGetRegistryPath(ConfigPath
);
1189 RtlInitUnicodeString(&TempName
, ConfigPath
);
1190 RtlAppendStringToString((PSTRING
)&FileName
, (PSTRING
)&TempName
);
1191 FileStart
= FileName
.Length
;
1193 /* And build the registry root path */
1194 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1195 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1196 //RegStart = RegName.Length;
1198 /* Build the base name */
1199 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1200 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1202 /* Check if this is a child of the root */
1203 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == '\\')
1205 /* Then setup the whole name */
1206 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1207 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1210 /* Now add the rest of the file name */
1211 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1212 FileName
.Length
= FileStart
;
1213 RtlAppendStringToString((PSTRING
)&FileName
, (PSTRING
)&TempName
);
1214 if (!CmpMachineHiveList
[i
].CmHive
)
1216 /* We need to allocate a new hive structure */
1217 CmpMachineHiveList
[i
].Allocate
= TRUE
;
1219 /* Load the hive file */
1220 Status
= CmpInitHiveFromFile(&FileName
,
1221 CmpMachineHiveList
[i
].HHiveFlags
,
1223 &CmpMachineHiveList
[i
].Allocate
,
1225 if (!(NT_SUCCESS(Status
)) ||
1226 (!(CmHive
->FileHandles
[HFILE_TYPE_LOG
]) && !(CmpMiniNTBoot
))) // HACK
1228 /* We failed or couldn't get a log file, raise a hard error */
1229 ErrorParameters
= &FileName
;
1230 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1233 (PULONG_PTR
)&ErrorParameters
,
1238 /* Set the hive flags and newly allocated hive pointer */
1239 CmHive
->Flags
= CmpMachineHiveList
[i
].CmHiveFlags
;
1240 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1244 /* We already have a hive, is it volatile? */
1245 CmHive
= CmpMachineHiveList
[i
].CmHive
;
1246 if (!(CmHive
->Hive
.HiveFlags
& HIVE_VOLATILE
))
1248 /* It's now, open the hive file and log */
1249 Status
= CmpOpenHiveFiles(&FileName
,
1253 &PrimaryDisposition
,
1254 &SecondaryDisposition
,
1259 if (!(NT_SUCCESS(Status
)) || !(LogHandle
))
1261 /* Couldn't open the hive or its log file, raise a hard error */
1262 ErrorParameters
= &FileName
;
1263 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1266 (PULONG_PTR
)&ErrorParameters
,
1270 /* And bugcheck for posterity's sake */
1271 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 0, i
, Status
);
1274 /* Save the file handles. This should remove our sync hacks */
1275 CmHive
->FileHandles
[HFILE_TYPE_LOG
] = LogHandle
;
1276 CmHive
->FileHandles
[HFILE_TYPE_PRIMARY
] = PrimaryHandle
;
1278 /* Allow lazy flushing since the handles are there -- remove sync hacks */
1279 //ASSERT(CmHive->Hive.HiveFlags & HIVE_NOLAZYFLUSH);
1280 CmHive
->Hive
.HiveFlags
&= ~HIVE_NOLAZYFLUSH
;
1282 /* Get the real size of the hive */
1283 Length
= CmHive
->Hive
.Storage
[Stable
].Length
+ HBLOCK_SIZE
;
1285 /* Check if the cluster size doesn't match */
1286 if (CmHive
->Hive
.Cluster
!= ClusterSize
) ASSERT(FALSE
);
1288 /* Set the file size */
1289 DPRINT("FIXME: Should set file size: %lx\n", Length
);
1290 //if (!CmpFileSetSize((PHHIVE)CmHive, HFILE_TYPE_PRIMARY, Length, Length))
1292 /* This shouldn't fail */
1296 /* Another thing we don't support is NTLDR-recovery */
1297 if (CmHive
->Hive
.BaseBlock
->BootRecover
) ASSERT(FALSE
);
1299 /* Finally, set our allocated hive to the same hive we've had */
1300 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1301 ASSERT(CmpMachineHiveList
[i
].CmHive
== CmpMachineHiveList
[i
].CmHive2
);
1306 CmpMachineHiveList
[i
].ThreadFinished
= TRUE
;
1308 /* Check if we're the last worker */
1309 WorkerCount
= InterlockedIncrement(&CmpLoadWorkerIncrement
);
1310 if (WorkerCount
== CM_NUMBER_OF_MACHINE_HIVES
)
1312 /* Signal the event */
1313 KeSetEvent(&CmpLoadWorkerEvent
, 0, FALSE
);
1316 /* Kill the thread */
1317 PsTerminateSystemThread(Status
);
1322 CmpInitializeHiveList(IN USHORT Flag
)
1324 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1325 UNICODE_STRING TempName
, FileName
, RegName
;
1330 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1333 /* Allow writing for now */
1336 /* Build the file name and registry name strings */
1337 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, MAX_PATH
);
1338 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, MAX_PATH
);
1340 /* Now build the system root path */
1341 CmpGetRegistryPath(ConfigPath
);
1342 RtlInitUnicodeString(&TempName
, ConfigPath
);
1343 RtlAppendStringToString((PSTRING
)&FileName
, (PSTRING
)&TempName
);
1345 /* And build the registry root path */
1346 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1347 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1348 RegStart
= RegName
.Length
;
1350 /* Setup the event to synchronize workers */
1351 KeInitializeEvent(&CmpLoadWorkerEvent
, SynchronizationEvent
, FALSE
);
1353 /* Enter special boot condition */
1354 CmpSpecialBootCondition
= TRUE
;
1356 /* Create the SD for the root hives */
1357 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1359 /* Loop every hive we care about */
1360 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1362 /* Make sure the list is setup */
1363 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1365 /* Create a thread to handle this hive */
1366 Status
= PsCreateSystemThread(&Thread
,
1373 if (NT_SUCCESS(Status
))
1375 /* We don't care about the handle -- the thread self-terminates */
1380 /* Can't imagine this happening */
1381 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 3, i
, Status
);
1385 /* Make sure we've reached the end of the list */
1386 ASSERT(CmpMachineHiveList
[i
].Name
== NULL
);
1388 /* Wait for hive loading to finish */
1389 KeWaitForSingleObject(&CmpLoadWorkerEvent
,
1395 /* Exit the special boot condition and make sure all workers completed */
1396 CmpSpecialBootCondition
= FALSE
;
1397 ASSERT(CmpLoadWorkerIncrement
== CM_NUMBER_OF_MACHINE_HIVES
);
1399 /* Loop hives again */
1400 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1402 /* Make sure the thread ran and finished */
1403 ASSERT(CmpMachineHiveList
[i
].ThreadFinished
== TRUE
);
1404 ASSERT(CmpMachineHiveList
[i
].ThreadStarted
== TRUE
);
1406 /* Check if this was a new hive */
1407 if (!CmpMachineHiveList
[i
].CmHive
)
1409 /* Make sure we allocated something */
1410 ASSERT(CmpMachineHiveList
[i
].CmHive2
!= NULL
);
1412 /* Build the base name */
1413 RegName
.Length
= RegStart
;
1414 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1415 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1417 /* Check if this is a child of the root */
1418 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == '\\')
1420 /* Then setup the whole name */
1421 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1422 RtlAppendStringToString((PSTRING
)&RegName
, (PSTRING
)&TempName
);
1425 /* Now link the hive to its master */
1426 Status
= CmpLinkHiveToMaster(&RegName
,
1428 CmpMachineHiveList
[i
].CmHive2
,
1429 CmpMachineHiveList
[i
].Allocate
,
1430 SecurityDescriptor
);
1431 if (Status
!= STATUS_SUCCESS
)
1433 /* Linking needs to work */
1434 KeBugCheckEx(CONFIG_LIST_FAILED
, 11, Status
, i
, (ULONG_PTR
)&RegName
);
1437 /* Check if we had to allocate a new hive */
1438 if (CmpMachineHiveList
[i
].Allocate
)
1440 /* Sync the new hive */
1441 //HvSyncHive((PHHIVE)(CmpMachineHiveList[i].CmHive2));
1445 /* Check if we created a new hive */
1446 if (CmpMachineHiveList
[i
].CmHive2
)
1448 /* Add to HiveList key */
1449 CmpAddToHiveFileList(CmpMachineHiveList
[i
].CmHive2
);
1453 /* Get rid of the SD */
1454 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1456 /* Link SECURITY to SAM */
1457 CmpLinkKeyToHive(L
"\\Registry\\Machine\\Security\\SAM",
1458 L
"\\Registry\\Machine\\SAM\\SAM");
1460 /* Link S-1-5-18 to .Default */
1461 CmpLinkKeyToHive(L
"\\Registry\\User\\S-1-5-18",
1462 L
"\\Registry\\User\\.Default");
1470 OBJECT_ATTRIBUTES ObjectAttributes
;
1471 UNICODE_STRING KeyName
;
1474 PCMHIVE HardwareHive
;
1475 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1478 /* Check if this is PE-boot */
1479 if (InitIsWinPEMode
)
1481 /* Set registry to PE mode */
1482 CmpMiniNTBoot
= TRUE
;
1483 CmpShareSystemHives
= TRUE
;
1486 /* Initialize the hive list and lock */
1487 InitializeListHead(&CmpHiveListHead
);
1488 ExInitializePushLock(&CmpHiveListHeadLock
);
1489 ExInitializePushLock(&CmpLoadHiveLock
);
1491 /* Initialize registry lock */
1492 ExInitializeResourceLite(&CmpRegistryLock
);
1494 /* Initialize the cache */
1495 CmpInitializeCache();
1497 /* Initialize allocation and delayed dereferencing */
1498 CmpInitCmPrivateAlloc();
1499 CmpInitCmPrivateDelayAlloc();
1500 CmpInitDelayDerefKCBEngine();
1502 /* Initialize callbacks */
1505 /* Initialize self healing */
1506 KeInitializeGuardedMutex(&CmpSelfHealQueueLock
);
1507 InitializeListHead(&CmpSelfHealQueueListHead
);
1509 /* Save the current process and lock the registry */
1510 CmpSystemProcess
= PsGetCurrentProcess();
1512 /* Create the key object types */
1513 Status
= CmpCreateObjectTypes();
1514 if (!NT_SUCCESS(Status
))
1517 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 1, Status
, 0);
1520 /* Build the master hive */
1521 Status
= CmpInitializeHive((PCMHIVE
*)&CmiVolatileHive
,
1531 if (!NT_SUCCESS(Status
))
1534 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 2, Status
, 0);
1537 /* Create the \REGISTRY key node */
1538 if (!CmpCreateRegistryRoot())
1541 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 3, 0, 0);
1544 /* Create the default security descriptor */
1545 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1547 /* Create '\Registry\Machine' key. */
1548 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE");
1549 InitializeObjectAttributes(&ObjectAttributes
,
1551 OBJ_CASE_INSENSITIVE
,
1553 SecurityDescriptor
);
1554 Status
= NtCreateKey(&KeyHandle
,
1555 KEY_READ
| KEY_WRITE
,
1561 if (!NT_SUCCESS(Status
))
1564 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 5, Status
, 0);
1567 /* Close the handle */
1570 /* Create '\Registry\User' key. */
1571 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\USER");
1572 InitializeObjectAttributes(&ObjectAttributes
,
1574 OBJ_CASE_INSENSITIVE
,
1576 SecurityDescriptor
);
1577 Status
= NtCreateKey(&KeyHandle
,
1578 KEY_READ
| KEY_WRITE
,
1584 if (!NT_SUCCESS(Status
))
1587 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 6, Status
, 0);
1590 /* Close the handle */
1593 /* Initialize the system hive */
1594 if (!CmpInitializeSystemHive(KeLoaderBlock
))
1597 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 7, 0, 0);
1600 /* Create the 'CurrentControlSet' link. */
1601 Status
= CmpCreateControlSet(KeLoaderBlock
);
1602 if (!NT_SUCCESS(Status
))
1605 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 8, Status
, 0);
1608 /* Create the hardware hive */
1609 Status
= CmpInitializeHive((PCMHIVE
*)&HardwareHive
,
1619 if (!NT_SUCCESS(Status
))
1622 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 11, Status
, 0);
1625 /* Add the hive to the hive list */
1626 CmpMachineHiveList
[0].CmHive
= (PCMHIVE
)HardwareHive
;
1628 /* Attach it to the machine key */
1629 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\HARDWARE");
1630 Status
= CmpLinkHiveToMaster(&KeyName
,
1632 (PCMHIVE
)HardwareHive
,
1634 SecurityDescriptor
);
1635 if (!NT_SUCCESS(Status
))
1638 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 12, Status
, 0);
1641 /* Add to HiveList key */
1642 CmpAddToHiveFileList(HardwareHive
);
1644 /* Free the security descriptor */
1645 ExFreePoolWithTag(SecurityDescriptor
, TAG_CM
);
1647 /* Fill out the Hardware key with the ARC Data from the Loader */
1648 Status
= CmpInitializeHardwareConfiguration(KeLoaderBlock
);
1649 if (!NT_SUCCESS(Status
))
1652 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 13, Status
, 0);
1655 /* Initialize machine-dependent information into the registry */
1656 Status
= CmpInitializeMachineDependentConfiguration(KeLoaderBlock
);
1657 if (!NT_SUCCESS(Status
))
1660 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 14, Status
, 0);
1663 /* Initialize volatile registry settings */
1664 Status
= CmpSetSystemValues(KeLoaderBlock
);
1665 if (!NT_SUCCESS(Status
))
1668 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 15, Status
, 0);
1671 /* Free the load options */
1672 ExFreePoolWithTag(CmpLoadOptions
.Buffer
, TAG_CM
);
1674 /* If we got here, all went well */
1681 CmpFreeDriverList(IN PHHIVE Hive
,
1682 IN PLIST_ENTRY DriverList
)
1684 PLIST_ENTRY NextEntry
, OldEntry
;
1685 PBOOT_DRIVER_NODE DriverNode
;
1688 /* Parse the current list */
1689 NextEntry
= DriverList
->Flink
;
1690 while (NextEntry
!= DriverList
)
1692 /* Get the driver node */
1693 DriverNode
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_NODE
, ListEntry
.Link
);
1695 /* Get the next entry now, since we're going to free it later */
1696 OldEntry
= NextEntry
;
1697 NextEntry
= NextEntry
->Flink
;
1699 /* Was there a name? */
1700 if (DriverNode
->Name
.Buffer
)
1703 CmpFree(DriverNode
->Name
.Buffer
, DriverNode
->Name
.Length
);
1706 /* Was there a registry path? */
1707 if (DriverNode
->ListEntry
.RegistryPath
.Buffer
)
1710 CmpFree(DriverNode
->ListEntry
.RegistryPath
.Buffer
,
1711 DriverNode
->ListEntry
.RegistryPath
.MaximumLength
);
1714 /* Was there a file path? */
1715 if (DriverNode
->ListEntry
.FilePath
.Buffer
)
1718 CmpFree(DriverNode
->ListEntry
.FilePath
.Buffer
,
1719 DriverNode
->ListEntry
.FilePath
.MaximumLength
);
1722 /* Now free the node, and move on */
1723 CmpFree(OldEntry
, sizeof(BOOT_DRIVER_NODE
));
1730 CmGetSystemDriverList(VOID
)
1732 LIST_ENTRY DriverList
;
1733 OBJECT_ATTRIBUTES ObjectAttributes
;
1735 PCM_KEY_BODY KeyBody
;
1737 HCELL_INDEX RootCell
, ControlCell
;
1739 UNICODE_STRING KeyName
;
1740 PLIST_ENTRY NextEntry
;
1742 PUNICODE_STRING
* ServicePath
= NULL
;
1743 BOOLEAN Success
, AutoSelect
;
1744 PBOOT_DRIVER_LIST_ENTRY DriverEntry
;
1747 /* Initialize the driver list */
1748 InitializeListHead(&DriverList
);
1750 /* Open the system hive key */
1751 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\System");
1752 InitializeObjectAttributes(&ObjectAttributes
,
1754 OBJ_CASE_INSENSITIVE
,
1757 Status
= NtOpenKey(&KeyHandle
, KEY_READ
, &ObjectAttributes
);
1758 if (!NT_SUCCESS(Status
)) return NULL
;
1760 /* Reference the key object to get the root hive/cell to access directly */
1761 Status
= ObReferenceObjectByHandle(KeyHandle
,
1767 if (!NT_SUCCESS(Status
))
1774 /* Do all this under the registry lock */
1775 CmpLockRegistryExclusive();
1777 /* Get the hive and key cell */
1778 Hive
= KeyBody
->KeyControlBlock
->KeyHive
;
1779 RootCell
= KeyBody
->KeyControlBlock
->KeyCell
;
1781 /* Open the current control set key */
1782 RtlInitUnicodeString(&KeyName
, L
"Current");
1783 ControlCell
= CmpFindControlSet(Hive
, RootCell
, &KeyName
, &AutoSelect
);
1784 if (ControlCell
== HCELL_NIL
) goto EndPath
;
1786 /* Find all system drivers */
1787 Success
= CmpFindDrivers(Hive
, ControlCell
, SystemLoad
, NULL
, &DriverList
);
1788 if (!Success
) goto EndPath
;
1790 /* Sort by group/tag */
1791 if (!CmpSortDriverList(Hive
, ControlCell
, &DriverList
)) goto EndPath
;
1793 /* Remove circular dependencies (cycles) and sort */
1794 if (!CmpResolveDriverDependencies(&DriverList
)) goto EndPath
;
1796 /* Loop the list to count drivers */
1797 for (i
= 0, NextEntry
= DriverList
.Flink
;
1798 NextEntry
!= &DriverList
;
1799 i
++, NextEntry
= NextEntry
->Flink
);
1801 /* Allocate the array */
1802 ServicePath
= ExAllocatePool(NonPagedPool
, (i
+ 1) * sizeof(PUNICODE_STRING
));
1803 if (!ServicePath
) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 2, 1, 0, 0);
1805 /* Loop the driver list */
1806 for (i
= 0, NextEntry
= DriverList
.Flink
;
1807 NextEntry
!= &DriverList
;
1808 i
++, NextEntry
= NextEntry
->Flink
)
1811 DriverEntry
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_LIST_ENTRY
, Link
);
1813 /* Allocate the path for the caller and duplicate the registry path */
1814 ServicePath
[i
] = ExAllocatePool(NonPagedPool
, sizeof(UNICODE_STRING
));
1815 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1816 &DriverEntry
->RegistryPath
,
1820 /* Terminate the list */
1821 ServicePath
[i
] = NULL
;
1824 /* Free the driver list if we had one */
1825 if (!IsListEmpty(&DriverList
)) CmpFreeDriverList(Hive
, &DriverList
);
1827 /* Unlock the registry */
1828 CmpUnlockRegistry();
1830 /* Close the key handle and dereference the object, then return the path */
1831 ObDereferenceObject(KeyBody
);
1838 CmpLockRegistryExclusive(VOID
)
1840 /* Enter a critical region and lock the registry */
1841 KeEnterCriticalRegion();
1842 ExAcquireResourceExclusiveLite(&CmpRegistryLock
, TRUE
);
1845 ASSERT(CmpFlushStarveWriters
== 0);
1846 RtlGetCallersAddress(&CmpRegistryLockCaller
, &CmpRegistryLockCallerCaller
);
1851 CmpLockRegistry(VOID
)
1853 /* Enter a critical region */
1854 KeEnterCriticalRegion();
1856 /* Check if we have to starve writers */
1857 if (CmpFlushStarveWriters
)
1859 /* Starve exlusive waiters */
1860 ExAcquireSharedStarveExclusive(&CmpRegistryLock
, TRUE
);
1864 /* Just grab the lock */
1865 ExAcquireResourceSharedLite(&CmpRegistryLock
, TRUE
);
1871 CmpTestRegistryLock(VOID
)
1874 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1879 CmpTestRegistryLockExclusive(VOID
)
1882 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1887 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive
)
1889 /* Lock the flusher. We should already be in a critical section */
1890 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1891 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1892 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1893 ExAcquireResourceExclusiveLite(Hive
->FlusherLock
, TRUE
);
1898 CmpLockHiveFlusherShared(IN PCMHIVE Hive
)
1900 /* Lock the flusher. We should already be in a critical section */
1901 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1902 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1903 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1904 ExAcquireResourceSharedLite(Hive
->FlusherLock
, TRUE
);
1909 CmpUnlockHiveFlusher(IN PCMHIVE Hive
)
1912 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1913 CMP_ASSERT_FLUSH_LOCK(Hive
);
1915 /* Release the lock */
1916 ExReleaseResourceLite(Hive
->FlusherLock
);
1921 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive
)
1924 return !ExIsResourceAcquiredSharedLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
1929 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive
)
1932 return !ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
1937 CmpUnlockRegistry(VOID
)
1940 CMP_ASSERT_REGISTRY_LOCK();
1942 /* Check if we should flush the registry */
1943 if (CmpFlushOnLockRelease
)
1945 /* The registry should be exclusively locked for this */
1946 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
1948 /* Flush the registry */
1949 CmpDoFlushAll(TRUE
);
1950 CmpFlushOnLockRelease
= FALSE
;
1954 /* Lazy flush the registry */
1958 /* Release the lock and leave the critical region */
1959 ExReleaseResourceLite(&CmpRegistryLock
);
1960 KeLeaveCriticalRegion();
1965 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1
,
1968 ULONG Index1
, Index2
;
1971 CMP_ASSERT_REGISTRY_LOCK();
1973 /* Get hash indexes */
1974 Index1
= GET_HASH_INDEX(ConvKey1
);
1975 Index2
= GET_HASH_INDEX(ConvKey2
);
1977 /* See which one is highest */
1978 if (Index1
< Index2
)
1980 /* Grab them in the proper order */
1981 CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
1982 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
1986 /* Grab the second one first, then the first */
1987 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
1988 if (Index1
!= Index2
) CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
1994 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1
,
1997 ULONG Index1
, Index2
;
2000 CMP_ASSERT_REGISTRY_LOCK();
2002 /* Get hash indexes */
2003 Index1
= GET_HASH_INDEX(ConvKey1
);
2004 Index2
= GET_HASH_INDEX(ConvKey2
);
2005 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey2
).Owner
== KeGetCurrentThread()) ||
2006 (CmpTestRegistryLockExclusive()));
2008 /* See which one is highest */
2009 if (Index1
< Index2
)
2011 /* Grab them in the proper order */
2012 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2013 (CmpTestRegistryLockExclusive()));
2014 CmpReleaseKcbLockByKey(ConvKey2
);
2015 CmpReleaseKcbLockByKey(ConvKey1
);
2019 /* Release the first one first, then the second */
2020 if (Index1
!= Index2
)
2022 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2023 (CmpTestRegistryLockExclusive()));
2024 CmpReleaseKcbLockByKey(ConvKey1
);
2026 CmpReleaseKcbLockByKey(ConvKey2
);
2032 CmShutdownSystem(VOID
)
2034 /* Kill the workers */
2035 if (!CmFirstTime
) CmpShutdownWorkers();
2037 /* Flush all hives */
2038 CmpLockRegistryExclusive();
2039 CmpDoFlushAll(TRUE
);
2040 CmpUnlockRegistry();
2045 CmpSetVersionData(VOID
)
2047 OBJECT_ATTRIBUTES ObjectAttributes
;
2048 UNICODE_STRING KeyName
;
2049 UNICODE_STRING ValueName
;
2050 UNICODE_STRING ValueData
;
2051 HANDLE SoftwareKeyHandle
= NULL
;
2052 HANDLE MicrosoftKeyHandle
= NULL
;
2053 HANDLE WindowsNtKeyHandle
= NULL
;
2054 HANDLE CurrentVersionKeyHandle
= NULL
;
2058 /* Open the 'CurrentVersion' key */
2059 RtlInitUnicodeString(&KeyName
,
2060 L
"\\REGISTRY\\MACHINE\\SOFTWARE");
2062 InitializeObjectAttributes(&ObjectAttributes
,
2064 OBJ_CASE_INSENSITIVE
,
2068 Status
= NtCreateKey(&SoftwareKeyHandle
,
2075 if (!NT_SUCCESS(Status
))
2077 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2081 /* Open the 'CurrentVersion' key */
2082 RtlInitUnicodeString(&KeyName
,
2085 InitializeObjectAttributes(&ObjectAttributes
,
2087 OBJ_CASE_INSENSITIVE
,
2091 Status
= NtCreateKey(&MicrosoftKeyHandle
,
2098 if (!NT_SUCCESS(Status
))
2100 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2104 /* Open the 'CurrentVersion' key */
2105 RtlInitUnicodeString(&KeyName
,
2108 InitializeObjectAttributes(&ObjectAttributes
,
2110 OBJ_CASE_INSENSITIVE
,
2114 Status
= NtCreateKey(&WindowsNtKeyHandle
,
2121 if (!NT_SUCCESS(Status
))
2123 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2127 /* Open the 'CurrentVersion' key */
2128 RtlInitUnicodeString(&KeyName
,
2131 InitializeObjectAttributes(&ObjectAttributes
,
2133 OBJ_CASE_INSENSITIVE
,
2137 Status
= NtCreateKey(&CurrentVersionKeyHandle
,
2138 KEY_CREATE_SUB_KEY
| KEY_SET_VALUE
,
2144 if (!NT_SUCCESS(Status
))
2146 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2150 /* Set the 'CurrentType' value */
2151 RtlInitUnicodeString(&ValueName
,
2155 wcscpy(Buffer
, L
"Multiprocessor");
2157 wcscpy(Buffer
, L
"Uniprocessor");
2160 wcscat(Buffer
, L
" ");
2163 wcscat(Buffer
, L
"Checked");
2165 wcscat(Buffer
, L
"Free");
2168 RtlInitUnicodeString(&ValueData
,
2171 NtSetValueKey(CurrentVersionKeyHandle
,
2176 ValueData
.Length
+ sizeof(WCHAR
));
2179 /* Close the keys */
2180 if (CurrentVersionKeyHandle
!= NULL
)
2181 NtClose(CurrentVersionKeyHandle
);
2183 if (WindowsNtKeyHandle
!= NULL
)
2184 NtClose(WindowsNtKeyHandle
);
2186 if (MicrosoftKeyHandle
!= NULL
)
2187 NtClose(MicrosoftKeyHandle
);
2189 if (SoftwareKeyHandle
!= NULL
)
2190 NtClose(SoftwareKeyHandle
);