[NTOS]: Underline the fact that CmpGetRegistryPath (especially when being run in...
[reactos.git] / reactos / ntoskrnl / config / cmsysini.c
1 /*
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)
8 */
9
10 /* INCLUDES *******************************************************************/
11
12 #include "ntoskrnl.h"
13 #define NDEBUG
14 #include "debug.h"
15
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;
29 BOOLEAN CmpNoWrite;
30 BOOLEAN CmpWasSetupBoot;
31 BOOLEAN CmpProfileLoaded;
32 BOOLEAN CmpNoVolatileCreates;
33 ULONG CmpTraceLevel = 0;
34
35 extern LONG CmpFlushStarveWriters;
36 extern BOOLEAN CmFirstTime;
37
38 /* FUNCTIONS ******************************************************************/
39
40 BOOLEAN
41 NTAPI
42 CmpLinkKeyToHive(
43 _In_z_ PWSTR LinkKeyName,
44 _In_z_ PWSTR TargetKeyName)
45 {
46 OBJECT_ATTRIBUTES ObjectAttributes;
47 UNICODE_STRING LinkKeyName_U;
48 HANDLE TargetKeyHandle;
49 ULONG Disposition;
50 NTSTATUS Status;
51 PAGED_CODE();
52
53 /* Initialize the object attributes */
54 RtlInitUnicodeString(&LinkKeyName_U, LinkKeyName);
55 InitializeObjectAttributes(&ObjectAttributes,
56 &LinkKeyName_U,
57 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
58 NULL,
59 NULL);
60
61 /* Create the link key */
62 Status = ZwCreateKey(&TargetKeyHandle,
63 KEY_CREATE_LINK,
64 &ObjectAttributes,
65 0,
66 NULL,
67 REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK,
68 &Disposition);
69 if (!NT_SUCCESS(Status))
70 {
71 DPRINT1("CM: CmpLinkKeyToHive: couldn't create %S Status = 0x%lx\n",
72 LinkKeyName, Status);
73 return FALSE;
74 }
75
76 /* Check if the new key was actually created */
77 if (Disposition != REG_CREATED_NEW_KEY)
78 {
79 DPRINT1("CM: CmpLinkKeyToHive: %S already exists!\n", LinkKeyName);
80 ZwClose(TargetKeyHandle);
81 return FALSE;
82 }
83
84 /* Set the target key name as link target */
85 Status = ZwSetValueKey(TargetKeyHandle,
86 &CmSymbolicLinkValueName,
87 0,
88 REG_LINK,
89 TargetKeyName,
90 (ULONG)wcslen(TargetKeyName) * sizeof(WCHAR));
91
92 /* Close the link key handle */
93 ObCloseHandle(TargetKeyHandle, KernelMode);
94
95 if (!NT_SUCCESS(Status))
96 {
97 DPRINT1("CM: CmpLinkKeyToHive: couldn't create symbolic link for %S\n",
98 TargetKeyName);
99 return FALSE;
100 }
101
102 return TRUE;
103 }
104
105 VOID
106 NTAPI
107 CmpDeleteKeyObject(PVOID DeletedObject)
108 {
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;
113 NTSTATUS Status;
114 PAGED_CODE();
115
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))
122 {
123 /* If we failed, notify the post routine */
124 PostOperationInfo.Status = Status;
125 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose, &PostOperationInfo);
126 return;
127 }
128
129 /* Acquire hive lock */
130 CmpLockRegistry();
131
132 /* Make sure this is a valid key body */
133 if (KeyBody->Type == CM_KEY_BODY_TYPE)
134 {
135 /* Get the KCB */
136 Kcb = KeyBody->KeyControlBlock;
137 if (Kcb)
138 {
139 /* Delist the key */
140 DelistKeyBodyFromKCB(KeyBody, FALSE);
141
142 /* Dereference the KCB */
143 CmpDelayDerefKeyControlBlock(Kcb);
144 }
145 }
146
147 /* Release the registry lock */
148 CmpUnlockRegistry();
149
150 /* Do the post callback */
151 PostOperationInfo.Status = STATUS_SUCCESS;
152 CmiCallRegisteredCallbacks(RegNtPostKeyHandleClose, &PostOperationInfo);
153 }
154
155 VOID
156 NTAPI
157 CmpCloseKeyObject(IN PEPROCESS Process OPTIONAL,
158 IN PVOID Object,
159 IN ACCESS_MASK GrantedAccess,
160 IN ULONG ProcessHandleCount,
161 IN ULONG SystemHandleCount)
162 {
163 PCM_KEY_BODY KeyBody = (PCM_KEY_BODY)Object;
164 PAGED_CODE();
165
166 /* Don't do anything if we're not the last handle */
167 if (SystemHandleCount > 1) return;
168
169 /* Make sure we're a valid key body */
170 if (KeyBody->Type == CM_KEY_BODY_TYPE)
171 {
172 /* Don't do anything if we don't have a notify block */
173 if (!KeyBody->NotifyBlock) return;
174
175 /* This shouldn't happen yet */
176 ASSERT(FALSE);
177 }
178 }
179
180 NTSTATUS
181 NTAPI
182 CmpQueryKeyName(IN PVOID ObjectBody,
183 IN BOOLEAN HasName,
184 IN OUT POBJECT_NAME_INFORMATION ObjectNameInfo,
185 IN ULONG Length,
186 OUT PULONG ReturnLength,
187 IN KPROCESSOR_MODE PreviousMode)
188 {
189 PUNICODE_STRING KeyName;
190 ULONG BytesToCopy;
191 NTSTATUS Status = STATUS_SUCCESS;
192 PCM_KEY_BODY KeyBody = (PCM_KEY_BODY)ObjectBody;
193 PCM_KEY_CONTROL_BLOCK Kcb = KeyBody->KeyControlBlock;
194
195 /* Acquire hive lock */
196 CmpLockRegistry();
197
198 /* Lock KCB shared */
199 CmpAcquireKcbLockShared(Kcb);
200
201 /* Check if it's a deleted block */
202 if (Kcb->Delete)
203 {
204 /* Release the locks */
205 CmpReleaseKcbLock(Kcb);
206 CmpUnlockRegistry();
207
208 /* Let the caller know it's deleted */
209 return STATUS_KEY_DELETED;
210 }
211
212 /* Get the name */
213 KeyName = CmpConstructName(Kcb);
214
215 /* Release the locks */
216 CmpReleaseKcbLock(Kcb);
217 CmpUnlockRegistry();
218
219 /* Check if we got the name */
220 if (!KeyName) return STATUS_INSUFFICIENT_RESOURCES;
221
222 /* Set the returned length */
223 *ReturnLength = KeyName->Length + sizeof(OBJECT_NAME_INFORMATION) + sizeof(WCHAR);
224
225 /* Calculate amount of bytes to copy into the buffer */
226 BytesToCopy = KeyName->Length + sizeof(WCHAR);
227
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))))
231 {
232 /* Free the buffer allocated by CmpConstructName */
233 ExFreePoolWithTag(KeyName, TAG_CM);
234
235 /* Return buffer length failure without writing anything there because nothing fits */
236 return STATUS_INFO_LENGTH_MISMATCH;
237 }
238
239 /* Check if the provided buffer can be partially written */
240 if (Length < (*ReturnLength))
241 {
242 /* Yes, indicate so in the return status */
243 Status = STATUS_INFO_LENGTH_MISMATCH;
244
245 /* Calculate amount of bytes which the provided buffer could handle */
246 BytesToCopy = Length - sizeof(OBJECT_NAME_INFORMATION);
247 }
248
249 /* Remove the null termination character from the size */
250 BytesToCopy -= sizeof(WCHAR);
251
252 /* Fill in the result */
253 _SEH2_TRY
254 {
255 /* Return data to user */
256 ObjectNameInfo->Name.Buffer = (PWCHAR)(ObjectNameInfo + 1);
257 ObjectNameInfo->Name.MaximumLength = KeyName->Length;
258 ObjectNameInfo->Name.Length = KeyName->Length;
259
260 /* Copy string content*/
261 RtlCopyMemory(ObjectNameInfo->Name.Buffer,
262 KeyName->Buffer,
263 BytesToCopy);
264
265 /* Null terminate it */
266 ObjectNameInfo->Name.Buffer[BytesToCopy / sizeof(WCHAR)] = 0;
267 }
268 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
269 {
270 /* Get the status */
271 Status = _SEH2_GetExceptionCode();
272 }
273 _SEH2_END;
274
275 /* Free the buffer allocated by CmpConstructName */
276 ExFreePoolWithTag(KeyName, TAG_CM);
277
278 /* Return status */
279 return Status;
280 }
281
282 NTSTATUS
283 NTAPI
284 CmpInitHiveFromFile(IN PCUNICODE_STRING HiveName,
285 IN ULONG HiveFlags,
286 OUT PCMHIVE *Hive,
287 IN OUT PBOOLEAN New,
288 IN ULONG CheckFlags)
289 {
290 ULONG HiveDisposition, LogDisposition;
291 HANDLE FileHandle = NULL, LogHandle = NULL;
292 NTSTATUS Status;
293 ULONG Operation, FileType;
294 PCMHIVE NewHive;
295 PAGED_CODE();
296
297 /* Assume failure */
298 *Hive = NULL;
299
300 /* Open or create the hive files */
301 Status = CmpOpenHiveFiles(HiveName,
302 L".LOG",
303 &FileHandle,
304 &LogHandle,
305 &HiveDisposition,
306 &LogDisposition,
307 *New,
308 FALSE,
309 TRUE,
310 NULL);
311 if (!NT_SUCCESS(Status)) return Status;
312
313 /* Check if we have a log handle */
314 FileType = (LogHandle) ? HFILE_TYPE_LOG : HFILE_TYPE_PRIMARY;
315
316 /* Check if we created or opened the hive */
317 if (HiveDisposition == FILE_CREATED)
318 {
319 /* Do a create operation */
320 Operation = HINIT_CREATE;
321 *New = TRUE;
322 }
323 else
324 {
325 /* Open it as a file */
326 Operation = HINIT_FILE;
327 *New = FALSE;
328 }
329
330 /* Check if we're sharing hives */
331 if (CmpShareSystemHives)
332 {
333 /* Then force using the primary hive */
334 FileType = HFILE_TYPE_PRIMARY;
335 if (LogHandle)
336 {
337 /* Get rid of the log handle */
338 ZwClose(LogHandle);
339 LogHandle = NULL;
340 }
341 }
342
343 /* Check if we're too late */
344 if (HvShutdownComplete)
345 {
346 /* Fail */
347 ZwClose(FileHandle);
348 if (LogHandle) ZwClose(LogHandle);
349 return STATUS_TOO_LATE;
350 }
351
352 /* Initialize the hive */
353 Status = CmpInitializeHive(&NewHive,
354 Operation,
355 HiveFlags,
356 FileType,
357 NULL,
358 FileHandle,
359 LogHandle,
360 NULL,
361 HiveName,
362 CheckFlags);
363 if (!NT_SUCCESS(Status))
364 {
365 /* Fail */
366 ZwClose(FileHandle);
367 if (LogHandle) ZwClose(LogHandle);
368 return Status;
369 }
370
371 /* Success, return hive */
372 *Hive = NewHive;
373
374 /* Duplicate the hive name */
375 NewHive->FileFullPath.Buffer = ExAllocatePoolWithTag(PagedPool,
376 HiveName->Length,
377 TAG_CM);
378 if (NewHive->FileFullPath.Buffer)
379 {
380 /* Copy the string */
381 RtlCopyMemory(NewHive->FileFullPath.Buffer,
382 HiveName->Buffer,
383 HiveName->Length);
384 NewHive->FileFullPath.Length = HiveName->Length;
385 NewHive->FileFullPath.MaximumLength = HiveName->MaximumLength;
386 }
387
388 /* Return success */
389 return STATUS_SUCCESS;
390 }
391
392 NTSTATUS
393 NTAPI
394 INIT_FUNCTION
395 CmpSetSystemValues(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
396 {
397 OBJECT_ATTRIBUTES ObjectAttributes;
398 UNICODE_STRING KeyName, ValueName = { 0, 0, NULL };
399 HANDLE KeyHandle = NULL;
400 NTSTATUS Status;
401 ASSERT(LoaderBlock != NULL);
402
403 /* Setup attributes for loader options */
404 RtlInitUnicodeString(&KeyName,
405 L"\\REGISTRY\\MACHINE\\SYSTEM\\CurrentControlSet\\"
406 L"Control");
407 InitializeObjectAttributes(&ObjectAttributes,
408 &KeyName,
409 OBJ_CASE_INSENSITIVE,
410 NULL,
411 NULL);
412 Status = NtOpenKey(&KeyHandle, KEY_WRITE, &ObjectAttributes);
413 if (!NT_SUCCESS(Status)) goto Quickie;
414
415 /* Key opened, now write to the key */
416 RtlInitUnicodeString(&KeyName, L"SystemStartOptions");
417 Status = NtSetValueKey(KeyHandle,
418 &KeyName,
419 0,
420 REG_SZ,
421 CmpLoadOptions.Buffer,
422 CmpLoadOptions.Length);
423 if (!NT_SUCCESS(Status)) goto Quickie;
424
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,
429 &KeyName,
430 0,
431 REG_SZ,
432 ValueName.Buffer,
433 ValueName.Length);
434
435 Quickie:
436 /* Free the buffers */
437 RtlFreeUnicodeString(&ValueName);
438
439 /* Close the key and return */
440 if (KeyHandle) NtClose(KeyHandle);
441
442 /* Return the status */
443 return (ExpInTextModeSetup ? STATUS_SUCCESS : Status);
444 }
445
446 static
447 NTSTATUS
448 INIT_FUNCTION
449 CmpCreateHardwareProfile(HANDLE ControlSetHandle)
450 {
451 OBJECT_ATTRIBUTES ObjectAttributes;
452 UNICODE_STRING KeyName;
453 HANDLE ProfilesHandle = NULL;
454 HANDLE ProfileHandle = NULL;
455 ULONG Disposition;
456 NTSTATUS Status;
457
458 DPRINT("CmpCreateHardwareProfile()\n");
459
460 /* Create the Hardware Profiles key */
461 RtlInitUnicodeString(&KeyName, L"Hardware Profiles");
462 InitializeObjectAttributes(&ObjectAttributes,
463 &KeyName,
464 OBJ_CASE_INSENSITIVE,
465 ControlSetHandle,
466 NULL);
467 Status = NtCreateKey(&ProfilesHandle,
468 KEY_ALL_ACCESS,
469 &ObjectAttributes,
470 0,
471 NULL,
472 0,
473 &Disposition);
474 if (!NT_SUCCESS(Status))
475 {
476 DPRINT1("Creating the Hardware Profile key failed\n");
477 goto done;
478 }
479
480 /* Sanity check */
481 ASSERT(Disposition == REG_CREATED_NEW_KEY);
482
483 /* Create the 0000 key */
484 RtlInitUnicodeString(&KeyName, L"0000");
485 InitializeObjectAttributes(&ObjectAttributes,
486 &KeyName,
487 OBJ_CASE_INSENSITIVE,
488 ProfilesHandle,
489 NULL);
490 Status = NtCreateKey(&ProfileHandle,
491 KEY_ALL_ACCESS,
492 &ObjectAttributes,
493 0,
494 NULL,
495 0,
496 &Disposition);
497 if (!NT_SUCCESS(Status))
498 {
499 DPRINT1("Creating the Hardware Profile\\0000 key failed\n");
500 goto done;
501 }
502
503 /* Sanity check */
504 ASSERT(Disposition == REG_CREATED_NEW_KEY);
505
506 done:
507 if (ProfilesHandle)
508 NtClose(ProfilesHandle);
509
510 if (ProfileHandle)
511 NtClose(ProfileHandle);
512
513 DPRINT("CmpCreateHardwareProfile() done\n");
514
515 return Status;
516 }
517
518 NTSTATUS
519 NTAPI
520 INIT_FUNCTION
521 CmpCreateControlSet(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
522 {
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;
530 CHAR Buffer[128];
531 WCHAR UnicodeBuffer[128];
532 HANDLE SelectHandle, KeyHandle, ConfigHandle = NULL, ProfileHandle = NULL;
533 HANDLE ParentHandle = NULL;
534 ULONG ControlSet, HwProfile;
535 ANSI_STRING TempString;
536 NTSTATUS Status;
537 ULONG ResultLength, Disposition;
538 PLOADER_PARAMETER_EXTENSION LoaderExtension;
539 PAGED_CODE();
540
541 /* Open the select key */
542 InitializeObjectAttributes(&ObjectAttributes,
543 &SelectName,
544 OBJ_CASE_INSENSITIVE,
545 NULL,
546 NULL);
547 Status = NtOpenKey(&SelectHandle, KEY_READ, &ObjectAttributes);
548 if (!NT_SUCCESS(Status))
549 {
550 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
551 if (!LoaderBlock->RegistryBase)
552 {
553 /* Build the ControlSet001 key */
554 RtlInitUnicodeString(&KeyName,
555 L"\\Registry\\Machine\\System\\ControlSet001");
556 InitializeObjectAttributes(&ObjectAttributes,
557 &KeyName,
558 OBJ_CASE_INSENSITIVE,
559 NULL,
560 NULL);
561 Status = NtCreateKey(&KeyHandle,
562 KEY_ALL_ACCESS,
563 &ObjectAttributes,
564 0,
565 NULL,
566 0,
567 &Disposition);
568 if (!NT_SUCCESS(Status)) return Status;
569
570 /* Create the Hardware Profile keys */
571 Status = CmpCreateHardwareProfile(KeyHandle);
572 if (!NT_SUCCESS(Status))
573 return Status;
574
575 /* Don't need the handle */
576 ZwClose(KeyHandle);
577
578 /* Use hard-coded setting */
579 ControlSet = 1;
580 goto UseSet;
581 }
582
583 /* Fail for real boots */
584 return Status;
585 }
586
587 /* Open the current value */
588 RtlInitUnicodeString(&KeyName, L"Current");
589 Status = NtQueryValueKey(SelectHandle,
590 &KeyName,
591 KeyValueFullInformation,
592 ValueInfoBuffer,
593 sizeof(ValueInfoBuffer),
594 &ResultLength);
595 NtClose(SelectHandle);
596 if (!NT_SUCCESS(Status)) return Status;
597
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);
601
602 /* Create the current control set key */
603 UseSet:
604 RtlInitUnicodeString(&KeyName,
605 L"\\Registry\\Machine\\System\\CurrentControlSet");
606 InitializeObjectAttributes(&ObjectAttributes,
607 &KeyName,
608 OBJ_CASE_INSENSITIVE,
609 NULL,
610 NULL);
611 Status = NtCreateKey(&KeyHandle,
612 KEY_CREATE_LINK,
613 &ObjectAttributes,
614 0,
615 NULL,
616 REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK,
617 &Disposition);
618 if (!NT_SUCCESS(Status)) return Status;
619
620 /* Sanity check */
621 ASSERT(Disposition == REG_CREATED_NEW_KEY);
622
623 /* Initialize the symbolic link name */
624 sprintf(Buffer,
625 "\\Registry\\Machine\\System\\ControlSet%03ld",
626 ControlSet);
627 RtlInitAnsiString(&TempString, Buffer);
628
629 /* Create a Unicode string out of it */
630 KeyName.MaximumLength = sizeof(UnicodeBuffer);
631 KeyName.Buffer = UnicodeBuffer;
632 Status = RtlAnsiStringToUnicodeString(&KeyName, &TempString, FALSE);
633
634 /* Set the value */
635 Status = NtSetValueKey(KeyHandle,
636 &CmSymbolicLinkValueName,
637 0,
638 REG_LINK,
639 KeyName.Buffer,
640 KeyName.Length);
641 if (!NT_SUCCESS(Status)) return Status;
642
643 /* Get the configuration database key */
644 InitializeObjectAttributes(&ObjectAttributes,
645 &ConfigName,
646 OBJ_CASE_INSENSITIVE,
647 KeyHandle,
648 NULL);
649 Status = NtOpenKey(&ConfigHandle, KEY_READ, &ObjectAttributes);
650 NtClose(KeyHandle);
651
652 /* Check if we don't have one */
653 if (!NT_SUCCESS(Status))
654 {
655 /* Cleanup and exit */
656 ConfigHandle = 0;
657 goto Cleanup;
658 }
659
660 /* ReactOS Hack: Hard-code current to 001 for SetupLdr */
661 if (!LoaderBlock->RegistryBase)
662 {
663 HwProfile = 0;
664 }
665 else
666 {
667 /* Now get the current config */
668 RtlInitUnicodeString(&KeyName, L"CurrentConfig");
669 Status = NtQueryValueKey(ConfigHandle,
670 &KeyName,
671 KeyValueFullInformation,
672 ValueInfoBuffer,
673 sizeof(ValueInfoBuffer),
674 &ResultLength);
675
676 /* Set pointer to buffer */
677 ValueInfo = (PKEY_VALUE_FULL_INFORMATION)ValueInfoBuffer;
678
679 /* Check if we failed or got a non DWORD-value */
680 if (!(NT_SUCCESS(Status)) || (ValueInfo->Type != REG_DWORD)) goto Cleanup;
681
682 /* Get the hadware profile */
683 HwProfile = *(PULONG)((PUCHAR)ValueInfo + ValueInfo->DataOffset);
684 }
685
686 /* Open the hardware profile key */
687 RtlInitUnicodeString(&KeyName,
688 L"\\Registry\\Machine\\System\\CurrentControlSet"
689 L"\\Hardware Profiles");
690 InitializeObjectAttributes(&ObjectAttributes,
691 &KeyName,
692 OBJ_CASE_INSENSITIVE,
693 NULL,
694 NULL);
695 Status = NtOpenKey(&ParentHandle, KEY_READ, &ObjectAttributes);
696 if (!NT_SUCCESS(Status))
697 {
698 /* Exit and clean up */
699 ParentHandle = 0;
700 goto Cleanup;
701 }
702
703 /* Build the profile name */
704 sprintf(Buffer, "%04ld", HwProfile);
705 RtlInitAnsiString(&TempString, Buffer);
706
707 /* Convert it to Unicode */
708 KeyName.MaximumLength = sizeof(UnicodeBuffer);
709 KeyName.Buffer = UnicodeBuffer;
710 Status = RtlAnsiStringToUnicodeString(&KeyName,
711 &TempString,
712 FALSE);
713 ASSERT(Status == STATUS_SUCCESS);
714
715 /* Open the associated key */
716 InitializeObjectAttributes(&ObjectAttributes,
717 &KeyName,
718 OBJ_CASE_INSENSITIVE,
719 ParentHandle,
720 NULL);
721 Status = NtOpenKey(&ProfileHandle,
722 KEY_READ | KEY_WRITE,
723 &ObjectAttributes);
724 if (!NT_SUCCESS (Status))
725 {
726 /* Cleanup and exit */
727 ProfileHandle = 0;
728 goto Cleanup;
729 }
730
731 /* Check if we have a loader block extension */
732 LoaderExtension = LoaderBlock->Extension;
733 if (LoaderExtension)
734 {
735 DPRINT("ReactOS doesn't support NTLDR Profiles yet!\n");
736 }
737
738 /* Create the current hardware profile key */
739 RtlInitUnicodeString(&KeyName,
740 L"\\Registry\\Machine\\System\\CurrentControlSet\\"
741 L"Hardware Profiles\\Current");
742 InitializeObjectAttributes(&ObjectAttributes,
743 &KeyName,
744 OBJ_CASE_INSENSITIVE,
745 NULL,
746 NULL);
747 Status = NtCreateKey(&KeyHandle,
748 KEY_CREATE_LINK,
749 &ObjectAttributes,
750 0,
751 NULL,
752 REG_OPTION_VOLATILE | REG_OPTION_CREATE_LINK,
753 &Disposition);
754 if (NT_SUCCESS(Status))
755 {
756 /* Sanity check */
757 ASSERT(Disposition == REG_CREATED_NEW_KEY);
758
759 /* Create the profile name */
760 sprintf(Buffer,
761 "\\Registry\\Machine\\System\\CurrentControlSet\\"
762 "Hardware Profiles\\%04ld",
763 HwProfile);
764 RtlInitAnsiString(&TempString, Buffer);
765
766 /* Convert it to Unicode */
767 KeyName.MaximumLength = sizeof(UnicodeBuffer);
768 KeyName.Buffer = UnicodeBuffer;
769 Status = RtlAnsiStringToUnicodeString(&KeyName,
770 &TempString,
771 FALSE);
772 ASSERT(STATUS_SUCCESS == Status);
773
774 /* Set it */
775 Status = NtSetValueKey(KeyHandle,
776 &CmSymbolicLinkValueName,
777 0,
778 REG_LINK,
779 KeyName.Buffer,
780 KeyName.Length);
781 NtClose(KeyHandle);
782 }
783
784 /* Close every opened handle */
785 Cleanup:
786 if (ConfigHandle) NtClose(ConfigHandle);
787 if (ProfileHandle) NtClose(ProfileHandle);
788 if (ParentHandle) NtClose(ParentHandle);
789
790 DPRINT("CmpCreateControlSet() done\n");
791
792 /* Return success */
793 return STATUS_SUCCESS;
794 }
795
796 NTSTATUS
797 NTAPI
798 CmpLinkHiveToMaster(IN PUNICODE_STRING LinkName,
799 IN HANDLE RootDirectory,
800 IN PCMHIVE RegistryHive,
801 IN BOOLEAN Allocate,
802 IN PSECURITY_DESCRIPTOR SecurityDescriptor)
803 {
804 OBJECT_ATTRIBUTES ObjectAttributes;
805 NTSTATUS Status;
806 CM_PARSE_CONTEXT ParseContext = {0};
807 HANDLE KeyHandle;
808 PCM_KEY_BODY KeyBody;
809 PAGED_CODE();
810
811 /* Setup the object attributes */
812 InitializeObjectAttributes(&ObjectAttributes,
813 LinkName,
814 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
815 RootDirectory,
816 SecurityDescriptor);
817
818 /* Setup the parse context */
819 ParseContext.CreateLink = TRUE;
820 ParseContext.CreateOperation = TRUE;
821 ParseContext.ChildHive.KeyHive = &RegistryHive->Hive;
822
823 /* Check if we have a root keycell or if we need to create it */
824 if (Allocate)
825 {
826 /* Create it */
827 ParseContext.ChildHive.KeyCell = HCELL_NIL;
828 }
829 else
830 {
831 /* We have one */
832 ParseContext.ChildHive.KeyCell = RegistryHive->Hive.BaseBlock->RootCell;
833 }
834
835 /* Create the link node */
836 Status = ObOpenObjectByName(&ObjectAttributes,
837 CmpKeyObjectType,
838 KernelMode,
839 NULL,
840 KEY_READ | KEY_WRITE,
841 (PVOID)&ParseContext,
842 &KeyHandle);
843 if (!NT_SUCCESS(Status)) return Status;
844
845 /* Mark the hive as clean */
846 RegistryHive->Hive.DirtyFlag = FALSE;
847
848 /* ReactOS Hack: Keep alive */
849 Status = ObReferenceObjectByHandle(KeyHandle,
850 0,
851 CmpKeyObjectType,
852 KernelMode,
853 (PVOID*)&KeyBody,
854 NULL);
855 ASSERT(NT_SUCCESS(Status));
856
857 /* Close the extra handle */
858 ZwClose(KeyHandle);
859 return STATUS_SUCCESS;
860 }
861
862 BOOLEAN
863 NTAPI
864 INIT_FUNCTION
865 CmpInitializeSystemHive(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
866 {
867 PVOID HiveBase;
868 ANSI_STRING LoadString;
869 PVOID Buffer;
870 ULONG Length;
871 NTSTATUS Status;
872 BOOLEAN Allocate;
873 UNICODE_STRING KeyName;
874 PCMHIVE SystemHive = NULL;
875 UNICODE_STRING HiveName = RTL_CONSTANT_STRING(L"SYSTEM");
876 PSECURITY_DESCRIPTOR SecurityDescriptor;
877 PAGED_CODE();
878
879 /* Setup the ansi string */
880 RtlInitAnsiString(&LoadString, LoaderBlock->LoadOptions);
881
882 /* Allocate the unicode buffer */
883 Length = LoadString.Length * sizeof(WCHAR) + sizeof(UNICODE_NULL);
884 Buffer = ExAllocatePoolWithTag(PagedPool, Length, TAG_CM);
885 if (!Buffer)
886 {
887 /* Fail */
888 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO, 3, 1, (ULONG_PTR)LoaderBlock, 0);
889 }
890
891 /* Setup the unicode string */
892 RtlInitEmptyUnicodeString(&CmpLoadOptions, Buffer, (USHORT)Length);
893
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);
898
899 /* Get the System Hive base address */
900 HiveBase = LoaderBlock->RegistryBase;
901 if (HiveBase)
902 {
903 /* Import it */
904 Status = CmpInitializeHive(&SystemHive,
905 HINIT_MEMORY,
906 HIVE_NOLAZYFLUSH,
907 HFILE_TYPE_LOG,
908 HiveBase,
909 NULL,
910 NULL,
911 NULL,
912 &HiveName,
913 2);
914 if (!NT_SUCCESS(Status)) return FALSE;
915
916 /* Set the hive filename */
917 RtlCreateUnicodeString(&SystemHive->FileFullPath,
918 L"\\SystemRoot\\System32\\Config\\SYSTEM");
919
920 /* We imported, no need to create a new hive */
921 Allocate = FALSE;
922
923 /* Manually set the hive as volatile, if in Live CD mode */
924 if (CmpShareSystemHives) SystemHive->Hive.HiveFlags = HIVE_VOLATILE;
925 }
926 else
927 {
928 /* Create it */
929 Status = CmpInitializeHive(&SystemHive,
930 HINIT_CREATE,
931 HIVE_NOLAZYFLUSH,
932 HFILE_TYPE_LOG,
933 NULL,
934 NULL,
935 NULL,
936 NULL,
937 &HiveName,
938 0);
939 if (!NT_SUCCESS(Status)) return FALSE;
940
941 /* Set the hive filename */
942 RtlCreateUnicodeString(&SystemHive->FileFullPath,
943 L"\\SystemRoot\\System32\\Config\\SYSTEM");
944
945 /* Tell CmpLinkHiveToMaster to allocate a hive */
946 Allocate = TRUE;
947 }
948
949 /* Save the boot type */
950 CmpBootType = SystemHive->Hive.BaseBlock->BootType;
951
952 /* Are we in self-healing mode? */
953 if (!CmSelfHeal)
954 {
955 /* Disable self-healing internally and check if boot type wanted it */
956 CmpSelfHeal = FALSE;
957 if (CmpBootType & 4)
958 {
959 /* We're disabled, so bugcheck */
960 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO,
961 3,
962 3,
963 (ULONG_PTR)SystemHive,
964 0);
965 }
966 }
967
968 /* Create the default security descriptor */
969 SecurityDescriptor = CmpHiveRootSecurityDescriptor();
970
971 /* Attach it to the system key */
972 RtlInitUnicodeString(&KeyName, L"\\Registry\\Machine\\SYSTEM");
973 Status = CmpLinkHiveToMaster(&KeyName,
974 NULL,
975 SystemHive,
976 Allocate,
977 SecurityDescriptor);
978
979 /* Free the security descriptor */
980 ExFreePoolWithTag(SecurityDescriptor, TAG_CMSD);
981 if (!NT_SUCCESS(Status)) return FALSE;
982
983 /* Add the hive to the hive list */
984 CmpMachineHiveList[3].CmHive = SystemHive;
985
986 /* Success! */
987 return TRUE;
988 }
989
990 NTSTATUS
991 NTAPI
992 INIT_FUNCTION
993 CmpCreateObjectTypes(VOID)
994 {
995 OBJECT_TYPE_INITIALIZER ObjectTypeInitializer;
996 UNICODE_STRING Name;
997 GENERIC_MAPPING CmpKeyMapping = {KEY_READ,
998 KEY_WRITE,
999 KEY_EXECUTE,
1000 KEY_ALL_ACCESS};
1001 PAGED_CODE();
1002
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;
1019
1020 /* Create it */
1021 return ObCreateObjectType(&Name, &ObjectTypeInitializer, NULL, &CmpKeyObjectType);
1022 }
1023
1024 BOOLEAN
1025 NTAPI
1026 INIT_FUNCTION
1027 CmpCreateRootNode(IN PHHIVE Hive,
1028 IN PCWSTR Name,
1029 OUT PHCELL_INDEX Index)
1030 {
1031 UNICODE_STRING KeyName;
1032 PCM_KEY_NODE KeyCell;
1033 PAGED_CODE();
1034
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),
1040 Stable,
1041 HCELL_NIL);
1042 if (*Index == HCELL_NIL) return FALSE;
1043
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;
1048
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;
1067
1068 /* Copy the name (this will also set the length) */
1069 KeyCell->NameLength = CmpCopyName(Hive, KeyCell->Name, &KeyName);
1070
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;
1074
1075 /* Return success */
1076 HvReleaseCell(Hive, *Index);
1077 return TRUE;
1078 }
1079
1080 BOOLEAN
1081 NTAPI
1082 INIT_FUNCTION
1083 CmpCreateRegistryRoot(VOID)
1084 {
1085 UNICODE_STRING KeyName;
1086 OBJECT_ATTRIBUTES ObjectAttributes;
1087 PCM_KEY_BODY RootKey;
1088 HCELL_INDEX RootIndex;
1089 NTSTATUS Status;
1090 PCM_KEY_NODE KeyCell;
1091 PSECURITY_DESCRIPTOR SecurityDescriptor;
1092 PCM_KEY_CONTROL_BLOCK Kcb;
1093 PAGED_CODE();
1094
1095 /* Setup the root node */
1096 if (!CmpCreateRootNode(&CmiVolatileHive->Hive, L"REGISTRY", &RootIndex))
1097 {
1098 /* We failed */
1099 return FALSE;
1100 }
1101
1102 /* Create '\Registry' key. */
1103 RtlInitUnicodeString(&KeyName, L"\\REGISTRY");
1104 SecurityDescriptor = CmpHiveRootSecurityDescriptor();
1105 InitializeObjectAttributes(&ObjectAttributes,
1106 &KeyName,
1107 OBJ_CASE_INSENSITIVE,
1108 NULL,
1109 SecurityDescriptor);
1110 Status = ObCreateObject(KernelMode,
1111 CmpKeyObjectType,
1112 &ObjectAttributes,
1113 KernelMode,
1114 NULL,
1115 sizeof(CM_KEY_BODY),
1116 0,
1117 0,
1118 (PVOID*)&RootKey);
1119 ExFreePoolWithTag(SecurityDescriptor, TAG_CMSD);
1120 if (!NT_SUCCESS(Status)) return FALSE;
1121
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;
1126
1127 /* Create the KCB */
1128 RtlInitUnicodeString(&KeyName, L"\\REGISTRY");
1129 Kcb = CmpCreateKeyControlBlock(&CmiVolatileHive->Hive,
1130 RootIndex,
1131 KeyCell,
1132 NULL,
1133 0,
1134 &KeyName);
1135 if (!Kcb)
1136 {
1137 ObDereferenceObject(RootKey);
1138 return FALSE;
1139 }
1140
1141 /* Initialize the object */
1142 RootKey->KeyControlBlock = Kcb;
1143 RootKey->Type = CM_KEY_BODY_TYPE;
1144 RootKey->NotifyBlock = NULL;
1145 RootKey->ProcessID = PsGetCurrentProcessId();
1146
1147 /* Link with KCB */
1148 EnlistKeyBodyWithKCB(RootKey, 0);
1149
1150 /* Insert the key into the namespace */
1151 Status = ObInsertObject(RootKey,
1152 NULL,
1153 KEY_ALL_ACCESS,
1154 0,
1155 NULL,
1156 &CmpRegistryRootHandle);
1157 if (!NT_SUCCESS(Status))
1158 {
1159 ObDereferenceObject(RootKey);
1160 return FALSE;
1161 }
1162
1163 /* Reference the key again so that we never lose it */
1164 Status = ObReferenceObjectByHandle(CmpRegistryRootHandle,
1165 KEY_READ,
1166 NULL,
1167 KernelMode,
1168 (PVOID*)&RootKey,
1169 NULL);
1170 if (!NT_SUCCESS(Status))
1171 {
1172 ObDereferenceObject(RootKey);
1173 return FALSE;
1174 }
1175
1176 /* Completely sucessful */
1177 return TRUE;
1178 }
1179
1180 NTSTATUS
1181 NTAPI
1182 CmpGetRegistryPath(OUT PWCHAR ConfigPath)
1183 {
1184 OBJECT_ATTRIBUTES ObjectAttributes;
1185 NTSTATUS Status;
1186 HANDLE KeyHandle;
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;
1191
1192 /* Check if we are booted in setup */
1193 if (ExpInTextModeSetup)
1194 {
1195 DPRINT1("CmpGetRegistryPath TextMode setup HACK!!\n");
1196
1197 /* Setup the object attributes */
1198 InitializeObjectAttributes(&ObjectAttributes,
1199 &KeyName,
1200 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
1201 NULL,
1202 NULL);
1203 /* Open the key */
1204 Status = ZwOpenKey(&KeyHandle,
1205 KEY_ALL_ACCESS,
1206 &ObjectAttributes);
1207 if (!NT_SUCCESS(Status)) return Status;
1208
1209 /* Allocate the buffer */
1210 BufferSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 4096;
1211 ValueInfo = ExAllocatePoolWithTag(PagedPool, BufferSize, TAG_CM);
1212 if (!ValueInfo)
1213 {
1214 /* Fail */
1215 ZwClose(KeyHandle);
1216 return STATUS_INSUFFICIENT_RESOURCES;
1217 }
1218
1219 /* Query the value */
1220 Status = ZwQueryValueKey(KeyHandle,
1221 &ValueName,
1222 KeyValuePartialInformation,
1223 ValueInfo,
1224 BufferSize,
1225 &ResultSize);
1226 ZwClose(KeyHandle);
1227 if (!NT_SUCCESS(Status))
1228 {
1229 /* Fail */
1230 ExFreePoolWithTag(ValueInfo, TAG_CM);
1231 return Status;
1232 }
1233
1234 /* Copy the config path and null-terminate it */
1235 RtlCopyMemory(ConfigPath,
1236 ValueInfo->Data,
1237 ValueInfo->DataLength);
1238 ConfigPath[ValueInfo->DataLength / sizeof(WCHAR)] = UNICODE_NULL;
1239 ExFreePoolWithTag(ValueInfo, TAG_CM);
1240 }
1241 else
1242 {
1243 /* Just use default path */
1244 wcscpy(ConfigPath, L"\\SystemRoot");
1245 }
1246
1247 /* Add registry path */
1248 wcscat(ConfigPath, L"\\System32\\Config\\");
1249
1250 DPRINT1("CmpGetRegistryPath: ConfigPath = '%S'\n", ConfigPath);
1251
1252 /* Done */
1253 return STATUS_SUCCESS;
1254 }
1255
1256 VOID
1257 NTAPI
1258 CmpLoadHiveThread(IN PVOID StartContext)
1259 {
1260 WCHAR FileBuffer[MAX_PATH], RegBuffer[MAX_PATH], ConfigPath[MAX_PATH];
1261 UNICODE_STRING TempName, FileName, RegName;
1262 ULONG i, ErrorResponse, WorkerCount, Length;
1263 USHORT FileStart;
1264 ULONG PrimaryDisposition, SecondaryDisposition, ClusterSize;
1265 PCMHIVE CmHive;
1266 HANDLE PrimaryHandle = NULL, LogHandle = NULL;
1267 NTSTATUS Status = STATUS_SUCCESS;
1268 PVOID ErrorParameters;
1269 PAGED_CODE();
1270
1271 /* Get the hive index, make sure it makes sense */
1272 i = PtrToUlong(StartContext);
1273 ASSERT(CmpMachineHiveList[i].Name != NULL);
1274
1275 /* We were started */
1276 CmpMachineHiveList[i].ThreadStarted = TRUE;
1277
1278 /* Build the file name and registry name strings */
1279 RtlInitEmptyUnicodeString(&FileName, FileBuffer, sizeof(FileBuffer));
1280 RtlInitEmptyUnicodeString(&RegName, RegBuffer, sizeof(RegBuffer));
1281
1282 /* Now build the system root path */
1283 CmpGetRegistryPath(ConfigPath);
1284 RtlInitUnicodeString(&TempName, ConfigPath);
1285 RtlAppendUnicodeStringToString(&FileName, &TempName);
1286 FileStart = FileName.Length;
1287
1288 /* And build the registry root path */
1289 RtlInitUnicodeString(&TempName, L"\\REGISTRY\\");
1290 RtlAppendUnicodeStringToString(&RegName, &TempName);
1291
1292 /* Build the base name */
1293 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].BaseName);
1294 RtlAppendUnicodeStringToString(&RegName, &TempName);
1295
1296 /* Check if this is a child of the root */
1297 if (RegName.Buffer[RegName.Length / sizeof(WCHAR) - 1] == OBJ_NAME_PATH_SEPARATOR)
1298 {
1299 /* Then setup the whole name */
1300 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].Name);
1301 RtlAppendUnicodeStringToString(&RegName, &TempName);
1302 }
1303
1304 /* Now add the rest of the file name */
1305 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].Name);
1306 FileName.Length = FileStart;
1307 RtlAppendUnicodeStringToString(&FileName, &TempName);
1308 if (!CmpMachineHiveList[i].CmHive)
1309 {
1310 /* We need to allocate a new hive structure */
1311 CmpMachineHiveList[i].Allocate = TRUE;
1312
1313 /* Load the hive file */
1314 Status = CmpInitHiveFromFile(&FileName,
1315 CmpMachineHiveList[i].HHiveFlags,
1316 &CmHive,
1317 &CmpMachineHiveList[i].Allocate,
1318 0);
1319 if (!(NT_SUCCESS(Status)) ||
1320 (!(CmHive->FileHandles[HFILE_TYPE_LOG]) && !(CmpMiniNTBoot))) // HACK
1321 {
1322 /* We failed or couldn't get a log file, raise a hard error */
1323 ErrorParameters = &FileName;
1324 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE,
1325 1,
1326 1,
1327 (PULONG_PTR)&ErrorParameters,
1328 OptionOk,
1329 &ErrorResponse);
1330 }
1331
1332 /* Set the hive flags and newly allocated hive pointer */
1333 CmHive->Flags = CmpMachineHiveList[i].CmHiveFlags;
1334 CmpMachineHiveList[i].CmHive2 = CmHive;
1335 }
1336 else
1337 {
1338 /* We already have a hive, is it volatile? */
1339 CmHive = CmpMachineHiveList[i].CmHive;
1340 if (!(CmHive->Hive.HiveFlags & HIVE_VOLATILE))
1341 {
1342 /* It's now, open the hive file and log */
1343 Status = CmpOpenHiveFiles(&FileName,
1344 L".LOG",
1345 &PrimaryHandle,
1346 &LogHandle,
1347 &PrimaryDisposition,
1348 &SecondaryDisposition,
1349 TRUE,
1350 TRUE,
1351 FALSE,
1352 &ClusterSize);
1353 if (!(NT_SUCCESS(Status)) || !(LogHandle))
1354 {
1355 /* Couldn't open the hive or its log file, raise a hard error */
1356 ErrorParameters = &FileName;
1357 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE,
1358 1,
1359 1,
1360 (PULONG_PTR)&ErrorParameters,
1361 OptionOk,
1362 &ErrorResponse);
1363
1364 /* And bugcheck for posterity's sake */
1365 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO, 9, 0, i, Status);
1366 }
1367
1368 /* Save the file handles. This should remove our sync hacks */
1369 CmHive->FileHandles[HFILE_TYPE_LOG] = LogHandle;
1370 CmHive->FileHandles[HFILE_TYPE_PRIMARY] = PrimaryHandle;
1371
1372 /* Allow lazy flushing since the handles are there -- remove sync hacks */
1373 //ASSERT(CmHive->Hive.HiveFlags & HIVE_NOLAZYFLUSH);
1374 CmHive->Hive.HiveFlags &= ~HIVE_NOLAZYFLUSH;
1375
1376 /* Get the real size of the hive */
1377 Length = CmHive->Hive.Storage[Stable].Length + HBLOCK_SIZE;
1378
1379 /* Check if the cluster size doesn't match */
1380 if (CmHive->Hive.Cluster != ClusterSize) ASSERT(FALSE);
1381
1382 /* Set the file size */
1383 DPRINT("FIXME: Should set file size: %lx\n", Length);
1384 //if (!CmpFileSetSize((PHHIVE)CmHive, HFILE_TYPE_PRIMARY, Length, Length))
1385 {
1386 /* This shouldn't fail */
1387 //ASSERT(FALSE);
1388 }
1389
1390 /* Another thing we don't support is NTLDR-recovery */
1391 if (CmHive->Hive.BaseBlock->BootRecover) ASSERT(FALSE);
1392
1393 /* Finally, set our allocated hive to the same hive we've had */
1394 CmpMachineHiveList[i].CmHive2 = CmHive;
1395 ASSERT(CmpMachineHiveList[i].CmHive == CmpMachineHiveList[i].CmHive2);
1396 }
1397 }
1398
1399 /* We're done */
1400 CmpMachineHiveList[i].ThreadFinished = TRUE;
1401
1402 /* Check if we're the last worker */
1403 WorkerCount = InterlockedIncrement(&CmpLoadWorkerIncrement);
1404 if (WorkerCount == CM_NUMBER_OF_MACHINE_HIVES)
1405 {
1406 /* Signal the event */
1407 KeSetEvent(&CmpLoadWorkerEvent, 0, FALSE);
1408 }
1409
1410 /* Kill the thread */
1411 PsTerminateSystemThread(Status);
1412 }
1413
1414 VOID
1415 NTAPI
1416 CmpInitializeHiveList(IN USHORT Flag)
1417 {
1418 WCHAR FileBuffer[MAX_PATH], RegBuffer[MAX_PATH], ConfigPath[MAX_PATH];
1419 UNICODE_STRING TempName, FileName, RegName;
1420 HANDLE Thread;
1421 NTSTATUS Status;
1422 ULONG i;
1423 USHORT RegStart;
1424 PSECURITY_DESCRIPTOR SecurityDescriptor;
1425 PAGED_CODE();
1426
1427 /* Allow writing for now */
1428 CmpNoWrite = FALSE;
1429
1430 /* Build the file name and registry name strings */
1431 RtlInitEmptyUnicodeString(&FileName, FileBuffer, sizeof(FileBuffer));
1432 RtlInitEmptyUnicodeString(&RegName, RegBuffer, sizeof(RegBuffer));
1433
1434 /* Now build the system root path */
1435 CmpGetRegistryPath(ConfigPath);
1436 RtlInitUnicodeString(&TempName, ConfigPath);
1437 RtlAppendUnicodeStringToString(&FileName, &TempName);
1438
1439 /* And build the registry root path */
1440 RtlInitUnicodeString(&TempName, L"\\REGISTRY\\");
1441 RtlAppendUnicodeStringToString(&RegName, &TempName);
1442 RegStart = RegName.Length;
1443
1444 /* Setup the event to synchronize workers */
1445 KeInitializeEvent(&CmpLoadWorkerEvent, SynchronizationEvent, FALSE);
1446
1447 /* Enter special boot condition */
1448 CmpSpecialBootCondition = TRUE;
1449
1450 /* Create the SD for the root hives */
1451 SecurityDescriptor = CmpHiveRootSecurityDescriptor();
1452
1453 /* Loop every hive we care about */
1454 for (i = 0; i < CM_NUMBER_OF_MACHINE_HIVES; i++)
1455 {
1456 /* Make sure the list is setup */
1457 ASSERT(CmpMachineHiveList[i].Name != NULL);
1458
1459 /* Create a thread to handle this hive */
1460 Status = PsCreateSystemThread(&Thread,
1461 THREAD_ALL_ACCESS,
1462 NULL,
1463 0,
1464 NULL,
1465 CmpLoadHiveThread,
1466 UlongToPtr(i));
1467 if (NT_SUCCESS(Status))
1468 {
1469 /* We don't care about the handle -- the thread self-terminates */
1470 ZwClose(Thread);
1471 }
1472 else
1473 {
1474 /* Can't imagine this happening */
1475 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO, 9, 3, i, Status);
1476 }
1477 }
1478
1479 /* Make sure we've reached the end of the list */
1480 ASSERT(CmpMachineHiveList[i].Name == NULL);
1481
1482 /* Wait for hive loading to finish */
1483 KeWaitForSingleObject(&CmpLoadWorkerEvent,
1484 Executive,
1485 KernelMode,
1486 FALSE,
1487 NULL);
1488
1489 /* Exit the special boot condition and make sure all workers completed */
1490 CmpSpecialBootCondition = FALSE;
1491 ASSERT(CmpLoadWorkerIncrement == CM_NUMBER_OF_MACHINE_HIVES);
1492
1493 /* Loop hives again */
1494 for (i = 0; i < CM_NUMBER_OF_MACHINE_HIVES; i++)
1495 {
1496 /* Make sure the thread ran and finished */
1497 ASSERT(CmpMachineHiveList[i].ThreadFinished == TRUE);
1498 ASSERT(CmpMachineHiveList[i].ThreadStarted == TRUE);
1499
1500 /* Check if this was a new hive */
1501 if (!CmpMachineHiveList[i].CmHive)
1502 {
1503 /* Make sure we allocated something */
1504 ASSERT(CmpMachineHiveList[i].CmHive2 != NULL);
1505
1506 /* Build the base name */
1507 RegName.Length = RegStart;
1508 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].BaseName);
1509 RtlAppendUnicodeStringToString(&RegName, &TempName);
1510
1511 /* Check if this is a child of the root */
1512 if (RegName.Buffer[RegName.Length / sizeof(WCHAR) - 1] == OBJ_NAME_PATH_SEPARATOR)
1513 {
1514 /* Then setup the whole name */
1515 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].Name);
1516 RtlAppendUnicodeStringToString(&RegName, &TempName);
1517 }
1518
1519 /* Now link the hive to its master */
1520 Status = CmpLinkHiveToMaster(&RegName,
1521 NULL,
1522 CmpMachineHiveList[i].CmHive2,
1523 CmpMachineHiveList[i].Allocate,
1524 SecurityDescriptor);
1525 if (Status != STATUS_SUCCESS)
1526 {
1527 /* Linking needs to work */
1528 KeBugCheckEx(CONFIG_LIST_FAILED, 11, Status, i, (ULONG_PTR)&RegName);
1529 }
1530
1531 /* Check if we had to allocate a new hive */
1532 if (CmpMachineHiveList[i].Allocate)
1533 {
1534 /* Sync the new hive */
1535 //HvSyncHive((PHHIVE)(CmpMachineHiveList[i].CmHive2));
1536 }
1537 }
1538
1539 /* Check if we created a new hive */
1540 if (CmpMachineHiveList[i].CmHive2)
1541 {
1542 /* Add to HiveList key */
1543 CmpAddToHiveFileList(CmpMachineHiveList[i].CmHive2);
1544 }
1545 }
1546
1547 /* Get rid of the SD */
1548 ExFreePoolWithTag(SecurityDescriptor, TAG_CMSD);
1549
1550 /* Link SECURITY to SAM */
1551 CmpLinkKeyToHive(L"\\Registry\\Machine\\Security\\SAM",
1552 L"\\Registry\\Machine\\SAM\\SAM");
1553
1554 /* Link S-1-5-18 to .Default */
1555 CmpNoVolatileCreates = FALSE;
1556 CmpLinkKeyToHive(L"\\Registry\\User\\S-1-5-18",
1557 L"\\Registry\\User\\.Default");
1558 CmpNoVolatileCreates = TRUE;
1559 }
1560
1561 BOOLEAN
1562 NTAPI
1563 INIT_FUNCTION
1564 CmInitSystem1(VOID)
1565 {
1566 OBJECT_ATTRIBUTES ObjectAttributes;
1567 UNICODE_STRING KeyName;
1568 HANDLE KeyHandle;
1569 NTSTATUS Status;
1570 PCMHIVE HardwareHive;
1571 PSECURITY_DESCRIPTOR SecurityDescriptor;
1572 PAGED_CODE();
1573
1574 /* Check if this is PE-boot */
1575 if (InitIsWinPEMode)
1576 {
1577 /* Set registry to PE mode */
1578 CmpMiniNTBoot = TRUE;
1579 CmpShareSystemHives = TRUE;
1580 }
1581
1582 /* Initialize the hive list and lock */
1583 InitializeListHead(&CmpHiveListHead);
1584 ExInitializePushLock(&CmpHiveListHeadLock);
1585 ExInitializePushLock(&CmpLoadHiveLock);
1586
1587 /* Initialize registry lock */
1588 ExInitializeResourceLite(&CmpRegistryLock);
1589
1590 /* Initialize the cache */
1591 CmpInitializeCache();
1592
1593 /* Initialize allocation and delayed dereferencing */
1594 CmpInitCmPrivateAlloc();
1595 CmpInitCmPrivateDelayAlloc();
1596 CmpInitDelayDerefKCBEngine();
1597
1598 /* Initialize callbacks */
1599 CmpInitCallback();
1600
1601 /* Initialize self healing */
1602 KeInitializeGuardedMutex(&CmpSelfHealQueueLock);
1603 InitializeListHead(&CmpSelfHealQueueListHead);
1604
1605 /* Save the current process and lock the registry */
1606 CmpSystemProcess = PsGetCurrentProcess();
1607
1608 /* Create the key object types */
1609 Status = CmpCreateObjectTypes();
1610 if (!NT_SUCCESS(Status))
1611 {
1612 /* Bugcheck */
1613 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 1, Status, 0);
1614 }
1615
1616 /* Build the master hive */
1617 Status = CmpInitializeHive(&CmiVolatileHive,
1618 HINIT_CREATE,
1619 HIVE_VOLATILE,
1620 HFILE_TYPE_PRIMARY,
1621 NULL,
1622 NULL,
1623 NULL,
1624 NULL,
1625 NULL,
1626 0);
1627 if (!NT_SUCCESS(Status))
1628 {
1629 /* Bugcheck */
1630 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 2, Status, 0);
1631 }
1632
1633 /* Create the \REGISTRY key node */
1634 if (!CmpCreateRegistryRoot())
1635 {
1636 /* Bugcheck */
1637 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 3, 0, 0);
1638 }
1639
1640 /* Create the default security descriptor */
1641 SecurityDescriptor = CmpHiveRootSecurityDescriptor();
1642
1643 /* Create '\Registry\Machine' key. */
1644 RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\MACHINE");
1645 InitializeObjectAttributes(&ObjectAttributes,
1646 &KeyName,
1647 OBJ_CASE_INSENSITIVE,
1648 NULL,
1649 SecurityDescriptor);
1650 Status = NtCreateKey(&KeyHandle,
1651 KEY_READ | KEY_WRITE,
1652 &ObjectAttributes,
1653 0,
1654 NULL,
1655 0,
1656 NULL);
1657 if (!NT_SUCCESS(Status))
1658 {
1659 /* Bugcheck */
1660 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 5, Status, 0);
1661 }
1662
1663 /* Close the handle */
1664 NtClose(KeyHandle);
1665
1666 /* Create '\Registry\User' key. */
1667 RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\USER");
1668 InitializeObjectAttributes(&ObjectAttributes,
1669 &KeyName,
1670 OBJ_CASE_INSENSITIVE,
1671 NULL,
1672 SecurityDescriptor);
1673 Status = NtCreateKey(&KeyHandle,
1674 KEY_READ | KEY_WRITE,
1675 &ObjectAttributes,
1676 0,
1677 NULL,
1678 0,
1679 NULL);
1680 if (!NT_SUCCESS(Status))
1681 {
1682 /* Bugcheck */
1683 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 6, Status, 0);
1684 }
1685
1686 /* Close the handle */
1687 NtClose(KeyHandle);
1688
1689 /* After this point, do not allow creating keys in the master hive */
1690 CmpNoVolatileCreates = TRUE;
1691
1692 /* Initialize the system hive */
1693 if (!CmpInitializeSystemHive(KeLoaderBlock))
1694 {
1695 /* Bugcheck */
1696 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 7, 0, 0);
1697 }
1698
1699 /* Create the 'CurrentControlSet' link. */
1700 Status = CmpCreateControlSet(KeLoaderBlock);
1701 if (!NT_SUCCESS(Status))
1702 {
1703 /* Bugcheck */
1704 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 8, Status, 0);
1705 }
1706
1707 /* Create the hardware hive */
1708 Status = CmpInitializeHive(&HardwareHive,
1709 HINIT_CREATE,
1710 HIVE_VOLATILE,
1711 HFILE_TYPE_PRIMARY,
1712 NULL,
1713 NULL,
1714 NULL,
1715 NULL,
1716 NULL,
1717 0);
1718 if (!NT_SUCCESS(Status))
1719 {
1720 /* Bugcheck */
1721 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 11, Status, 0);
1722 }
1723
1724 /* Add the hive to the hive list */
1725 CmpMachineHiveList[0].CmHive = HardwareHive;
1726
1727 /* Attach it to the machine key */
1728 RtlInitUnicodeString(&KeyName, L"\\Registry\\Machine\\HARDWARE");
1729 Status = CmpLinkHiveToMaster(&KeyName,
1730 NULL,
1731 HardwareHive,
1732 TRUE,
1733 SecurityDescriptor);
1734 if (!NT_SUCCESS(Status))
1735 {
1736 /* Bugcheck */
1737 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 12, Status, 0);
1738 }
1739
1740 /* Add to HiveList key */
1741 CmpAddToHiveFileList(HardwareHive);
1742
1743 /* Free the security descriptor */
1744 ExFreePoolWithTag(SecurityDescriptor, TAG_CMSD);
1745
1746 /* Fill out the Hardware key with the ARC Data from the Loader */
1747 Status = CmpInitializeHardwareConfiguration(KeLoaderBlock);
1748 if (!NT_SUCCESS(Status))
1749 {
1750 /* Bugcheck */
1751 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 13, Status, 0);
1752 }
1753
1754 /* Initialize machine-dependent information into the registry */
1755 Status = CmpInitializeMachineDependentConfiguration(KeLoaderBlock);
1756 if (!NT_SUCCESS(Status))
1757 {
1758 /* Bugcheck */
1759 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 14, Status, 0);
1760 }
1761
1762 /* Initialize volatile registry settings */
1763 Status = CmpSetSystemValues(KeLoaderBlock);
1764 if (!NT_SUCCESS(Status))
1765 {
1766 /* Bugcheck */
1767 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 15, Status, 0);
1768 }
1769
1770 /* Free the load options */
1771 ExFreePoolWithTag(CmpLoadOptions.Buffer, TAG_CM);
1772
1773 /* If we got here, all went well */
1774 return TRUE;
1775 }
1776
1777 VOID
1778 NTAPI
1779 INIT_FUNCTION
1780 CmpFreeDriverList(IN PHHIVE Hive,
1781 IN PLIST_ENTRY DriverList)
1782 {
1783 PLIST_ENTRY NextEntry, OldEntry;
1784 PBOOT_DRIVER_NODE DriverNode;
1785 PAGED_CODE();
1786
1787 /* Parse the current list */
1788 NextEntry = DriverList->Flink;
1789 while (NextEntry != DriverList)
1790 {
1791 /* Get the driver node */
1792 DriverNode = CONTAINING_RECORD(NextEntry, BOOT_DRIVER_NODE, ListEntry.Link);
1793
1794 /* Get the next entry now, since we're going to free it later */
1795 OldEntry = NextEntry;
1796 NextEntry = NextEntry->Flink;
1797
1798 /* Was there a name? */
1799 if (DriverNode->Name.Buffer)
1800 {
1801 /* Free it */
1802 CmpFree(DriverNode->Name.Buffer, DriverNode->Name.Length);
1803 }
1804
1805 /* Was there a registry path? */
1806 if (DriverNode->ListEntry.RegistryPath.Buffer)
1807 {
1808 /* Free it */
1809 CmpFree(DriverNode->ListEntry.RegistryPath.Buffer,
1810 DriverNode->ListEntry.RegistryPath.MaximumLength);
1811 }
1812
1813 /* Was there a file path? */
1814 if (DriverNode->ListEntry.FilePath.Buffer)
1815 {
1816 /* Free it */
1817 CmpFree(DriverNode->ListEntry.FilePath.Buffer,
1818 DriverNode->ListEntry.FilePath.MaximumLength);
1819 }
1820
1821 /* Now free the node, and move on */
1822 CmpFree(OldEntry, sizeof(BOOT_DRIVER_NODE));
1823 }
1824 }
1825
1826 PUNICODE_STRING*
1827 NTAPI
1828 INIT_FUNCTION
1829 CmGetSystemDriverList(VOID)
1830 {
1831 LIST_ENTRY DriverList;
1832 OBJECT_ATTRIBUTES ObjectAttributes;
1833 NTSTATUS Status;
1834 PCM_KEY_BODY KeyBody;
1835 PHHIVE Hive;
1836 HCELL_INDEX RootCell, ControlCell;
1837 HANDLE KeyHandle;
1838 UNICODE_STRING KeyName;
1839 PLIST_ENTRY NextEntry;
1840 ULONG i;
1841 PUNICODE_STRING* ServicePath = NULL;
1842 BOOLEAN Success, AutoSelect;
1843 PBOOT_DRIVER_LIST_ENTRY DriverEntry;
1844 PAGED_CODE();
1845
1846 /* Initialize the driver list */
1847 InitializeListHead(&DriverList);
1848
1849 /* Open the system hive key */
1850 RtlInitUnicodeString(&KeyName, L"\\Registry\\Machine\\System");
1851 InitializeObjectAttributes(&ObjectAttributes,
1852 &KeyName,
1853 OBJ_CASE_INSENSITIVE,
1854 NULL,
1855 NULL);
1856 Status = NtOpenKey(&KeyHandle, KEY_READ, &ObjectAttributes);
1857 if (!NT_SUCCESS(Status)) return NULL;
1858
1859 /* Reference the key object to get the root hive/cell to access directly */
1860 Status = ObReferenceObjectByHandle(KeyHandle,
1861 KEY_QUERY_VALUE,
1862 CmpKeyObjectType,
1863 KernelMode,
1864 (PVOID*)&KeyBody,
1865 NULL);
1866 if (!NT_SUCCESS(Status))
1867 {
1868 /* Fail */
1869 NtClose(KeyHandle);
1870 return NULL;
1871 }
1872
1873 /* Do all this under the registry lock */
1874 CmpLockRegistryExclusive();
1875
1876 /* Get the hive and key cell */
1877 Hive = KeyBody->KeyControlBlock->KeyHive;
1878 RootCell = KeyBody->KeyControlBlock->KeyCell;
1879
1880 /* Open the current control set key */
1881 RtlInitUnicodeString(&KeyName, L"Current");
1882 ControlCell = CmpFindControlSet(Hive, RootCell, &KeyName, &AutoSelect);
1883 if (ControlCell == HCELL_NIL) goto EndPath;
1884
1885 /* Find all system drivers */
1886 Success = CmpFindDrivers(Hive, ControlCell, SystemLoad, NULL, &DriverList);
1887 if (!Success) goto EndPath;
1888
1889 /* Sort by group/tag */
1890 if (!CmpSortDriverList(Hive, ControlCell, &DriverList)) goto EndPath;
1891
1892 /* Remove circular dependencies (cycles) and sort */
1893 if (!CmpResolveDriverDependencies(&DriverList)) goto EndPath;
1894
1895 /* Loop the list to count drivers */
1896 for (i = 0, NextEntry = DriverList.Flink;
1897 NextEntry != &DriverList;
1898 i++, NextEntry = NextEntry->Flink);
1899
1900 /* Allocate the array */
1901 ServicePath = ExAllocatePool(NonPagedPool, (i + 1) * sizeof(PUNICODE_STRING));
1902 if (!ServicePath) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 2, 1, 0, 0);
1903
1904 /* Loop the driver list */
1905 for (i = 0, NextEntry = DriverList.Flink;
1906 NextEntry != &DriverList;
1907 i++, NextEntry = NextEntry->Flink)
1908 {
1909 /* Get the entry */
1910 DriverEntry = CONTAINING_RECORD(NextEntry, BOOT_DRIVER_LIST_ENTRY, Link);
1911
1912 /* Allocate the path for the caller and duplicate the registry path */
1913 ServicePath[i] = ExAllocatePool(NonPagedPool, sizeof(UNICODE_STRING));
1914 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE,
1915 &DriverEntry->RegistryPath,
1916 ServicePath[i]);
1917 }
1918
1919 /* Terminate the list */
1920 ServicePath[i] = NULL;
1921
1922 EndPath:
1923 /* Free the driver list if we had one */
1924 if (!IsListEmpty(&DriverList)) CmpFreeDriverList(Hive, &DriverList);
1925
1926 /* Unlock the registry */
1927 CmpUnlockRegistry();
1928
1929 /* Close the key handle and dereference the object, then return the path */
1930 ObDereferenceObject(KeyBody);
1931 NtClose(KeyHandle);
1932 return ServicePath;
1933 }
1934
1935 VOID
1936 NTAPI
1937 CmpLockRegistryExclusive(VOID)
1938 {
1939 /* Enter a critical region and lock the registry */
1940 KeEnterCriticalRegion();
1941 ExAcquireResourceExclusiveLite(&CmpRegistryLock, TRUE);
1942
1943 /* Sanity check */
1944 ASSERT(CmpFlushStarveWriters == 0);
1945 RtlGetCallersAddress(&CmpRegistryLockCaller, &CmpRegistryLockCallerCaller);
1946 }
1947
1948 VOID
1949 NTAPI
1950 CmpLockRegistry(VOID)
1951 {
1952 /* Enter a critical region */
1953 KeEnterCriticalRegion();
1954
1955 /* Check if we have to starve writers */
1956 if (CmpFlushStarveWriters)
1957 {
1958 /* Starve exlusive waiters */
1959 ExAcquireSharedStarveExclusive(&CmpRegistryLock, TRUE);
1960 }
1961 else
1962 {
1963 /* Just grab the lock */
1964 ExAcquireResourceSharedLite(&CmpRegistryLock, TRUE);
1965 }
1966 }
1967
1968 BOOLEAN
1969 NTAPI
1970 CmpTestRegistryLock(VOID)
1971 {
1972 /* Test the lock */
1973 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock) ? FALSE : TRUE;
1974 }
1975
1976 BOOLEAN
1977 NTAPI
1978 CmpTestRegistryLockExclusive(VOID)
1979 {
1980 /* Test the lock */
1981 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock) ? FALSE : TRUE;
1982 }
1983
1984 VOID
1985 NTAPI
1986 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive)
1987 {
1988 /* Lock the flusher. We should already be in a critical section */
1989 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive);
1990 ASSERT((ExIsResourceAcquiredShared(Hive->FlusherLock) == 0) &&
1991 (ExIsResourceAcquiredExclusiveLite(Hive->FlusherLock) == 0));
1992 ExAcquireResourceExclusiveLite(Hive->FlusherLock, TRUE);
1993 }
1994
1995 VOID
1996 NTAPI
1997 CmpLockHiveFlusherShared(IN PCMHIVE Hive)
1998 {
1999 /* Lock the flusher. We should already be in a critical section */
2000 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive);
2001 ASSERT((ExIsResourceAcquiredShared(Hive->FlusherLock) == 0) &&
2002 (ExIsResourceAcquiredExclusiveLite(Hive->FlusherLock) == 0));
2003 ExAcquireResourceSharedLite(Hive->FlusherLock, TRUE);
2004 }
2005
2006 VOID
2007 NTAPI
2008 CmpUnlockHiveFlusher(IN PCMHIVE Hive)
2009 {
2010 /* Sanity check */
2011 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive);
2012 CMP_ASSERT_FLUSH_LOCK(Hive);
2013
2014 /* Release the lock */
2015 ExReleaseResourceLite(Hive->FlusherLock);
2016 }
2017
2018 BOOLEAN
2019 NTAPI
2020 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive)
2021 {
2022 /* Test the lock */
2023 return !ExIsResourceAcquiredSharedLite(Hive->FlusherLock) ? FALSE : TRUE;
2024 }
2025
2026 BOOLEAN
2027 NTAPI
2028 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive)
2029 {
2030 /* Test the lock */
2031 return !ExIsResourceAcquiredExclusiveLite(Hive->FlusherLock) ? FALSE : TRUE;
2032 }
2033
2034 VOID
2035 NTAPI
2036 CmpUnlockRegistry(VOID)
2037 {
2038 /* Sanity check */
2039 CMP_ASSERT_REGISTRY_LOCK();
2040
2041 /* Check if we should flush the registry */
2042 if (CmpFlushOnLockRelease)
2043 {
2044 /* The registry should be exclusively locked for this */
2045 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
2046
2047 /* Flush the registry */
2048 CmpDoFlushAll(TRUE);
2049 CmpFlushOnLockRelease = FALSE;
2050 }
2051 else
2052 {
2053 /* Lazy flush the registry */
2054 CmpLazyFlush();
2055 }
2056
2057 /* Release the lock and leave the critical region */
2058 ExReleaseResourceLite(&CmpRegistryLock);
2059 KeLeaveCriticalRegion();
2060 }
2061
2062 VOID
2063 NTAPI
2064 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1,
2065 IN ULONG ConvKey2)
2066 {
2067 ULONG Index1, Index2;
2068
2069 /* Sanity check */
2070 CMP_ASSERT_REGISTRY_LOCK();
2071
2072 /* Get hash indexes */
2073 Index1 = GET_HASH_INDEX(ConvKey1);
2074 Index2 = GET_HASH_INDEX(ConvKey2);
2075
2076 /* See which one is highest */
2077 if (Index1 < Index2)
2078 {
2079 /* Grab them in the proper order */
2080 CmpAcquireKcbLockExclusiveByKey(ConvKey1);
2081 CmpAcquireKcbLockExclusiveByKey(ConvKey2);
2082 }
2083 else
2084 {
2085 /* Grab the second one first, then the first */
2086 CmpAcquireKcbLockExclusiveByKey(ConvKey2);
2087 if (Index1 != Index2) CmpAcquireKcbLockExclusiveByKey(ConvKey1);
2088 }
2089 }
2090
2091 VOID
2092 NTAPI
2093 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1,
2094 IN ULONG ConvKey2)
2095 {
2096 ULONG Index1, Index2;
2097
2098 /* Sanity check */
2099 CMP_ASSERT_REGISTRY_LOCK();
2100
2101 /* Get hash indexes */
2102 Index1 = GET_HASH_INDEX(ConvKey1);
2103 Index2 = GET_HASH_INDEX(ConvKey2);
2104 ASSERT((GET_HASH_ENTRY(CmpCacheTable, ConvKey2).Owner == KeGetCurrentThread()) ||
2105 (CmpTestRegistryLockExclusive()));
2106
2107 /* See which one is highest */
2108 if (Index1 < Index2)
2109 {
2110 /* Grab them in the proper order */
2111 ASSERT((GET_HASH_ENTRY(CmpCacheTable, ConvKey1).Owner == KeGetCurrentThread()) ||
2112 (CmpTestRegistryLockExclusive()));
2113 CmpReleaseKcbLockByKey(ConvKey2);
2114 CmpReleaseKcbLockByKey(ConvKey1);
2115 }
2116 else
2117 {
2118 /* Release the first one first, then the second */
2119 if (Index1 != Index2)
2120 {
2121 ASSERT((GET_HASH_ENTRY(CmpCacheTable, ConvKey1).Owner == KeGetCurrentThread()) ||
2122 (CmpTestRegistryLockExclusive()));
2123 CmpReleaseKcbLockByKey(ConvKey1);
2124 }
2125 CmpReleaseKcbLockByKey(ConvKey2);
2126 }
2127 }
2128
2129 VOID
2130 NTAPI
2131 CmShutdownSystem(VOID)
2132 {
2133 PLIST_ENTRY ListEntry;
2134 PCMHIVE Hive;
2135
2136 /* Kill the workers */
2137 if (!CmFirstTime) CmpShutdownWorkers();
2138
2139 /* Flush all hives */
2140 CmpLockRegistryExclusive();
2141 CmpDoFlushAll(TRUE);
2142
2143 /* Close all hive files */
2144 ListEntry = CmpHiveListHead.Flink;
2145 while (ListEntry != &CmpHiveListHead)
2146 {
2147 Hive = CONTAINING_RECORD(ListEntry, CMHIVE, HiveList);
2148
2149 CmpCloseHiveFiles(Hive);
2150
2151 ListEntry = ListEntry->Flink;
2152 }
2153
2154 CmpUnlockRegistry();
2155 }
2156
2157 VOID
2158 NTAPI
2159 CmpSetVersionData(VOID)
2160 {
2161 NTSTATUS Status;
2162 OBJECT_ATTRIBUTES ObjectAttributes;
2163 UNICODE_STRING KeyName;
2164 UNICODE_STRING ValueName;
2165 UNICODE_STRING ValueData;
2166 ANSI_STRING TempString;
2167 HANDLE SoftwareKeyHandle = NULL;
2168 HANDLE MicrosoftKeyHandle = NULL;
2169 HANDLE WindowsNtKeyHandle = NULL;
2170 HANDLE CurrentVersionKeyHandle = NULL;
2171 WCHAR Buffer[128]; // Buffer large enough to contain a full ULONG in decimal representation,
2172 // and the full 'CurrentType' string.
2173
2174 /*
2175 * Open the 'HKLM\Software\Microsoft\Windows NT\CurrentVersion' key
2176 * (create the intermediate subkeys if needed).
2177 */
2178
2179 RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\MACHINE\\SOFTWARE");
2180 InitializeObjectAttributes(&ObjectAttributes,
2181 &KeyName,
2182 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2183 NULL,
2184 NULL);
2185 Status = NtCreateKey(&SoftwareKeyHandle,
2186 KEY_CREATE_SUB_KEY,
2187 &ObjectAttributes,
2188 0,
2189 NULL,
2190 0,
2191 NULL);
2192 if (!NT_SUCCESS(Status))
2193 {
2194 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2195 return;
2196 }
2197
2198 RtlInitUnicodeString(&KeyName, L"Microsoft");
2199 InitializeObjectAttributes(&ObjectAttributes,
2200 &KeyName,
2201 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2202 SoftwareKeyHandle,
2203 NULL);
2204 Status = NtCreateKey(&MicrosoftKeyHandle,
2205 KEY_CREATE_SUB_KEY,
2206 &ObjectAttributes,
2207 0,
2208 NULL,
2209 0,
2210 NULL);
2211 if (!NT_SUCCESS(Status))
2212 {
2213 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2214 goto Quit;
2215 }
2216
2217 RtlInitUnicodeString(&KeyName, L"Windows NT");
2218 InitializeObjectAttributes(&ObjectAttributes,
2219 &KeyName,
2220 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2221 MicrosoftKeyHandle,
2222 NULL);
2223 Status = NtCreateKey(&WindowsNtKeyHandle,
2224 KEY_CREATE_SUB_KEY,
2225 &ObjectAttributes,
2226 0,
2227 NULL,
2228 0,
2229 NULL);
2230 if (!NT_SUCCESS(Status))
2231 {
2232 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2233 goto Quit;
2234 }
2235
2236 RtlInitUnicodeString(&KeyName, L"CurrentVersion");
2237 InitializeObjectAttributes(&ObjectAttributes,
2238 &KeyName,
2239 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2240 WindowsNtKeyHandle,
2241 NULL);
2242 Status = NtCreateKey(&CurrentVersionKeyHandle,
2243 KEY_CREATE_SUB_KEY | KEY_SET_VALUE,
2244 &ObjectAttributes,
2245 0,
2246 NULL,
2247 0,
2248 NULL);
2249 if (!NT_SUCCESS(Status))
2250 {
2251 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2252 goto Quit;
2253 }
2254
2255 /* Set the 'CurrentVersion' value */
2256 RtlInitUnicodeString(&ValueName, L"CurrentVersion");
2257 NtSetValueKey(CurrentVersionKeyHandle,
2258 &ValueName,
2259 0,
2260 REG_SZ,
2261 CmVersionString.Buffer,
2262 CmVersionString.Length + sizeof(WCHAR));
2263
2264 /* Set the 'CurrentBuildNumber' value */
2265 RtlInitUnicodeString(&ValueName, L"CurrentBuildNumber");
2266 RtlInitEmptyUnicodeString(&ValueData, Buffer, sizeof(Buffer));
2267 RtlIntegerToUnicodeString(NtBuildNumber & 0xFFFF, 10, &ValueData);
2268 NtSetValueKey(CurrentVersionKeyHandle,
2269 &ValueName,
2270 0,
2271 REG_SZ,
2272 ValueData.Buffer,
2273 ValueData.Length + sizeof(WCHAR));
2274
2275 /* Set the 'BuildLab' value */
2276 RtlInitUnicodeString(&ValueName, L"BuildLab");
2277 RtlInitAnsiString(&TempString, NtBuildLab);
2278 Status = RtlAnsiStringToUnicodeString(&ValueData, &TempString, FALSE);
2279 if (NT_SUCCESS(Status))
2280 {
2281 NtSetValueKey(CurrentVersionKeyHandle,
2282 &ValueName,
2283 0,
2284 REG_SZ,
2285 ValueData.Buffer,
2286 ValueData.Length + sizeof(WCHAR));
2287 }
2288
2289 /* Set the 'CurrentType' value */
2290 RtlInitUnicodeString(&ValueName, L"CurrentType");
2291
2292 swprintf(Buffer, L"%s %s",
2293 #ifdef CONFIG_SMP
2294 L"Multiprocessor"
2295 #else
2296 L"Uniprocessor"
2297 #endif
2298 ,
2299 #if (DBG == 1)
2300 L"Checked"
2301 #else
2302 L"Free"
2303 #endif
2304 );
2305 RtlInitUnicodeString(&ValueData, Buffer);
2306 NtSetValueKey(CurrentVersionKeyHandle,
2307 &ValueName,
2308 0,
2309 REG_SZ,
2310 ValueData.Buffer,
2311 ValueData.Length + sizeof(WCHAR));
2312
2313 /* Set the 'CSDVersion' value */
2314 RtlInitUnicodeString(&ValueName, L"CSDVersion");
2315 if (CmCSDVersionString.Length != 0)
2316 {
2317 NtSetValueKey(CurrentVersionKeyHandle,
2318 &ValueName,
2319 0,
2320 REG_SZ,
2321 CmCSDVersionString.Buffer,
2322 CmCSDVersionString.Length + sizeof(WCHAR));
2323 }
2324 else
2325 {
2326 NtDeleteValueKey(CurrentVersionKeyHandle, &ValueName);
2327 }
2328
2329 /* Set the 'CSDBuildNumber' value */
2330 RtlInitUnicodeString(&ValueName, L"CSDBuildNumber");
2331 if (CmNtSpBuildNumber != 0)
2332 {
2333 RtlInitEmptyUnicodeString(&ValueData, Buffer, sizeof(Buffer));
2334 RtlIntegerToUnicodeString(CmNtSpBuildNumber, 10, &ValueData);
2335 NtSetValueKey(CurrentVersionKeyHandle,
2336 &ValueName,
2337 0,
2338 REG_SZ,
2339 ValueData.Buffer,
2340 ValueData.Length + sizeof(WCHAR));
2341 }
2342 else
2343 {
2344 NtDeleteValueKey(CurrentVersionKeyHandle, &ValueName);
2345 }
2346
2347 /* Set the 'SystemRoot' value */
2348 RtlInitUnicodeString(&ValueName, L"SystemRoot");
2349 NtSetValueKey(CurrentVersionKeyHandle,
2350 &ValueName,
2351 0,
2352 REG_SZ,
2353 NtSystemRoot.Buffer,
2354 NtSystemRoot.Length + sizeof(WCHAR));
2355
2356 Quit:
2357 /* Close the keys */
2358 if (CurrentVersionKeyHandle != NULL)
2359 NtClose(CurrentVersionKeyHandle);
2360
2361 if (WindowsNtKeyHandle != NULL)
2362 NtClose(WindowsNtKeyHandle);
2363
2364 if (MicrosoftKeyHandle != NULL)
2365 NtClose(MicrosoftKeyHandle);
2366
2367 if (SoftwareKeyHandle != NULL)
2368 NtClose(SoftwareKeyHandle);
2369 }
2370
2371 /* EOF */