2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/config/cmsysini.c
5 * PURPOSE: Configuration Manager - System Initialization Code
6 * PROGRAMMERS: ReactOS Portable Systems Group
7 * Alex Ionescu (alex.ionescu@reactos.org)
10 /* INCLUDES *******************************************************************/
16 POBJECT_TYPE CmpKeyObjectType
;
17 PCMHIVE CmiVolatileHive
;
18 LIST_ENTRY CmpHiveListHead
;
19 ERESOURCE CmpRegistryLock
;
20 KGUARDED_MUTEX CmpSelfHealQueueLock
;
21 LIST_ENTRY CmpSelfHealQueueListHead
;
22 KEVENT CmpLoadWorkerEvent
;
23 LONG CmpLoadWorkerIncrement
;
24 PEPROCESS CmpSystemProcess
;
25 BOOLEAN HvShutdownComplete
;
26 PVOID CmpRegistryLockCallerCaller
, CmpRegistryLockCaller
;
27 BOOLEAN CmpFlushOnLockRelease
;
28 BOOLEAN CmpSpecialBootCondition
;
30 BOOLEAN CmpWasSetupBoot
;
31 BOOLEAN CmpProfileLoaded
;
32 BOOLEAN CmpNoVolatileCreates
;
33 ULONG CmpTraceLevel
= 0;
35 extern LONG CmpFlushStarveWriters
;
36 extern BOOLEAN CmFirstTime
;
38 /* FUNCTIONS ******************************************************************/
43 _In_z_ PWSTR LinkKeyName
,
44 _In_z_ PWSTR TargetKeyName
)
46 OBJECT_ATTRIBUTES ObjectAttributes
;
47 UNICODE_STRING LinkKeyName_U
;
48 HANDLE TargetKeyHandle
;
53 /* Initialize the object attributes */
54 RtlInitUnicodeString(&LinkKeyName_U
, LinkKeyName
);
55 InitializeObjectAttributes(&ObjectAttributes
,
57 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
61 /* Create the link key */
62 Status
= ZwCreateKey(&TargetKeyHandle
,
67 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
69 if (!NT_SUCCESS(Status
))
71 DPRINT1("CM: CmpLinkKeyToHive: couldn't create %S Status = 0x%lx\n",
76 /* Check if the new key was actually created */
77 if (Disposition
!= REG_CREATED_NEW_KEY
)
79 DPRINT1("CM: CmpLinkKeyToHive: %S already exists!\n", LinkKeyName
);
80 ZwClose(TargetKeyHandle
);
84 /* Set the target key name as link target */
85 Status
= ZwSetValueKey(TargetKeyHandle
,
86 &CmSymbolicLinkValueName
,
90 (ULONG
)wcslen(TargetKeyName
) * sizeof(WCHAR
));
92 /* Close the link key handle */
93 ObCloseHandle(TargetKeyHandle
, KernelMode
);
95 if (!NT_SUCCESS(Status
))
97 DPRINT1("CM: CmpLinkKeyToHive: couldn't create symbolic link for %S\n",
107 CmpDeleteKeyObject(PVOID DeletedObject
)
109 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)DeletedObject
;
110 PCM_KEY_CONTROL_BLOCK Kcb
;
111 REG_KEY_HANDLE_CLOSE_INFORMATION KeyHandleCloseInfo
;
112 REG_POST_OPERATION_INFORMATION PostOperationInfo
;
116 /* First off, prepare the handle close information callback */
117 PostOperationInfo
.Object
= KeyBody
;
118 KeyHandleCloseInfo
.Object
= KeyBody
;
119 Status
= CmiCallRegisteredCallbacks(RegNtPreKeyHandleClose
,
120 &KeyHandleCloseInfo
);
121 if (!NT_SUCCESS(Status
))
123 /* If we failed, notify the post routine */
124 PostOperationInfo
.Status
= Status
;
125 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
129 /* Acquire hive lock */
132 /* Make sure this is a valid key body */
133 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
136 Kcb
= KeyBody
->KeyControlBlock
;
140 DelistKeyBodyFromKCB(KeyBody
, FALSE
);
142 /* Dereference the KCB */
143 CmpDelayDerefKeyControlBlock(Kcb
);
147 /* Release the registry lock */
150 /* Do the post callback */
151 PostOperationInfo
.Status
= STATUS_SUCCESS
;
152 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose
, &PostOperationInfo
);
157 CmpCloseKeyObject(IN PEPROCESS Process OPTIONAL
,
159 IN ACCESS_MASK GrantedAccess
,
160 IN ULONG ProcessHandleCount
,
161 IN ULONG SystemHandleCount
)
163 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)Object
;
166 /* Don't do anything if we're not the last handle */
167 if (SystemHandleCount
> 1) return;
169 /* Make sure we're a valid key body */
170 if (KeyBody
->Type
== CM_KEY_BODY_TYPE
)
172 /* Don't do anything if we don't have a notify block */
173 if (!KeyBody
->NotifyBlock
) return;
175 /* This shouldn't happen yet */
182 CmpQueryKeyName(IN PVOID ObjectBody
,
184 IN OUT POBJECT_NAME_INFORMATION ObjectNameInfo
,
186 OUT PULONG ReturnLength
,
187 IN KPROCESSOR_MODE PreviousMode
)
189 PUNICODE_STRING KeyName
;
191 NTSTATUS Status
= STATUS_SUCCESS
;
192 PCM_KEY_BODY KeyBody
= (PCM_KEY_BODY
)ObjectBody
;
193 PCM_KEY_CONTROL_BLOCK Kcb
= KeyBody
->KeyControlBlock
;
195 /* Acquire hive lock */
198 /* Lock KCB shared */
199 CmpAcquireKcbLockShared(Kcb
);
201 /* Check if it's a deleted block */
204 /* Release the locks */
205 CmpReleaseKcbLock(Kcb
);
208 /* Let the caller know it's deleted */
209 return STATUS_KEY_DELETED
;
213 KeyName
= CmpConstructName(Kcb
);
215 /* Release the locks */
216 CmpReleaseKcbLock(Kcb
);
219 /* Check if we got the name */
220 if (!KeyName
) return STATUS_INSUFFICIENT_RESOURCES
;
222 /* Set the returned length */
223 *ReturnLength
= KeyName
->Length
+ sizeof(OBJECT_NAME_INFORMATION
) + sizeof(WCHAR
);
225 /* Calculate amount of bytes to copy into the buffer */
226 BytesToCopy
= KeyName
->Length
+ sizeof(WCHAR
);
228 /* Check if the provided buffer is too small to fit even anything */
229 if ((Length
<= sizeof(OBJECT_NAME_INFORMATION
)) ||
230 ((Length
< (*ReturnLength
)) && (BytesToCopy
< sizeof(WCHAR
))))
232 /* Free the buffer allocated by CmpConstructName */
233 ExFreePoolWithTag(KeyName
, TAG_CM
);
235 /* Return buffer length failure without writing anything there because nothing fits */
236 return STATUS_INFO_LENGTH_MISMATCH
;
239 /* Check if the provided buffer can be partially written */
240 if (Length
< (*ReturnLength
))
242 /* Yes, indicate so in the return status */
243 Status
= STATUS_INFO_LENGTH_MISMATCH
;
245 /* Calculate amount of bytes which the provided buffer could handle */
246 BytesToCopy
= Length
- sizeof(OBJECT_NAME_INFORMATION
);
249 /* Remove the null termination character from the size */
250 BytesToCopy
-= sizeof(WCHAR
);
252 /* Fill in the result */
255 /* Return data to user */
256 ObjectNameInfo
->Name
.Buffer
= (PWCHAR
)(ObjectNameInfo
+ 1);
257 ObjectNameInfo
->Name
.MaximumLength
= KeyName
->Length
;
258 ObjectNameInfo
->Name
.Length
= KeyName
->Length
;
260 /* Copy string content*/
261 RtlCopyMemory(ObjectNameInfo
->Name
.Buffer
,
265 /* Null terminate it */
266 ObjectNameInfo
->Name
.Buffer
[BytesToCopy
/ sizeof(WCHAR
)] = 0;
268 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
271 Status
= _SEH2_GetExceptionCode();
275 /* Free the buffer allocated by CmpConstructName */
276 ExFreePoolWithTag(KeyName
, TAG_CM
);
284 CmpInitHiveFromFile(IN PCUNICODE_STRING HiveName
,
290 ULONG HiveDisposition
, LogDisposition
;
291 HANDLE FileHandle
= NULL
, LogHandle
= NULL
;
293 ULONG Operation
, FileType
;
300 /* Open or create the hive files */
301 Status
= CmpOpenHiveFiles(HiveName
,
311 if (!NT_SUCCESS(Status
)) return Status
;
313 /* Check if we have a log handle */
314 FileType
= (LogHandle
) ? HFILE_TYPE_LOG
: HFILE_TYPE_PRIMARY
;
316 /* Check if we created or opened the hive */
317 if (HiveDisposition
== FILE_CREATED
)
319 /* Do a create operation */
320 Operation
= HINIT_CREATE
;
325 /* Open it as a file */
326 Operation
= HINIT_FILE
;
330 /* Check if we're sharing hives */
331 if (CmpShareSystemHives
)
333 /* Then force using the primary hive */
334 FileType
= HFILE_TYPE_PRIMARY
;
337 /* Get rid of the log handle */
343 /* Check if we're too late */
344 if (HvShutdownComplete
)
348 if (LogHandle
) ZwClose(LogHandle
);
349 return STATUS_TOO_LATE
;
352 /* Initialize the hive */
353 Status
= CmpInitializeHive(&NewHive
,
363 if (!NT_SUCCESS(Status
))
367 if (LogHandle
) ZwClose(LogHandle
);
371 /* Success, return hive */
374 /* Duplicate the hive name */
375 NewHive
->FileFullPath
.Buffer
= ExAllocatePoolWithTag(PagedPool
,
378 if (NewHive
->FileFullPath
.Buffer
)
380 /* Copy the string */
381 RtlCopyMemory(NewHive
->FileFullPath
.Buffer
,
384 NewHive
->FileFullPath
.Length
= HiveName
->Length
;
385 NewHive
->FileFullPath
.MaximumLength
= HiveName
->MaximumLength
;
389 return STATUS_SUCCESS
;
395 CmpSetSystemValues(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
397 OBJECT_ATTRIBUTES ObjectAttributes
;
398 UNICODE_STRING KeyName
, ValueName
= { 0, 0, NULL
};
399 HANDLE KeyHandle
= NULL
;
401 ASSERT(LoaderBlock
!= NULL
);
403 /* Setup attributes for loader options */
404 RtlInitUnicodeString(&KeyName
,
405 L
"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\"
407 InitializeObjectAttributes(&ObjectAttributes
,
409 OBJ_CASE_INSENSITIVE
,
412 Status
= NtOpenKey(&KeyHandle
, KEY_WRITE
, &ObjectAttributes
);
413 if (!NT_SUCCESS(Status
)) goto Quickie
;
415 /* Key opened, now write to the key */
416 RtlInitUnicodeString(&KeyName
, L
"SystemStartOptions");
417 Status
= NtSetValueKey(KeyHandle
,
421 CmpLoadOptions
.Buffer
,
422 CmpLoadOptions
.Length
);
423 if (!NT_SUCCESS(Status
)) goto Quickie
;
425 /* Setup value name for system boot device in ARC format */
426 RtlInitUnicodeString(&KeyName
, L
"SystemBootDevice");
427 RtlCreateUnicodeStringFromAsciiz(&ValueName
, LoaderBlock
->ArcBootDeviceName
);
428 Status
= NtSetValueKey(KeyHandle
,
436 /* Free the buffers */
437 RtlFreeUnicodeString(&ValueName
);
439 /* Close the key and return */
440 if (KeyHandle
) NtClose(KeyHandle
);
442 /* Return the status */
443 return (ExpInTextModeSetup
? STATUS_SUCCESS
: Status
);
449 CmpCreateHardwareProfile(HANDLE ControlSetHandle
)
451 OBJECT_ATTRIBUTES ObjectAttributes
;
452 UNICODE_STRING KeyName
;
453 HANDLE ProfilesHandle
= NULL
;
454 HANDLE ProfileHandle
= NULL
;
458 DPRINT("CmpCreateHardwareProfile()\n");
460 /* Create the Hardware Profiles key */
461 RtlInitUnicodeString(&KeyName
, L
"Hardware Profiles");
462 InitializeObjectAttributes(&ObjectAttributes
,
464 OBJ_CASE_INSENSITIVE
,
467 Status
= NtCreateKey(&ProfilesHandle
,
474 if (!NT_SUCCESS(Status
))
476 DPRINT1("Creating the Hardware Profile key failed\n");
481 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
483 /* Create the 0000 key */
484 RtlInitUnicodeString(&KeyName
, L
"0000");
485 InitializeObjectAttributes(&ObjectAttributes
,
487 OBJ_CASE_INSENSITIVE
,
490 Status
= NtCreateKey(&ProfileHandle
,
497 if (!NT_SUCCESS(Status
))
499 DPRINT1("Creating the Hardware Profile\\0000 key failed\n");
504 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
508 NtClose(ProfilesHandle
);
511 NtClose(ProfileHandle
);
513 DPRINT("CmpCreateHardwareProfile() done\n");
521 CmpCreateControlSet(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
523 UNICODE_STRING ConfigName
= RTL_CONSTANT_STRING(L
"Control\\IDConfigDB");
524 UNICODE_STRING SelectName
=
525 RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\System\\Select");
526 UNICODE_STRING KeyName
;
527 OBJECT_ATTRIBUTES ObjectAttributes
;
528 CHAR ValueInfoBuffer
[128];
529 PKEY_VALUE_FULL_INFORMATION ValueInfo
;
531 WCHAR UnicodeBuffer
[128];
532 HANDLE SelectHandle
, KeyHandle
, ConfigHandle
= NULL
, ProfileHandle
= NULL
;
533 HANDLE ParentHandle
= NULL
;
534 ULONG ControlSet
, HwProfile
;
535 ANSI_STRING TempString
;
537 ULONG ResultLength
, Disposition
;
538 PLOADER_PARAMETER_EXTENSION LoaderExtension
;
541 /* Open the select key */
542 InitializeObjectAttributes(&ObjectAttributes
,
544 OBJ_CASE_INSENSITIVE
,
547 Status
= NtOpenKey(&SelectHandle
, KEY_READ
, &ObjectAttributes
);
548 if (!NT_SUCCESS(Status
))
550 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
551 if (!LoaderBlock
->RegistryBase
)
553 /* Build the ControlSet001 key */
554 RtlInitUnicodeString(&KeyName
,
555 L
"\\Registry\\Machine\\System\\ControlSet001");
556 InitializeObjectAttributes(&ObjectAttributes
,
558 OBJ_CASE_INSENSITIVE
,
561 Status
= NtCreateKey(&KeyHandle
,
568 if (!NT_SUCCESS(Status
)) return Status
;
570 /* Create the Hardware Profile keys */
571 Status
= CmpCreateHardwareProfile(KeyHandle
);
572 if (!NT_SUCCESS(Status
))
575 /* Don't need the handle */
578 /* Use hard-coded setting */
583 /* Fail for real boots */
587 /* Open the current value */
588 RtlInitUnicodeString(&KeyName
, L
"Current");
589 Status
= NtQueryValueKey(SelectHandle
,
591 KeyValueFullInformation
,
593 sizeof(ValueInfoBuffer
),
595 NtClose(SelectHandle
);
596 if (!NT_SUCCESS(Status
)) return Status
;
598 /* Get the actual value pointer, and get the control set ID */
599 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
600 ControlSet
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
602 /* Create the current control set key */
604 RtlInitUnicodeString(&KeyName
,
605 L
"\\Registry\\Machine\\System\\CurrentControlSet");
606 InitializeObjectAttributes(&ObjectAttributes
,
608 OBJ_CASE_INSENSITIVE
,
611 Status
= NtCreateKey(&KeyHandle
,
616 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
618 if (!NT_SUCCESS(Status
)) return Status
;
621 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
623 /* Initialize the symbolic link name */
625 "\\Registry\\Machine\\System\\ControlSet%03ld",
627 RtlInitAnsiString(&TempString
, Buffer
);
629 /* Create a Unicode string out of it */
630 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
631 KeyName
.Buffer
= UnicodeBuffer
;
632 Status
= RtlAnsiStringToUnicodeString(&KeyName
, &TempString
, FALSE
);
635 Status
= NtSetValueKey(KeyHandle
,
636 &CmSymbolicLinkValueName
,
641 if (!NT_SUCCESS(Status
)) return Status
;
643 /* Get the configuration database key */
644 InitializeObjectAttributes(&ObjectAttributes
,
646 OBJ_CASE_INSENSITIVE
,
649 Status
= NtOpenKey(&ConfigHandle
, KEY_READ
, &ObjectAttributes
);
652 /* Check if we don't have one */
653 if (!NT_SUCCESS(Status
))
655 /* Cleanup and exit */
660 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
661 if (!LoaderBlock
->RegistryBase
)
667 /* Now get the current config */
668 RtlInitUnicodeString(&KeyName
, L
"CurrentConfig");
669 Status
= NtQueryValueKey(ConfigHandle
,
671 KeyValueFullInformation
,
673 sizeof(ValueInfoBuffer
),
676 /* Set pointer to buffer */
677 ValueInfo
= (PKEY_VALUE_FULL_INFORMATION
)ValueInfoBuffer
;
679 /* Check if we failed or got a non DWORD-value */
680 if (!(NT_SUCCESS(Status
)) || (ValueInfo
->Type
!= REG_DWORD
)) goto Cleanup
;
682 /* Get the hadware profile */
683 HwProfile
= *(PULONG
)((PUCHAR
)ValueInfo
+ ValueInfo
->DataOffset
);
686 /* Open the hardware profile key */
687 RtlInitUnicodeString(&KeyName
,
688 L
"\\Registry\\Machine\\System\\CurrentControlSet"
689 L
"\\Hardware Profiles");
690 InitializeObjectAttributes(&ObjectAttributes
,
692 OBJ_CASE_INSENSITIVE
,
695 Status
= NtOpenKey(&ParentHandle
, KEY_READ
, &ObjectAttributes
);
696 if (!NT_SUCCESS(Status
))
698 /* Exit and clean up */
703 /* Build the profile name */
704 sprintf(Buffer
, "%04ld", HwProfile
);
705 RtlInitAnsiString(&TempString
, Buffer
);
707 /* Convert it to Unicode */
708 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
709 KeyName
.Buffer
= UnicodeBuffer
;
710 Status
= RtlAnsiStringToUnicodeString(&KeyName
,
713 ASSERT(Status
== STATUS_SUCCESS
);
715 /* Open the associated key */
716 InitializeObjectAttributes(&ObjectAttributes
,
718 OBJ_CASE_INSENSITIVE
,
721 Status
= NtOpenKey(&ProfileHandle
,
722 KEY_READ
| KEY_WRITE
,
724 if (!NT_SUCCESS (Status
))
726 /* Cleanup and exit */
731 /* Check if we have a loader block extension */
732 LoaderExtension
= LoaderBlock
->Extension
;
735 DPRINT("ReactOS doesn't support NTLDR Profiles yet!\n");
738 /* Create the current hardware profile key */
739 RtlInitUnicodeString(&KeyName
,
740 L
"\\Registry\\Machine\\System\\CurrentControlSet\\"
741 L
"Hardware Profiles\\Current");
742 InitializeObjectAttributes(&ObjectAttributes
,
744 OBJ_CASE_INSENSITIVE
,
747 Status
= NtCreateKey(&KeyHandle
,
752 REG_OPTION_VOLATILE
| REG_OPTION_CREATE_LINK
,
754 if (NT_SUCCESS(Status
))
757 ASSERT(Disposition
== REG_CREATED_NEW_KEY
);
759 /* Create the profile name */
761 "\\Registry\\Machine\\System\\CurrentControlSet\\"
762 "Hardware Profiles\\%04ld",
764 RtlInitAnsiString(&TempString
, Buffer
);
766 /* Convert it to Unicode */
767 KeyName
.MaximumLength
= sizeof(UnicodeBuffer
);
768 KeyName
.Buffer
= UnicodeBuffer
;
769 Status
= RtlAnsiStringToUnicodeString(&KeyName
,
772 ASSERT(STATUS_SUCCESS
== Status
);
775 Status
= NtSetValueKey(KeyHandle
,
776 &CmSymbolicLinkValueName
,
784 /* Close every opened handle */
786 if (ConfigHandle
) NtClose(ConfigHandle
);
787 if (ProfileHandle
) NtClose(ProfileHandle
);
788 if (ParentHandle
) NtClose(ParentHandle
);
790 DPRINT("CmpCreateControlSet() done\n");
793 return STATUS_SUCCESS
;
798 CmpLinkHiveToMaster(IN PUNICODE_STRING LinkName
,
799 IN HANDLE RootDirectory
,
800 IN PCMHIVE RegistryHive
,
802 IN PSECURITY_DESCRIPTOR SecurityDescriptor
)
804 OBJECT_ATTRIBUTES ObjectAttributes
;
806 CM_PARSE_CONTEXT ParseContext
= {0};
808 PCM_KEY_BODY KeyBody
;
811 /* Setup the object attributes */
812 InitializeObjectAttributes(&ObjectAttributes
,
814 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
818 /* Setup the parse context */
819 ParseContext
.CreateLink
= TRUE
;
820 ParseContext
.CreateOperation
= TRUE
;
821 ParseContext
.ChildHive
.KeyHive
= &RegistryHive
->Hive
;
823 /* Check if we have a root keycell or if we need to create it */
827 ParseContext
.ChildHive
.KeyCell
= HCELL_NIL
;
832 ParseContext
.ChildHive
.KeyCell
= RegistryHive
->Hive
.BaseBlock
->RootCell
;
835 /* Create the link node */
836 Status
= ObOpenObjectByName(&ObjectAttributes
,
840 KEY_READ
| KEY_WRITE
,
841 (PVOID
)&ParseContext
,
843 if (!NT_SUCCESS(Status
)) return Status
;
845 /* Mark the hive as clean */
846 RegistryHive
->Hive
.DirtyFlag
= FALSE
;
848 /* ReactOS Hack: Keep alive */
849 Status
= ObReferenceObjectByHandle(KeyHandle
,
855 ASSERT(NT_SUCCESS(Status
));
857 /* Close the extra handle */
859 return STATUS_SUCCESS
;
865 CmpInitializeSystemHive(IN PLOADER_PARAMETER_BLOCK LoaderBlock
)
868 ANSI_STRING LoadString
;
873 UNICODE_STRING KeyName
;
874 PCMHIVE SystemHive
= NULL
;
875 UNICODE_STRING HiveName
= RTL_CONSTANT_STRING(L
"SYSTEM");
876 PSECURITY_DESCRIPTOR SecurityDescriptor
;
879 /* Setup the ansi string */
880 RtlInitAnsiString(&LoadString
, LoaderBlock
->LoadOptions
);
882 /* Allocate the unicode buffer */
883 Length
= LoadString
.Length
* sizeof(WCHAR
) + sizeof(UNICODE_NULL
);
884 Buffer
= ExAllocatePoolWithTag(PagedPool
, Length
, TAG_CM
);
888 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 3, 1, (ULONG_PTR
)LoaderBlock
, 0);
891 /* Setup the unicode string */
892 RtlInitEmptyUnicodeString(&CmpLoadOptions
, Buffer
, (USHORT
)Length
);
894 /* Add the load options and null-terminate */
895 RtlAnsiStringToUnicodeString(&CmpLoadOptions
, &LoadString
, FALSE
);
896 CmpLoadOptions
.Buffer
[LoadString
.Length
] = UNICODE_NULL
;
897 CmpLoadOptions
.Length
+= sizeof(WCHAR
);
899 /* Get the System Hive base address */
900 HiveBase
= LoaderBlock
->RegistryBase
;
904 Status
= CmpInitializeHive(&SystemHive
,
914 if (!NT_SUCCESS(Status
)) return FALSE
;
916 /* Set the hive filename */
917 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
918 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
920 /* We imported, no need to create a new hive */
923 /* Manually set the hive as volatile, if in Live CD mode */
924 if (CmpShareSystemHives
) SystemHive
->Hive
.HiveFlags
= HIVE_VOLATILE
;
929 Status
= CmpInitializeHive(&SystemHive
,
939 if (!NT_SUCCESS(Status
)) return FALSE
;
941 /* Set the hive filename */
942 RtlCreateUnicodeString(&SystemHive
->FileFullPath
,
943 L
"\\SystemRoot\\System32\\Config\\SYSTEM");
945 /* Tell CmpLinkHiveToMaster to allocate a hive */
949 /* Save the boot type */
950 CmpBootType
= SystemHive
->Hive
.BaseBlock
->BootType
;
952 /* Are we in self-healing mode? */
955 /* Disable self-healing internally and check if boot type wanted it */
959 /* We're disabled, so bugcheck */
960 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
,
963 (ULONG_PTR
)SystemHive
,
968 /* Create the default security descriptor */
969 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
971 /* Attach it to the system key */
972 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\SYSTEM");
973 Status
= CmpLinkHiveToMaster(&KeyName
,
979 /* Free the security descriptor */
980 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
981 if (!NT_SUCCESS(Status
)) return FALSE
;
983 /* Add the hive to the hive list */
984 CmpMachineHiveList
[3].CmHive
= SystemHive
;
993 CmpCreateObjectTypes(VOID
)
995 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer
;
997 GENERIC_MAPPING CmpKeyMapping
= {KEY_READ
,
1003 /* Initialize the Key object type */
1004 RtlZeroMemory(&ObjectTypeInitializer
, sizeof(ObjectTypeInitializer
));
1005 RtlInitUnicodeString(&Name
, L
"Key");
1006 ObjectTypeInitializer
.Length
= sizeof(ObjectTypeInitializer
);
1007 ObjectTypeInitializer
.DefaultPagedPoolCharge
= sizeof(CM_KEY_BODY
);
1008 ObjectTypeInitializer
.GenericMapping
= CmpKeyMapping
;
1009 ObjectTypeInitializer
.PoolType
= PagedPool
;
1010 ObjectTypeInitializer
.ValidAccessMask
= KEY_ALL_ACCESS
;
1011 ObjectTypeInitializer
.UseDefaultObject
= TRUE
;
1012 ObjectTypeInitializer
.DeleteProcedure
= CmpDeleteKeyObject
;
1013 ObjectTypeInitializer
.ParseProcedure
= CmpParseKey
;
1014 ObjectTypeInitializer
.SecurityProcedure
= CmpSecurityMethod
;
1015 ObjectTypeInitializer
.QueryNameProcedure
= CmpQueryKeyName
;
1016 ObjectTypeInitializer
.CloseProcedure
= CmpCloseKeyObject
;
1017 ObjectTypeInitializer
.SecurityRequired
= TRUE
;
1018 ObjectTypeInitializer
.InvalidAttributes
= OBJ_EXCLUSIVE
| OBJ_PERMANENT
;
1021 return ObCreateObjectType(&Name
, &ObjectTypeInitializer
, NULL
, &CmpKeyObjectType
);
1027 CmpCreateRootNode(IN PHHIVE Hive
,
1029 OUT PHCELL_INDEX Index
)
1031 UNICODE_STRING KeyName
;
1032 PCM_KEY_NODE KeyCell
;
1035 /* Initialize the node name and allocate it */
1036 RtlInitUnicodeString(&KeyName
, Name
);
1037 *Index
= HvAllocateCell(Hive
,
1038 FIELD_OFFSET(CM_KEY_NODE
, Name
) +
1039 CmpNameSize(Hive
, &KeyName
),
1042 if (*Index
== HCELL_NIL
) return FALSE
;
1044 /* Set the cell index and get the data */
1045 Hive
->BaseBlock
->RootCell
= *Index
;
1046 KeyCell
= (PCM_KEY_NODE
)HvGetCell(Hive
, *Index
);
1047 if (!KeyCell
) return FALSE
;
1049 /* Setup the cell */
1050 KeyCell
->Signature
= CM_KEY_NODE_SIGNATURE
;
1051 KeyCell
->Flags
= KEY_HIVE_ENTRY
| KEY_NO_DELETE
;
1052 KeQuerySystemTime(&KeyCell
->LastWriteTime
);
1053 KeyCell
->Parent
= HCELL_NIL
;
1054 KeyCell
->SubKeyCounts
[Stable
] = 0;
1055 KeyCell
->SubKeyCounts
[Volatile
] = 0;
1056 KeyCell
->SubKeyLists
[Stable
] = HCELL_NIL
;
1057 KeyCell
->SubKeyLists
[Volatile
] = HCELL_NIL
;
1058 KeyCell
->ValueList
.Count
= 0;
1059 KeyCell
->ValueList
.List
= HCELL_NIL
;
1060 KeyCell
->Security
= HCELL_NIL
;
1061 KeyCell
->Class
= HCELL_NIL
;
1062 KeyCell
->ClassLength
= 0;
1063 KeyCell
->MaxNameLen
= 0;
1064 KeyCell
->MaxClassLen
= 0;
1065 KeyCell
->MaxValueNameLen
= 0;
1066 KeyCell
->MaxValueDataLen
= 0;
1068 /* Copy the name (this will also set the length) */
1069 KeyCell
->NameLength
= CmpCopyName(Hive
, KeyCell
->Name
, &KeyName
);
1071 /* Check if the name was compressed and set the flag if so */
1072 if (KeyCell
->NameLength
< KeyName
.Length
)
1073 KeyCell
->Flags
|= KEY_COMP_NAME
;
1075 /* Return success */
1076 HvReleaseCell(Hive
, *Index
);
1083 CmpCreateRegistryRoot(VOID
)
1085 UNICODE_STRING KeyName
;
1086 OBJECT_ATTRIBUTES ObjectAttributes
;
1087 PCM_KEY_BODY RootKey
;
1088 HCELL_INDEX RootIndex
;
1090 PCM_KEY_NODE KeyCell
;
1091 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1092 PCM_KEY_CONTROL_BLOCK Kcb
;
1095 /* Setup the root node */
1096 if (!CmpCreateRootNode(&CmiVolatileHive
->Hive
, L
"REGISTRY", &RootIndex
))
1102 /* Create '\Registry' key. */
1103 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1104 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1105 InitializeObjectAttributes(&ObjectAttributes
,
1107 OBJ_CASE_INSENSITIVE
,
1109 SecurityDescriptor
);
1110 Status
= ObCreateObject(KernelMode
,
1115 sizeof(CM_KEY_BODY
),
1119 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
1120 if (!NT_SUCCESS(Status
)) return FALSE
;
1122 /* Sanity check, and get the key cell */
1123 ASSERT((&CmiVolatileHive
->Hive
)->ReleaseCellRoutine
== NULL
);
1124 KeyCell
= (PCM_KEY_NODE
)HvGetCell(&CmiVolatileHive
->Hive
, RootIndex
);
1125 if (!KeyCell
) return FALSE
;
1127 /* Create the KCB */
1128 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY");
1129 Kcb
= CmpCreateKeyControlBlock(&CmiVolatileHive
->Hive
,
1137 ObDereferenceObject(RootKey
);
1141 /* Initialize the object */
1142 RootKey
->KeyControlBlock
= Kcb
;
1143 RootKey
->Type
= CM_KEY_BODY_TYPE
;
1144 RootKey
->NotifyBlock
= NULL
;
1145 RootKey
->ProcessID
= PsGetCurrentProcessId();
1148 EnlistKeyBodyWithKCB(RootKey
, 0);
1150 /* Insert the key into the namespace */
1151 Status
= ObInsertObject(RootKey
,
1156 &CmpRegistryRootHandle
);
1157 if (!NT_SUCCESS(Status
))
1159 ObDereferenceObject(RootKey
);
1163 /* Reference the key again so that we never lose it */
1164 Status
= ObReferenceObjectByHandle(CmpRegistryRootHandle
,
1170 if (!NT_SUCCESS(Status
))
1172 ObDereferenceObject(RootKey
);
1176 /* Completely sucessful */
1182 CmpGetRegistryPath(OUT PWCHAR ConfigPath
)
1184 OBJECT_ATTRIBUTES ObjectAttributes
;
1187 PKEY_VALUE_PARTIAL_INFORMATION ValueInfo
;
1188 UNICODE_STRING KeyName
= RTL_CONSTANT_STRING(L
"\\Registry\\Machine\\HARDWARE");
1189 UNICODE_STRING ValueName
= RTL_CONSTANT_STRING(L
"InstallPath");
1190 ULONG BufferSize
, ResultSize
;
1192 /* Check if we are booted in setup */
1193 if (ExpInTextModeSetup
)
1195 /* Setup the object attributes */
1196 InitializeObjectAttributes(&ObjectAttributes
,
1198 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
1202 Status
= ZwOpenKey(&KeyHandle
,
1205 if (!NT_SUCCESS(Status
)) return Status
;
1207 /* Allocate the buffer */
1208 BufferSize
= sizeof(KEY_VALUE_PARTIAL_INFORMATION
) + 4096;
1209 ValueInfo
= ExAllocatePoolWithTag(PagedPool
, BufferSize
, TAG_CM
);
1214 return STATUS_INSUFFICIENT_RESOURCES
;
1217 /* Query the value */
1218 Status
= ZwQueryValueKey(KeyHandle
,
1220 KeyValuePartialInformation
,
1225 if (!NT_SUCCESS(Status
))
1228 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1232 /* Copy the config path and null-terminate it */
1233 RtlCopyMemory(ConfigPath
,
1235 ValueInfo
->DataLength
);
1236 ConfigPath
[ValueInfo
->DataLength
/ sizeof(WCHAR
)] = UNICODE_NULL
;
1237 ExFreePoolWithTag(ValueInfo
, TAG_CM
);
1241 /* Just use default path */
1242 wcscpy(ConfigPath
, L
"\\SystemRoot");
1245 /* Add registry path */
1246 wcscat(ConfigPath
, L
"\\System32\\Config\\");
1249 return STATUS_SUCCESS
;
1254 CmpLoadHiveThread(IN PVOID StartContext
)
1256 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1257 UNICODE_STRING TempName
, FileName
, RegName
;
1258 ULONG i
, ErrorResponse
, WorkerCount
, Length
;
1260 ULONG PrimaryDisposition
, SecondaryDisposition
, ClusterSize
;
1262 HANDLE PrimaryHandle
= NULL
, LogHandle
= NULL
;
1263 NTSTATUS Status
= STATUS_SUCCESS
;
1264 PVOID ErrorParameters
;
1267 /* Get the hive index, make sure it makes sense */
1268 i
= PtrToUlong(StartContext
);
1269 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1271 /* We were started */
1272 CmpMachineHiveList
[i
].ThreadStarted
= TRUE
;
1274 /* Build the file name and registry name strings */
1275 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, sizeof(FileBuffer
));
1276 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, sizeof(RegBuffer
));
1278 /* Now build the system root path */
1279 CmpGetRegistryPath(ConfigPath
);
1280 RtlInitUnicodeString(&TempName
, ConfigPath
);
1281 RtlAppendUnicodeStringToString(&FileName
, &TempName
);
1282 FileStart
= FileName
.Length
;
1284 /* And build the registry root path */
1285 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1286 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1288 /* Build the base name */
1289 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1290 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1292 /* Check if this is a child of the root */
1293 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == OBJ_NAME_PATH_SEPARATOR
)
1295 /* Then setup the whole name */
1296 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1297 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1300 /* Now add the rest of the file name */
1301 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1302 FileName
.Length
= FileStart
;
1303 RtlAppendUnicodeStringToString(&FileName
, &TempName
);
1304 if (!CmpMachineHiveList
[i
].CmHive
)
1306 /* We need to allocate a new hive structure */
1307 CmpMachineHiveList
[i
].Allocate
= TRUE
;
1309 /* Load the hive file */
1310 Status
= CmpInitHiveFromFile(&FileName
,
1311 CmpMachineHiveList
[i
].HHiveFlags
,
1313 &CmpMachineHiveList
[i
].Allocate
,
1315 if (!(NT_SUCCESS(Status
)) ||
1316 (!(CmHive
->FileHandles
[HFILE_TYPE_LOG
]) && !(CmpMiniNTBoot
))) // HACK
1318 /* We failed or couldn't get a log file, raise a hard error */
1319 ErrorParameters
= &FileName
;
1320 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1323 (PULONG_PTR
)&ErrorParameters
,
1328 /* Set the hive flags and newly allocated hive pointer */
1329 CmHive
->Flags
= CmpMachineHiveList
[i
].CmHiveFlags
;
1330 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1334 /* We already have a hive, is it volatile? */
1335 CmHive
= CmpMachineHiveList
[i
].CmHive
;
1336 if (!(CmHive
->Hive
.HiveFlags
& HIVE_VOLATILE
))
1338 /* It's now, open the hive file and log */
1339 Status
= CmpOpenHiveFiles(&FileName
,
1343 &PrimaryDisposition
,
1344 &SecondaryDisposition
,
1349 if (!(NT_SUCCESS(Status
)) || !(LogHandle
))
1351 /* Couldn't open the hive or its log file, raise a hard error */
1352 ErrorParameters
= &FileName
;
1353 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE
,
1356 (PULONG_PTR
)&ErrorParameters
,
1360 /* And bugcheck for posterity's sake */
1361 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 0, i
, Status
);
1364 /* Save the file handles. This should remove our sync hacks */
1365 CmHive
->FileHandles
[HFILE_TYPE_LOG
] = LogHandle
;
1366 CmHive
->FileHandles
[HFILE_TYPE_PRIMARY
] = PrimaryHandle
;
1368 /* Allow lazy flushing since the handles are there -- remove sync hacks */
1369 //ASSERT(CmHive->Hive.HiveFlags & HIVE_NOLAZYFLUSH);
1370 CmHive
->Hive
.HiveFlags
&= ~HIVE_NOLAZYFLUSH
;
1372 /* Get the real size of the hive */
1373 Length
= CmHive
->Hive
.Storage
[Stable
].Length
+ HBLOCK_SIZE
;
1375 /* Check if the cluster size doesn't match */
1376 if (CmHive
->Hive
.Cluster
!= ClusterSize
) ASSERT(FALSE
);
1378 /* Set the file size */
1379 DPRINT("FIXME: Should set file size: %lx\n", Length
);
1380 //if (!CmpFileSetSize((PHHIVE)CmHive, HFILE_TYPE_PRIMARY, Length, Length))
1382 /* This shouldn't fail */
1386 /* Another thing we don't support is NTLDR-recovery */
1387 if (CmHive
->Hive
.BaseBlock
->BootRecover
) ASSERT(FALSE
);
1389 /* Finally, set our allocated hive to the same hive we've had */
1390 CmpMachineHiveList
[i
].CmHive2
= CmHive
;
1391 ASSERT(CmpMachineHiveList
[i
].CmHive
== CmpMachineHiveList
[i
].CmHive2
);
1396 CmpMachineHiveList
[i
].ThreadFinished
= TRUE
;
1398 /* Check if we're the last worker */
1399 WorkerCount
= InterlockedIncrement(&CmpLoadWorkerIncrement
);
1400 if (WorkerCount
== CM_NUMBER_OF_MACHINE_HIVES
)
1402 /* Signal the event */
1403 KeSetEvent(&CmpLoadWorkerEvent
, 0, FALSE
);
1406 /* Kill the thread */
1407 PsTerminateSystemThread(Status
);
1412 CmpInitializeHiveList(IN USHORT Flag
)
1414 WCHAR FileBuffer
[MAX_PATH
], RegBuffer
[MAX_PATH
], ConfigPath
[MAX_PATH
];
1415 UNICODE_STRING TempName
, FileName
, RegName
;
1420 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1423 /* Allow writing for now */
1426 /* Build the file name and registry name strings */
1427 RtlInitEmptyUnicodeString(&FileName
, FileBuffer
, sizeof(FileBuffer
));
1428 RtlInitEmptyUnicodeString(&RegName
, RegBuffer
, sizeof(RegBuffer
));
1430 /* Now build the system root path */
1431 CmpGetRegistryPath(ConfigPath
);
1432 RtlInitUnicodeString(&TempName
, ConfigPath
);
1433 RtlAppendUnicodeStringToString(&FileName
, &TempName
);
1435 /* And build the registry root path */
1436 RtlInitUnicodeString(&TempName
, L
"\\REGISTRY\\");
1437 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1438 RegStart
= RegName
.Length
;
1440 /* Setup the event to synchronize workers */
1441 KeInitializeEvent(&CmpLoadWorkerEvent
, SynchronizationEvent
, FALSE
);
1443 /* Enter special boot condition */
1444 CmpSpecialBootCondition
= TRUE
;
1446 /* Create the SD for the root hives */
1447 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1449 /* Loop every hive we care about */
1450 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1452 /* Make sure the list is setup */
1453 ASSERT(CmpMachineHiveList
[i
].Name
!= NULL
);
1455 /* Create a thread to handle this hive */
1456 Status
= PsCreateSystemThread(&Thread
,
1463 if (NT_SUCCESS(Status
))
1465 /* We don't care about the handle -- the thread self-terminates */
1470 /* Can't imagine this happening */
1471 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO
, 9, 3, i
, Status
);
1475 /* Make sure we've reached the end of the list */
1476 ASSERT(CmpMachineHiveList
[i
].Name
== NULL
);
1478 /* Wait for hive loading to finish */
1479 KeWaitForSingleObject(&CmpLoadWorkerEvent
,
1485 /* Exit the special boot condition and make sure all workers completed */
1486 CmpSpecialBootCondition
= FALSE
;
1487 ASSERT(CmpLoadWorkerIncrement
== CM_NUMBER_OF_MACHINE_HIVES
);
1489 /* Loop hives again */
1490 for (i
= 0; i
< CM_NUMBER_OF_MACHINE_HIVES
; i
++)
1492 /* Make sure the thread ran and finished */
1493 ASSERT(CmpMachineHiveList
[i
].ThreadFinished
== TRUE
);
1494 ASSERT(CmpMachineHiveList
[i
].ThreadStarted
== TRUE
);
1496 /* Check if this was a new hive */
1497 if (!CmpMachineHiveList
[i
].CmHive
)
1499 /* Make sure we allocated something */
1500 ASSERT(CmpMachineHiveList
[i
].CmHive2
!= NULL
);
1502 /* Build the base name */
1503 RegName
.Length
= RegStart
;
1504 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].BaseName
);
1505 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1507 /* Check if this is a child of the root */
1508 if (RegName
.Buffer
[RegName
.Length
/ sizeof(WCHAR
) - 1] == OBJ_NAME_PATH_SEPARATOR
)
1510 /* Then setup the whole name */
1511 RtlInitUnicodeString(&TempName
, CmpMachineHiveList
[i
].Name
);
1512 RtlAppendUnicodeStringToString(&RegName
, &TempName
);
1515 /* Now link the hive to its master */
1516 Status
= CmpLinkHiveToMaster(&RegName
,
1518 CmpMachineHiveList
[i
].CmHive2
,
1519 CmpMachineHiveList
[i
].Allocate
,
1520 SecurityDescriptor
);
1521 if (Status
!= STATUS_SUCCESS
)
1523 /* Linking needs to work */
1524 KeBugCheckEx(CONFIG_LIST_FAILED
, 11, Status
, i
, (ULONG_PTR
)&RegName
);
1527 /* Check if we had to allocate a new hive */
1528 if (CmpMachineHiveList
[i
].Allocate
)
1530 /* Sync the new hive */
1531 //HvSyncHive((PHHIVE)(CmpMachineHiveList[i].CmHive2));
1535 /* Check if we created a new hive */
1536 if (CmpMachineHiveList
[i
].CmHive2
)
1538 /* Add to HiveList key */
1539 CmpAddToHiveFileList(CmpMachineHiveList
[i
].CmHive2
);
1543 /* Get rid of the SD */
1544 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
1546 /* Link SECURITY to SAM */
1547 CmpLinkKeyToHive(L
"\\Registry\\Machine\\Security\\SAM",
1548 L
"\\Registry\\Machine\\SAM\\SAM");
1550 /* Link S-1-5-18 to .Default */
1551 CmpNoVolatileCreates
= FALSE
;
1552 CmpLinkKeyToHive(L
"\\Registry\\User\\S-1-5-18",
1553 L
"\\Registry\\User\\.Default");
1554 CmpNoVolatileCreates
= TRUE
;
1562 OBJECT_ATTRIBUTES ObjectAttributes
;
1563 UNICODE_STRING KeyName
;
1566 PCMHIVE HardwareHive
;
1567 PSECURITY_DESCRIPTOR SecurityDescriptor
;
1570 /* Check if this is PE-boot */
1571 if (InitIsWinPEMode
)
1573 /* Set registry to PE mode */
1574 CmpMiniNTBoot
= TRUE
;
1575 CmpShareSystemHives
= TRUE
;
1578 /* Initialize the hive list and lock */
1579 InitializeListHead(&CmpHiveListHead
);
1580 ExInitializePushLock(&CmpHiveListHeadLock
);
1581 ExInitializePushLock(&CmpLoadHiveLock
);
1583 /* Initialize registry lock */
1584 ExInitializeResourceLite(&CmpRegistryLock
);
1586 /* Initialize the cache */
1587 CmpInitializeCache();
1589 /* Initialize allocation and delayed dereferencing */
1590 CmpInitCmPrivateAlloc();
1591 CmpInitCmPrivateDelayAlloc();
1592 CmpInitDelayDerefKCBEngine();
1594 /* Initialize callbacks */
1597 /* Initialize self healing */
1598 KeInitializeGuardedMutex(&CmpSelfHealQueueLock
);
1599 InitializeListHead(&CmpSelfHealQueueListHead
);
1601 /* Save the current process and lock the registry */
1602 CmpSystemProcess
= PsGetCurrentProcess();
1604 /* Create the key object types */
1605 Status
= CmpCreateObjectTypes();
1606 if (!NT_SUCCESS(Status
))
1609 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 1, Status
, 0);
1612 /* Build the master hive */
1613 Status
= CmpInitializeHive(&CmiVolatileHive
,
1623 if (!NT_SUCCESS(Status
))
1626 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 2, Status
, 0);
1629 /* Create the \REGISTRY key node */
1630 if (!CmpCreateRegistryRoot())
1633 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 3, 0, 0);
1636 /* Create the default security descriptor */
1637 SecurityDescriptor
= CmpHiveRootSecurityDescriptor();
1639 /* Create '\Registry\Machine' key. */
1640 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE");
1641 InitializeObjectAttributes(&ObjectAttributes
,
1643 OBJ_CASE_INSENSITIVE
,
1645 SecurityDescriptor
);
1646 Status
= NtCreateKey(&KeyHandle
,
1647 KEY_READ
| KEY_WRITE
,
1653 if (!NT_SUCCESS(Status
))
1656 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 5, Status
, 0);
1659 /* Close the handle */
1662 /* Create '\Registry\User' key. */
1663 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\USER");
1664 InitializeObjectAttributes(&ObjectAttributes
,
1666 OBJ_CASE_INSENSITIVE
,
1668 SecurityDescriptor
);
1669 Status
= NtCreateKey(&KeyHandle
,
1670 KEY_READ
| KEY_WRITE
,
1676 if (!NT_SUCCESS(Status
))
1679 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 6, Status
, 0);
1682 /* Close the handle */
1685 /* After this point, do not allow creating keys in the master hive */
1686 CmpNoVolatileCreates
= TRUE
;
1688 /* Initialize the system hive */
1689 if (!CmpInitializeSystemHive(KeLoaderBlock
))
1692 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 7, 0, 0);
1695 /* Create the 'CurrentControlSet' link. */
1696 Status
= CmpCreateControlSet(KeLoaderBlock
);
1697 if (!NT_SUCCESS(Status
))
1700 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 8, Status
, 0);
1703 /* Create the hardware hive */
1704 Status
= CmpInitializeHive(&HardwareHive
,
1714 if (!NT_SUCCESS(Status
))
1717 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 11, Status
, 0);
1720 /* Add the hive to the hive list */
1721 CmpMachineHiveList
[0].CmHive
= HardwareHive
;
1723 /* Attach it to the machine key */
1724 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\HARDWARE");
1725 Status
= CmpLinkHiveToMaster(&KeyName
,
1729 SecurityDescriptor
);
1730 if (!NT_SUCCESS(Status
))
1733 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 12, Status
, 0);
1736 /* Add to HiveList key */
1737 CmpAddToHiveFileList(HardwareHive
);
1739 /* Free the security descriptor */
1740 ExFreePoolWithTag(SecurityDescriptor
, TAG_CMSD
);
1742 /* Fill out the Hardware key with the ARC Data from the Loader */
1743 Status
= CmpInitializeHardwareConfiguration(KeLoaderBlock
);
1744 if (!NT_SUCCESS(Status
))
1747 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 13, Status
, 0);
1750 /* Initialize machine-dependent information into the registry */
1751 Status
= CmpInitializeMachineDependentConfiguration(KeLoaderBlock
);
1752 if (!NT_SUCCESS(Status
))
1755 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 14, Status
, 0);
1758 /* Initialize volatile registry settings */
1759 Status
= CmpSetSystemValues(KeLoaderBlock
);
1760 if (!NT_SUCCESS(Status
))
1763 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 1, 15, Status
, 0);
1766 /* Free the load options */
1767 ExFreePoolWithTag(CmpLoadOptions
.Buffer
, TAG_CM
);
1769 /* If we got here, all went well */
1776 CmpFreeDriverList(IN PHHIVE Hive
,
1777 IN PLIST_ENTRY DriverList
)
1779 PLIST_ENTRY NextEntry
, OldEntry
;
1780 PBOOT_DRIVER_NODE DriverNode
;
1783 /* Parse the current list */
1784 NextEntry
= DriverList
->Flink
;
1785 while (NextEntry
!= DriverList
)
1787 /* Get the driver node */
1788 DriverNode
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_NODE
, ListEntry
.Link
);
1790 /* Get the next entry now, since we're going to free it later */
1791 OldEntry
= NextEntry
;
1792 NextEntry
= NextEntry
->Flink
;
1794 /* Was there a name? */
1795 if (DriverNode
->Name
.Buffer
)
1798 CmpFree(DriverNode
->Name
.Buffer
, DriverNode
->Name
.Length
);
1801 /* Was there a registry path? */
1802 if (DriverNode
->ListEntry
.RegistryPath
.Buffer
)
1805 CmpFree(DriverNode
->ListEntry
.RegistryPath
.Buffer
,
1806 DriverNode
->ListEntry
.RegistryPath
.MaximumLength
);
1809 /* Was there a file path? */
1810 if (DriverNode
->ListEntry
.FilePath
.Buffer
)
1813 CmpFree(DriverNode
->ListEntry
.FilePath
.Buffer
,
1814 DriverNode
->ListEntry
.FilePath
.MaximumLength
);
1817 /* Now free the node, and move on */
1818 CmpFree(OldEntry
, sizeof(BOOT_DRIVER_NODE
));
1825 CmGetSystemDriverList(VOID
)
1827 LIST_ENTRY DriverList
;
1828 OBJECT_ATTRIBUTES ObjectAttributes
;
1830 PCM_KEY_BODY KeyBody
;
1832 HCELL_INDEX RootCell
, ControlCell
;
1834 UNICODE_STRING KeyName
;
1835 PLIST_ENTRY NextEntry
;
1837 PUNICODE_STRING
* ServicePath
= NULL
;
1838 BOOLEAN Success
, AutoSelect
;
1839 PBOOT_DRIVER_LIST_ENTRY DriverEntry
;
1842 /* Initialize the driver list */
1843 InitializeListHead(&DriverList
);
1845 /* Open the system hive key */
1846 RtlInitUnicodeString(&KeyName
, L
"\\Registry\\Machine\\System");
1847 InitializeObjectAttributes(&ObjectAttributes
,
1849 OBJ_CASE_INSENSITIVE
,
1852 Status
= NtOpenKey(&KeyHandle
, KEY_READ
, &ObjectAttributes
);
1853 if (!NT_SUCCESS(Status
)) return NULL
;
1855 /* Reference the key object to get the root hive/cell to access directly */
1856 Status
= ObReferenceObjectByHandle(KeyHandle
,
1862 if (!NT_SUCCESS(Status
))
1869 /* Do all this under the registry lock */
1870 CmpLockRegistryExclusive();
1872 /* Get the hive and key cell */
1873 Hive
= KeyBody
->KeyControlBlock
->KeyHive
;
1874 RootCell
= KeyBody
->KeyControlBlock
->KeyCell
;
1876 /* Open the current control set key */
1877 RtlInitUnicodeString(&KeyName
, L
"Current");
1878 ControlCell
= CmpFindControlSet(Hive
, RootCell
, &KeyName
, &AutoSelect
);
1879 if (ControlCell
== HCELL_NIL
) goto EndPath
;
1881 /* Find all system drivers */
1882 Success
= CmpFindDrivers(Hive
, ControlCell
, SystemLoad
, NULL
, &DriverList
);
1883 if (!Success
) goto EndPath
;
1885 /* Sort by group/tag */
1886 if (!CmpSortDriverList(Hive
, ControlCell
, &DriverList
)) goto EndPath
;
1888 /* Remove circular dependencies (cycles) and sort */
1889 if (!CmpResolveDriverDependencies(&DriverList
)) goto EndPath
;
1891 /* Loop the list to count drivers */
1892 for (i
= 0, NextEntry
= DriverList
.Flink
;
1893 NextEntry
!= &DriverList
;
1894 i
++, NextEntry
= NextEntry
->Flink
);
1896 /* Allocate the array */
1897 ServicePath
= ExAllocatePool(NonPagedPool
, (i
+ 1) * sizeof(PUNICODE_STRING
));
1898 if (!ServicePath
) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED
, 2, 1, 0, 0);
1900 /* Loop the driver list */
1901 for (i
= 0, NextEntry
= DriverList
.Flink
;
1902 NextEntry
!= &DriverList
;
1903 i
++, NextEntry
= NextEntry
->Flink
)
1906 DriverEntry
= CONTAINING_RECORD(NextEntry
, BOOT_DRIVER_LIST_ENTRY
, Link
);
1908 /* Allocate the path for the caller and duplicate the registry path */
1909 ServicePath
[i
] = ExAllocatePool(NonPagedPool
, sizeof(UNICODE_STRING
));
1910 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE
,
1911 &DriverEntry
->RegistryPath
,
1915 /* Terminate the list */
1916 ServicePath
[i
] = NULL
;
1919 /* Free the driver list if we had one */
1920 if (!IsListEmpty(&DriverList
)) CmpFreeDriverList(Hive
, &DriverList
);
1922 /* Unlock the registry */
1923 CmpUnlockRegistry();
1925 /* Close the key handle and dereference the object, then return the path */
1926 ObDereferenceObject(KeyBody
);
1933 CmpLockRegistryExclusive(VOID
)
1935 /* Enter a critical region and lock the registry */
1936 KeEnterCriticalRegion();
1937 ExAcquireResourceExclusiveLite(&CmpRegistryLock
, TRUE
);
1940 ASSERT(CmpFlushStarveWriters
== 0);
1941 RtlGetCallersAddress(&CmpRegistryLockCaller
, &CmpRegistryLockCallerCaller
);
1946 CmpLockRegistry(VOID
)
1948 /* Enter a critical region */
1949 KeEnterCriticalRegion();
1951 /* Check if we have to starve writers */
1952 if (CmpFlushStarveWriters
)
1954 /* Starve exlusive waiters */
1955 ExAcquireSharedStarveExclusive(&CmpRegistryLock
, TRUE
);
1959 /* Just grab the lock */
1960 ExAcquireResourceSharedLite(&CmpRegistryLock
, TRUE
);
1966 CmpTestRegistryLock(VOID
)
1969 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1974 CmpTestRegistryLockExclusive(VOID
)
1977 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock
) ? FALSE
: TRUE
;
1982 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive
)
1984 /* Lock the flusher. We should already be in a critical section */
1985 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1986 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1987 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1988 ExAcquireResourceExclusiveLite(Hive
->FlusherLock
, TRUE
);
1993 CmpLockHiveFlusherShared(IN PCMHIVE Hive
)
1995 /* Lock the flusher. We should already be in a critical section */
1996 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
1997 ASSERT((ExIsResourceAcquiredShared(Hive
->FlusherLock
) == 0) &&
1998 (ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) == 0));
1999 ExAcquireResourceSharedLite(Hive
->FlusherLock
, TRUE
);
2004 CmpUnlockHiveFlusher(IN PCMHIVE Hive
)
2007 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive
);
2008 CMP_ASSERT_FLUSH_LOCK(Hive
);
2010 /* Release the lock */
2011 ExReleaseResourceLite(Hive
->FlusherLock
);
2016 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive
)
2019 return !ExIsResourceAcquiredSharedLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
2024 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive
)
2027 return !ExIsResourceAcquiredExclusiveLite(Hive
->FlusherLock
) ? FALSE
: TRUE
;
2032 CmpUnlockRegistry(VOID
)
2035 CMP_ASSERT_REGISTRY_LOCK();
2037 /* Check if we should flush the registry */
2038 if (CmpFlushOnLockRelease
)
2040 /* The registry should be exclusively locked for this */
2041 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
2043 /* Flush the registry */
2044 CmpDoFlushAll(TRUE
);
2045 CmpFlushOnLockRelease
= FALSE
;
2049 /* Lazy flush the registry */
2053 /* Release the lock and leave the critical region */
2054 ExReleaseResourceLite(&CmpRegistryLock
);
2055 KeLeaveCriticalRegion();
2060 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1
,
2063 ULONG Index1
, Index2
;
2066 CMP_ASSERT_REGISTRY_LOCK();
2068 /* Get hash indexes */
2069 Index1
= GET_HASH_INDEX(ConvKey1
);
2070 Index2
= GET_HASH_INDEX(ConvKey2
);
2072 /* See which one is highest */
2073 if (Index1
< Index2
)
2075 /* Grab them in the proper order */
2076 CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2077 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2081 /* Grab the second one first, then the first */
2082 CmpAcquireKcbLockExclusiveByKey(ConvKey2
);
2083 if (Index1
!= Index2
) CmpAcquireKcbLockExclusiveByKey(ConvKey1
);
2089 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1
,
2092 ULONG Index1
, Index2
;
2095 CMP_ASSERT_REGISTRY_LOCK();
2097 /* Get hash indexes */
2098 Index1
= GET_HASH_INDEX(ConvKey1
);
2099 Index2
= GET_HASH_INDEX(ConvKey2
);
2100 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey2
).Owner
== KeGetCurrentThread()) ||
2101 (CmpTestRegistryLockExclusive()));
2103 /* See which one is highest */
2104 if (Index1
< Index2
)
2106 /* Grab them in the proper order */
2107 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2108 (CmpTestRegistryLockExclusive()));
2109 CmpReleaseKcbLockByKey(ConvKey2
);
2110 CmpReleaseKcbLockByKey(ConvKey1
);
2114 /* Release the first one first, then the second */
2115 if (Index1
!= Index2
)
2117 ASSERT((GET_HASH_ENTRY(CmpCacheTable
, ConvKey1
).Owner
== KeGetCurrentThread()) ||
2118 (CmpTestRegistryLockExclusive()));
2119 CmpReleaseKcbLockByKey(ConvKey1
);
2121 CmpReleaseKcbLockByKey(ConvKey2
);
2127 CmShutdownSystem(VOID
)
2129 PLIST_ENTRY ListEntry
;
2132 /* Kill the workers */
2133 if (!CmFirstTime
) CmpShutdownWorkers();
2135 /* Flush all hives */
2136 CmpLockRegistryExclusive();
2137 CmpDoFlushAll(TRUE
);
2139 /* Close all hive files */
2140 ListEntry
= CmpHiveListHead
.Flink
;
2141 while (ListEntry
!= &CmpHiveListHead
)
2143 Hive
= CONTAINING_RECORD(ListEntry
, CMHIVE
, HiveList
);
2145 CmpCloseHiveFiles(Hive
);
2147 ListEntry
= ListEntry
->Flink
;
2150 CmpUnlockRegistry();
2155 CmpSetVersionData(VOID
)
2158 OBJECT_ATTRIBUTES ObjectAttributes
;
2159 UNICODE_STRING KeyName
;
2160 UNICODE_STRING ValueName
;
2161 UNICODE_STRING ValueData
;
2162 ANSI_STRING TempString
;
2163 HANDLE SoftwareKeyHandle
= NULL
;
2164 HANDLE MicrosoftKeyHandle
= NULL
;
2165 HANDLE WindowsNtKeyHandle
= NULL
;
2166 HANDLE CurrentVersionKeyHandle
= NULL
;
2167 WCHAR Buffer
[128]; // Buffer large enough to contain a full ULONG in decimal representation,
2168 // and the full 'CurrentType' string.
2171 * Open the 'HKLM\Software\Microsoft\Windows NT\CurrentVersion' key
2172 * (create the intermediate subkeys if needed).
2175 RtlInitUnicodeString(&KeyName
, L
"\\REGISTRY\\MACHINE\\SOFTWARE");
2176 InitializeObjectAttributes(&ObjectAttributes
,
2178 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2181 Status
= NtCreateKey(&SoftwareKeyHandle
,
2188 if (!NT_SUCCESS(Status
))
2190 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2194 RtlInitUnicodeString(&KeyName
, L
"Microsoft");
2195 InitializeObjectAttributes(&ObjectAttributes
,
2197 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2200 Status
= NtCreateKey(&MicrosoftKeyHandle
,
2207 if (!NT_SUCCESS(Status
))
2209 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2213 RtlInitUnicodeString(&KeyName
, L
"Windows NT");
2214 InitializeObjectAttributes(&ObjectAttributes
,
2216 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2219 Status
= NtCreateKey(&WindowsNtKeyHandle
,
2226 if (!NT_SUCCESS(Status
))
2228 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2232 RtlInitUnicodeString(&KeyName
, L
"CurrentVersion");
2233 InitializeObjectAttributes(&ObjectAttributes
,
2235 OBJ_CASE_INSENSITIVE
| OBJ_KERNEL_HANDLE
,
2238 Status
= NtCreateKey(&CurrentVersionKeyHandle
,
2239 KEY_CREATE_SUB_KEY
| KEY_SET_VALUE
,
2245 if (!NT_SUCCESS(Status
))
2247 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName
, Status
);
2251 /* Set the 'CurrentVersion' value */
2252 RtlInitUnicodeString(&ValueName
, L
"CurrentVersion");
2253 NtSetValueKey(CurrentVersionKeyHandle
,
2257 CmVersionString
.Buffer
,
2258 CmVersionString
.Length
+ sizeof(WCHAR
));
2260 /* Set the 'CurrentBuildNumber' value */
2261 RtlInitUnicodeString(&ValueName
, L
"CurrentBuildNumber");
2262 RtlInitEmptyUnicodeString(&ValueData
, Buffer
, sizeof(Buffer
));
2263 RtlIntegerToUnicodeString(NtBuildNumber
& 0xFFFF, 10, &ValueData
);
2264 NtSetValueKey(CurrentVersionKeyHandle
,
2269 ValueData
.Length
+ sizeof(WCHAR
));
2271 /* Set the 'BuildLab' value */
2272 RtlInitUnicodeString(&ValueName
, L
"BuildLab");
2273 RtlInitAnsiString(&TempString
, NtBuildLab
);
2274 Status
= RtlAnsiStringToUnicodeString(&ValueData
, &TempString
, FALSE
);
2275 if (NT_SUCCESS(Status
))
2277 NtSetValueKey(CurrentVersionKeyHandle
,
2282 ValueData
.Length
+ sizeof(WCHAR
));
2285 /* Set the 'CurrentType' value */
2286 RtlInitUnicodeString(&ValueName
, L
"CurrentType");
2288 swprintf(Buffer
, L
"%s %s",
2301 RtlInitUnicodeString(&ValueData
, Buffer
);
2302 NtSetValueKey(CurrentVersionKeyHandle
,
2307 ValueData
.Length
+ sizeof(WCHAR
));
2309 /* Set the 'CSDVersion' value */
2310 RtlInitUnicodeString(&ValueName
, L
"CSDVersion");
2311 if (CmCSDVersionString
.Length
!= 0)
2313 NtSetValueKey(CurrentVersionKeyHandle
,
2317 CmCSDVersionString
.Buffer
,
2318 CmCSDVersionString
.Length
+ sizeof(WCHAR
));
2322 NtDeleteValueKey(CurrentVersionKeyHandle
, &ValueName
);
2325 /* Set the 'CSDBuildNumber' value */
2326 RtlInitUnicodeString(&ValueName
, L
"CSDBuildNumber");
2327 if (CmNtSpBuildNumber
!= 0)
2329 RtlInitEmptyUnicodeString(&ValueData
, Buffer
, sizeof(Buffer
));
2330 RtlIntegerToUnicodeString(CmNtSpBuildNumber
, 10, &ValueData
);
2331 NtSetValueKey(CurrentVersionKeyHandle
,
2336 ValueData
.Length
+ sizeof(WCHAR
));
2340 NtDeleteValueKey(CurrentVersionKeyHandle
, &ValueName
);
2343 /* Set the 'SystemRoot' value */
2344 RtlInitUnicodeString(&ValueName
, L
"SystemRoot");
2345 NtSetValueKey(CurrentVersionKeyHandle
,
2349 NtSystemRoot
.Buffer
,
2350 NtSystemRoot
.Length
+ sizeof(WCHAR
));
2353 /* Close the keys */
2354 if (CurrentVersionKeyHandle
!= NULL
)
2355 NtClose(CurrentVersionKeyHandle
);
2357 if (WindowsNtKeyHandle
!= NULL
)
2358 NtClose(WindowsNtKeyHandle
);
2360 if (MicrosoftKeyHandle
!= NULL
)
2361 NtClose(MicrosoftKeyHandle
);
2363 if (SoftwareKeyHandle
!= NULL
)
2364 NtClose(SoftwareKeyHandle
);