[STORAHCI] Merge Storport Miniport driver by Aman Priyadarshi in GSoC.
[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 DPRINT1("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(IN 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 /* Setup the object attributes */
1196 InitializeObjectAttributes(&ObjectAttributes,
1197 &KeyName,
1198 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
1199 NULL,
1200 NULL);
1201 /* Open the key */
1202 Status = ZwOpenKey(&KeyHandle,
1203 KEY_ALL_ACCESS,
1204 &ObjectAttributes);
1205 if (!NT_SUCCESS(Status)) return Status;
1206
1207 /* Allocate the buffer */
1208 BufferSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + 4096;
1209 ValueInfo = ExAllocatePoolWithTag(PagedPool, BufferSize, TAG_CM);
1210 if (!ValueInfo)
1211 {
1212 /* Fail */
1213 ZwClose(KeyHandle);
1214 return STATUS_INSUFFICIENT_RESOURCES;
1215 }
1216
1217 /* Query the value */
1218 Status = ZwQueryValueKey(KeyHandle,
1219 &ValueName,
1220 KeyValuePartialInformation,
1221 ValueInfo,
1222 BufferSize,
1223 &ResultSize);
1224 ZwClose(KeyHandle);
1225 if (!NT_SUCCESS(Status))
1226 {
1227 /* Fail */
1228 ExFreePoolWithTag(ValueInfo, TAG_CM);
1229 return Status;
1230 }
1231
1232 /* Copy the config path and null-terminate it */
1233 RtlCopyMemory(ConfigPath,
1234 ValueInfo->Data,
1235 ValueInfo->DataLength);
1236 ConfigPath[ValueInfo->DataLength / sizeof(WCHAR)] = UNICODE_NULL;
1237 ExFreePoolWithTag(ValueInfo, TAG_CM);
1238 }
1239 else
1240 {
1241 /* Just use default path */
1242 wcscpy(ConfigPath, L"\\SystemRoot");
1243 }
1244
1245 /* Add registry path */
1246 wcscat(ConfigPath, L"\\System32\\Config\\");
1247
1248 /* Done */
1249 return STATUS_SUCCESS;
1250 }
1251
1252 VOID
1253 NTAPI
1254 CmpLoadHiveThread(IN PVOID StartContext)
1255 {
1256 WCHAR FileBuffer[MAX_PATH], RegBuffer[MAX_PATH], ConfigPath[MAX_PATH];
1257 UNICODE_STRING TempName, FileName, RegName;
1258 ULONG i, ErrorResponse, WorkerCount, Length;
1259 USHORT FileStart;
1260 //ULONG RegStart;
1261 ULONG PrimaryDisposition, SecondaryDisposition, ClusterSize;
1262 PCMHIVE CmHive;
1263 HANDLE PrimaryHandle = NULL, LogHandle = NULL;
1264 NTSTATUS Status = STATUS_SUCCESS;
1265 PVOID ErrorParameters;
1266 PAGED_CODE();
1267
1268 /* Get the hive index, make sure it makes sense */
1269 i = PtrToUlong(StartContext);
1270 ASSERT(CmpMachineHiveList[i].Name != NULL);
1271
1272 /* We were started */
1273 CmpMachineHiveList[i].ThreadStarted = TRUE;
1274
1275 /* Build the file name and registry name strings */
1276 RtlInitEmptyUnicodeString(&FileName, FileBuffer, MAX_PATH);
1277 RtlInitEmptyUnicodeString(&RegName, RegBuffer, MAX_PATH);
1278
1279 /* Now build the system root path */
1280 CmpGetRegistryPath(ConfigPath);
1281 RtlInitUnicodeString(&TempName, ConfigPath);
1282 RtlAppendStringToString((PSTRING)&FileName, (PSTRING)&TempName);
1283 FileStart = FileName.Length;
1284
1285 /* And build the registry root path */
1286 RtlInitUnicodeString(&TempName, L"\\REGISTRY\\");
1287 RtlAppendStringToString((PSTRING)&RegName, (PSTRING)&TempName);
1288 //RegStart = RegName.Length;
1289
1290 /* Build the base name */
1291 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].BaseName);
1292 RtlAppendStringToString((PSTRING)&RegName, (PSTRING)&TempName);
1293
1294 /* Check if this is a child of the root */
1295 if (RegName.Buffer[RegName.Length / sizeof(WCHAR) - 1] == '\\')
1296 {
1297 /* Then setup the whole name */
1298 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].Name);
1299 RtlAppendStringToString((PSTRING)&RegName, (PSTRING)&TempName);
1300 }
1301
1302 /* Now add the rest of the file name */
1303 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].Name);
1304 FileName.Length = FileStart;
1305 RtlAppendStringToString((PSTRING)&FileName, (PSTRING)&TempName);
1306 if (!CmpMachineHiveList[i].CmHive)
1307 {
1308 /* We need to allocate a new hive structure */
1309 CmpMachineHiveList[i].Allocate = TRUE;
1310
1311 /* Load the hive file */
1312 Status = CmpInitHiveFromFile(&FileName,
1313 CmpMachineHiveList[i].HHiveFlags,
1314 &CmHive,
1315 &CmpMachineHiveList[i].Allocate,
1316 0);
1317 if (!(NT_SUCCESS(Status)) ||
1318 (!(CmHive->FileHandles[HFILE_TYPE_LOG]) && !(CmpMiniNTBoot))) // HACK
1319 {
1320 /* We failed or couldn't get a log file, raise a hard error */
1321 ErrorParameters = &FileName;
1322 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE,
1323 1,
1324 1,
1325 (PULONG_PTR)&ErrorParameters,
1326 OptionOk,
1327 &ErrorResponse);
1328 }
1329
1330 /* Set the hive flags and newly allocated hive pointer */
1331 CmHive->Flags = CmpMachineHiveList[i].CmHiveFlags;
1332 CmpMachineHiveList[i].CmHive2 = CmHive;
1333 }
1334 else
1335 {
1336 /* We already have a hive, is it volatile? */
1337 CmHive = CmpMachineHiveList[i].CmHive;
1338 if (!(CmHive->Hive.HiveFlags & HIVE_VOLATILE))
1339 {
1340 /* It's now, open the hive file and log */
1341 Status = CmpOpenHiveFiles(&FileName,
1342 L".LOG",
1343 &PrimaryHandle,
1344 &LogHandle,
1345 &PrimaryDisposition,
1346 &SecondaryDisposition,
1347 TRUE,
1348 TRUE,
1349 FALSE,
1350 &ClusterSize);
1351 if (!(NT_SUCCESS(Status)) || !(LogHandle))
1352 {
1353 /* Couldn't open the hive or its log file, raise a hard error */
1354 ErrorParameters = &FileName;
1355 NtRaiseHardError(STATUS_CANNOT_LOAD_REGISTRY_FILE,
1356 1,
1357 1,
1358 (PULONG_PTR)&ErrorParameters,
1359 OptionOk,
1360 &ErrorResponse);
1361
1362 /* And bugcheck for posterity's sake */
1363 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO, 9, 0, i, Status);
1364 }
1365
1366 /* Save the file handles. This should remove our sync hacks */
1367 CmHive->FileHandles[HFILE_TYPE_LOG] = LogHandle;
1368 CmHive->FileHandles[HFILE_TYPE_PRIMARY] = PrimaryHandle;
1369
1370 /* Allow lazy flushing since the handles are there -- remove sync hacks */
1371 //ASSERT(CmHive->Hive.HiveFlags & HIVE_NOLAZYFLUSH);
1372 CmHive->Hive.HiveFlags &= ~HIVE_NOLAZYFLUSH;
1373
1374 /* Get the real size of the hive */
1375 Length = CmHive->Hive.Storage[Stable].Length + HBLOCK_SIZE;
1376
1377 /* Check if the cluster size doesn't match */
1378 if (CmHive->Hive.Cluster != ClusterSize) ASSERT(FALSE);
1379
1380 /* Set the file size */
1381 DPRINT("FIXME: Should set file size: %lx\n", Length);
1382 //if (!CmpFileSetSize((PHHIVE)CmHive, HFILE_TYPE_PRIMARY, Length, Length))
1383 {
1384 /* This shouldn't fail */
1385 //ASSERT(FALSE);
1386 }
1387
1388 /* Another thing we don't support is NTLDR-recovery */
1389 if (CmHive->Hive.BaseBlock->BootRecover) ASSERT(FALSE);
1390
1391 /* Finally, set our allocated hive to the same hive we've had */
1392 CmpMachineHiveList[i].CmHive2 = CmHive;
1393 ASSERT(CmpMachineHiveList[i].CmHive == CmpMachineHiveList[i].CmHive2);
1394 }
1395 }
1396
1397 /* We're done */
1398 CmpMachineHiveList[i].ThreadFinished = TRUE;
1399
1400 /* Check if we're the last worker */
1401 WorkerCount = InterlockedIncrement(&CmpLoadWorkerIncrement);
1402 if (WorkerCount == CM_NUMBER_OF_MACHINE_HIVES)
1403 {
1404 /* Signal the event */
1405 KeSetEvent(&CmpLoadWorkerEvent, 0, FALSE);
1406 }
1407
1408 /* Kill the thread */
1409 PsTerminateSystemThread(Status);
1410 }
1411
1412 VOID
1413 NTAPI
1414 CmpInitializeHiveList(IN USHORT Flag)
1415 {
1416 WCHAR FileBuffer[MAX_PATH], RegBuffer[MAX_PATH], ConfigPath[MAX_PATH];
1417 UNICODE_STRING TempName, FileName, RegName;
1418 HANDLE Thread;
1419 NTSTATUS Status;
1420 ULONG i;
1421 USHORT RegStart;
1422 PSECURITY_DESCRIPTOR SecurityDescriptor;
1423 PAGED_CODE();
1424
1425 /* Allow writing for now */
1426 CmpNoWrite = FALSE;
1427
1428 /* Build the file name and registry name strings */
1429 RtlInitEmptyUnicodeString(&FileName, FileBuffer, MAX_PATH);
1430 RtlInitEmptyUnicodeString(&RegName, RegBuffer, MAX_PATH);
1431
1432 /* Now build the system root path */
1433 CmpGetRegistryPath(ConfigPath);
1434 RtlInitUnicodeString(&TempName, ConfigPath);
1435 RtlAppendStringToString((PSTRING)&FileName, (PSTRING)&TempName);
1436
1437 /* And build the registry root path */
1438 RtlInitUnicodeString(&TempName, L"\\REGISTRY\\");
1439 RtlAppendStringToString((PSTRING)&RegName, (PSTRING)&TempName);
1440 RegStart = RegName.Length;
1441
1442 /* Setup the event to synchronize workers */
1443 KeInitializeEvent(&CmpLoadWorkerEvent, SynchronizationEvent, FALSE);
1444
1445 /* Enter special boot condition */
1446 CmpSpecialBootCondition = TRUE;
1447
1448 /* Create the SD for the root hives */
1449 SecurityDescriptor = CmpHiveRootSecurityDescriptor();
1450
1451 /* Loop every hive we care about */
1452 for (i = 0; i < CM_NUMBER_OF_MACHINE_HIVES; i++)
1453 {
1454 /* Make sure the list is setup */
1455 ASSERT(CmpMachineHiveList[i].Name != NULL);
1456
1457 /* Create a thread to handle this hive */
1458 Status = PsCreateSystemThread(&Thread,
1459 THREAD_ALL_ACCESS,
1460 NULL,
1461 0,
1462 NULL,
1463 CmpLoadHiveThread,
1464 UlongToPtr(i));
1465 if (NT_SUCCESS(Status))
1466 {
1467 /* We don't care about the handle -- the thread self-terminates */
1468 ZwClose(Thread);
1469 }
1470 else
1471 {
1472 /* Can't imagine this happening */
1473 KeBugCheckEx(BAD_SYSTEM_CONFIG_INFO, 9, 3, i, Status);
1474 }
1475 }
1476
1477 /* Make sure we've reached the end of the list */
1478 ASSERT(CmpMachineHiveList[i].Name == NULL);
1479
1480 /* Wait for hive loading to finish */
1481 KeWaitForSingleObject(&CmpLoadWorkerEvent,
1482 Executive,
1483 KernelMode,
1484 FALSE,
1485 NULL);
1486
1487 /* Exit the special boot condition and make sure all workers completed */
1488 CmpSpecialBootCondition = FALSE;
1489 ASSERT(CmpLoadWorkerIncrement == CM_NUMBER_OF_MACHINE_HIVES);
1490
1491 /* Loop hives again */
1492 for (i = 0; i < CM_NUMBER_OF_MACHINE_HIVES; i++)
1493 {
1494 /* Make sure the thread ran and finished */
1495 ASSERT(CmpMachineHiveList[i].ThreadFinished == TRUE);
1496 ASSERT(CmpMachineHiveList[i].ThreadStarted == TRUE);
1497
1498 /* Check if this was a new hive */
1499 if (!CmpMachineHiveList[i].CmHive)
1500 {
1501 /* Make sure we allocated something */
1502 ASSERT(CmpMachineHiveList[i].CmHive2 != NULL);
1503
1504 /* Build the base name */
1505 RegName.Length = RegStart;
1506 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].BaseName);
1507 RtlAppendStringToString((PSTRING)&RegName, (PSTRING)&TempName);
1508
1509 /* Check if this is a child of the root */
1510 if (RegName.Buffer[RegName.Length / sizeof(WCHAR) - 1] == '\\')
1511 {
1512 /* Then setup the whole name */
1513 RtlInitUnicodeString(&TempName, CmpMachineHiveList[i].Name);
1514 RtlAppendStringToString((PSTRING)&RegName, (PSTRING)&TempName);
1515 }
1516
1517 /* Now link the hive to its master */
1518 Status = CmpLinkHiveToMaster(&RegName,
1519 NULL,
1520 CmpMachineHiveList[i].CmHive2,
1521 CmpMachineHiveList[i].Allocate,
1522 SecurityDescriptor);
1523 if (Status != STATUS_SUCCESS)
1524 {
1525 /* Linking needs to work */
1526 KeBugCheckEx(CONFIG_LIST_FAILED, 11, Status, i, (ULONG_PTR)&RegName);
1527 }
1528
1529 /* Check if we had to allocate a new hive */
1530 if (CmpMachineHiveList[i].Allocate)
1531 {
1532 /* Sync the new hive */
1533 //HvSyncHive((PHHIVE)(CmpMachineHiveList[i].CmHive2));
1534 }
1535 }
1536
1537 /* Check if we created a new hive */
1538 if (CmpMachineHiveList[i].CmHive2)
1539 {
1540 /* Add to HiveList key */
1541 CmpAddToHiveFileList(CmpMachineHiveList[i].CmHive2);
1542 }
1543 }
1544
1545 /* Get rid of the SD */
1546 ExFreePoolWithTag(SecurityDescriptor, TAG_CMSD);
1547
1548 /* Link SECURITY to SAM */
1549 CmpLinkKeyToHive(L"\\Registry\\Machine\\Security\\SAM",
1550 L"\\Registry\\Machine\\SAM\\SAM");
1551
1552 /* Link S-1-5-18 to .Default */
1553 CmpNoVolatileCreates = FALSE;
1554 CmpLinkKeyToHive(L"\\Registry\\User\\S-1-5-18",
1555 L"\\Registry\\User\\.Default");
1556 CmpNoVolatileCreates = TRUE;
1557 }
1558
1559 BOOLEAN
1560 NTAPI
1561 INIT_FUNCTION
1562 CmInitSystem1(VOID)
1563 {
1564 OBJECT_ATTRIBUTES ObjectAttributes;
1565 UNICODE_STRING KeyName;
1566 HANDLE KeyHandle;
1567 NTSTATUS Status;
1568 PCMHIVE HardwareHive;
1569 PSECURITY_DESCRIPTOR SecurityDescriptor;
1570 PAGED_CODE();
1571
1572 /* Check if this is PE-boot */
1573 if (InitIsWinPEMode)
1574 {
1575 /* Set registry to PE mode */
1576 CmpMiniNTBoot = TRUE;
1577 CmpShareSystemHives = TRUE;
1578 }
1579
1580 /* Initialize the hive list and lock */
1581 InitializeListHead(&CmpHiveListHead);
1582 ExInitializePushLock(&CmpHiveListHeadLock);
1583 ExInitializePushLock(&CmpLoadHiveLock);
1584
1585 /* Initialize registry lock */
1586 ExInitializeResourceLite(&CmpRegistryLock);
1587
1588 /* Initialize the cache */
1589 CmpInitializeCache();
1590
1591 /* Initialize allocation and delayed dereferencing */
1592 CmpInitCmPrivateAlloc();
1593 CmpInitCmPrivateDelayAlloc();
1594 CmpInitDelayDerefKCBEngine();
1595
1596 /* Initialize callbacks */
1597 CmpInitCallback();
1598
1599 /* Initialize self healing */
1600 KeInitializeGuardedMutex(&CmpSelfHealQueueLock);
1601 InitializeListHead(&CmpSelfHealQueueListHead);
1602
1603 /* Save the current process and lock the registry */
1604 CmpSystemProcess = PsGetCurrentProcess();
1605
1606 /* Create the key object types */
1607 Status = CmpCreateObjectTypes();
1608 if (!NT_SUCCESS(Status))
1609 {
1610 /* Bugcheck */
1611 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 1, Status, 0);
1612 }
1613
1614 /* Build the master hive */
1615 Status = CmpInitializeHive(&CmiVolatileHive,
1616 HINIT_CREATE,
1617 HIVE_VOLATILE,
1618 HFILE_TYPE_PRIMARY,
1619 NULL,
1620 NULL,
1621 NULL,
1622 NULL,
1623 NULL,
1624 0);
1625 if (!NT_SUCCESS(Status))
1626 {
1627 /* Bugcheck */
1628 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 2, Status, 0);
1629 }
1630
1631 /* Create the \REGISTRY key node */
1632 if (!CmpCreateRegistryRoot())
1633 {
1634 /* Bugcheck */
1635 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 3, 0, 0);
1636 }
1637
1638 /* Create the default security descriptor */
1639 SecurityDescriptor = CmpHiveRootSecurityDescriptor();
1640
1641 /* Create '\Registry\Machine' key. */
1642 RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\MACHINE");
1643 InitializeObjectAttributes(&ObjectAttributes,
1644 &KeyName,
1645 OBJ_CASE_INSENSITIVE,
1646 NULL,
1647 SecurityDescriptor);
1648 Status = NtCreateKey(&KeyHandle,
1649 KEY_READ | KEY_WRITE,
1650 &ObjectAttributes,
1651 0,
1652 NULL,
1653 0,
1654 NULL);
1655 if (!NT_SUCCESS(Status))
1656 {
1657 /* Bugcheck */
1658 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 5, Status, 0);
1659 }
1660
1661 /* Close the handle */
1662 NtClose(KeyHandle);
1663
1664 /* Create '\Registry\User' key. */
1665 RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\USER");
1666 InitializeObjectAttributes(&ObjectAttributes,
1667 &KeyName,
1668 OBJ_CASE_INSENSITIVE,
1669 NULL,
1670 SecurityDescriptor);
1671 Status = NtCreateKey(&KeyHandle,
1672 KEY_READ | KEY_WRITE,
1673 &ObjectAttributes,
1674 0,
1675 NULL,
1676 0,
1677 NULL);
1678 if (!NT_SUCCESS(Status))
1679 {
1680 /* Bugcheck */
1681 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 6, Status, 0);
1682 }
1683
1684 /* Close the handle */
1685 NtClose(KeyHandle);
1686
1687 /* After this point, do not allow creating keys in the master hive */
1688 CmpNoVolatileCreates = TRUE;
1689
1690 /* Initialize the system hive */
1691 if (!CmpInitializeSystemHive(KeLoaderBlock))
1692 {
1693 /* Bugcheck */
1694 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 7, 0, 0);
1695 }
1696
1697 /* Create the 'CurrentControlSet' link. */
1698 Status = CmpCreateControlSet(KeLoaderBlock);
1699 if (!NT_SUCCESS(Status))
1700 {
1701 /* Bugcheck */
1702 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 8, Status, 0);
1703 }
1704
1705 /* Create the hardware hive */
1706 Status = CmpInitializeHive(&HardwareHive,
1707 HINIT_CREATE,
1708 HIVE_VOLATILE,
1709 HFILE_TYPE_PRIMARY,
1710 NULL,
1711 NULL,
1712 NULL,
1713 NULL,
1714 NULL,
1715 0);
1716 if (!NT_SUCCESS(Status))
1717 {
1718 /* Bugcheck */
1719 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 11, Status, 0);
1720 }
1721
1722 /* Add the hive to the hive list */
1723 CmpMachineHiveList[0].CmHive = HardwareHive;
1724
1725 /* Attach it to the machine key */
1726 RtlInitUnicodeString(&KeyName, L"\\Registry\\Machine\\HARDWARE");
1727 Status = CmpLinkHiveToMaster(&KeyName,
1728 NULL,
1729 HardwareHive,
1730 TRUE,
1731 SecurityDescriptor);
1732 if (!NT_SUCCESS(Status))
1733 {
1734 /* Bugcheck */
1735 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 12, Status, 0);
1736 }
1737
1738 /* Add to HiveList key */
1739 CmpAddToHiveFileList(HardwareHive);
1740
1741 /* Free the security descriptor */
1742 ExFreePoolWithTag(SecurityDescriptor, TAG_CMSD);
1743
1744 /* Fill out the Hardware key with the ARC Data from the Loader */
1745 Status = CmpInitializeHardwareConfiguration(KeLoaderBlock);
1746 if (!NT_SUCCESS(Status))
1747 {
1748 /* Bugcheck */
1749 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 13, Status, 0);
1750 }
1751
1752 /* Initialize machine-dependent information into the registry */
1753 Status = CmpInitializeMachineDependentConfiguration(KeLoaderBlock);
1754 if (!NT_SUCCESS(Status))
1755 {
1756 /* Bugcheck */
1757 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 14, Status, 0);
1758 }
1759
1760 /* Initialize volatile registry settings */
1761 Status = CmpSetSystemValues(KeLoaderBlock);
1762 if (!NT_SUCCESS(Status))
1763 {
1764 /* Bugcheck */
1765 KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 1, 15, Status, 0);
1766 }
1767
1768 /* Free the load options */
1769 ExFreePoolWithTag(CmpLoadOptions.Buffer, TAG_CM);
1770
1771 /* If we got here, all went well */
1772 return TRUE;
1773 }
1774
1775 VOID
1776 NTAPI
1777 INIT_FUNCTION
1778 CmpFreeDriverList(IN PHHIVE Hive,
1779 IN PLIST_ENTRY DriverList)
1780 {
1781 PLIST_ENTRY NextEntry, OldEntry;
1782 PBOOT_DRIVER_NODE DriverNode;
1783 PAGED_CODE();
1784
1785 /* Parse the current list */
1786 NextEntry = DriverList->Flink;
1787 while (NextEntry != DriverList)
1788 {
1789 /* Get the driver node */
1790 DriverNode = CONTAINING_RECORD(NextEntry, BOOT_DRIVER_NODE, ListEntry.Link);
1791
1792 /* Get the next entry now, since we're going to free it later */
1793 OldEntry = NextEntry;
1794 NextEntry = NextEntry->Flink;
1795
1796 /* Was there a name? */
1797 if (DriverNode->Name.Buffer)
1798 {
1799 /* Free it */
1800 CmpFree(DriverNode->Name.Buffer, DriverNode->Name.Length);
1801 }
1802
1803 /* Was there a registry path? */
1804 if (DriverNode->ListEntry.RegistryPath.Buffer)
1805 {
1806 /* Free it */
1807 CmpFree(DriverNode->ListEntry.RegistryPath.Buffer,
1808 DriverNode->ListEntry.RegistryPath.MaximumLength);
1809 }
1810
1811 /* Was there a file path? */
1812 if (DriverNode->ListEntry.FilePath.Buffer)
1813 {
1814 /* Free it */
1815 CmpFree(DriverNode->ListEntry.FilePath.Buffer,
1816 DriverNode->ListEntry.FilePath.MaximumLength);
1817 }
1818
1819 /* Now free the node, and move on */
1820 CmpFree(OldEntry, sizeof(BOOT_DRIVER_NODE));
1821 }
1822 }
1823
1824 PUNICODE_STRING*
1825 NTAPI
1826 INIT_FUNCTION
1827 CmGetSystemDriverList(VOID)
1828 {
1829 LIST_ENTRY DriverList;
1830 OBJECT_ATTRIBUTES ObjectAttributes;
1831 NTSTATUS Status;
1832 PCM_KEY_BODY KeyBody;
1833 PHHIVE Hive;
1834 HCELL_INDEX RootCell, ControlCell;
1835 HANDLE KeyHandle;
1836 UNICODE_STRING KeyName;
1837 PLIST_ENTRY NextEntry;
1838 ULONG i;
1839 PUNICODE_STRING* ServicePath = NULL;
1840 BOOLEAN Success, AutoSelect;
1841 PBOOT_DRIVER_LIST_ENTRY DriverEntry;
1842 PAGED_CODE();
1843
1844 /* Initialize the driver list */
1845 InitializeListHead(&DriverList);
1846
1847 /* Open the system hive key */
1848 RtlInitUnicodeString(&KeyName, L"\\Registry\\Machine\\System");
1849 InitializeObjectAttributes(&ObjectAttributes,
1850 &KeyName,
1851 OBJ_CASE_INSENSITIVE,
1852 NULL,
1853 NULL);
1854 Status = NtOpenKey(&KeyHandle, KEY_READ, &ObjectAttributes);
1855 if (!NT_SUCCESS(Status)) return NULL;
1856
1857 /* Reference the key object to get the root hive/cell to access directly */
1858 Status = ObReferenceObjectByHandle(KeyHandle,
1859 KEY_QUERY_VALUE,
1860 CmpKeyObjectType,
1861 KernelMode,
1862 (PVOID*)&KeyBody,
1863 NULL);
1864 if (!NT_SUCCESS(Status))
1865 {
1866 /* Fail */
1867 NtClose(KeyHandle);
1868 return NULL;
1869 }
1870
1871 /* Do all this under the registry lock */
1872 CmpLockRegistryExclusive();
1873
1874 /* Get the hive and key cell */
1875 Hive = KeyBody->KeyControlBlock->KeyHive;
1876 RootCell = KeyBody->KeyControlBlock->KeyCell;
1877
1878 /* Open the current control set key */
1879 RtlInitUnicodeString(&KeyName, L"Current");
1880 ControlCell = CmpFindControlSet(Hive, RootCell, &KeyName, &AutoSelect);
1881 if (ControlCell == HCELL_NIL) goto EndPath;
1882
1883 /* Find all system drivers */
1884 Success = CmpFindDrivers(Hive, ControlCell, SystemLoad, NULL, &DriverList);
1885 if (!Success) goto EndPath;
1886
1887 /* Sort by group/tag */
1888 if (!CmpSortDriverList(Hive, ControlCell, &DriverList)) goto EndPath;
1889
1890 /* Remove circular dependencies (cycles) and sort */
1891 if (!CmpResolveDriverDependencies(&DriverList)) goto EndPath;
1892
1893 /* Loop the list to count drivers */
1894 for (i = 0, NextEntry = DriverList.Flink;
1895 NextEntry != &DriverList;
1896 i++, NextEntry = NextEntry->Flink);
1897
1898 /* Allocate the array */
1899 ServicePath = ExAllocatePool(NonPagedPool, (i + 1) * sizeof(PUNICODE_STRING));
1900 if (!ServicePath) KeBugCheckEx(CONFIG_INITIALIZATION_FAILED, 2, 1, 0, 0);
1901
1902 /* Loop the driver list */
1903 for (i = 0, NextEntry = DriverList.Flink;
1904 NextEntry != &DriverList;
1905 i++, NextEntry = NextEntry->Flink)
1906 {
1907 /* Get the entry */
1908 DriverEntry = CONTAINING_RECORD(NextEntry, BOOT_DRIVER_LIST_ENTRY, Link);
1909
1910 /* Allocate the path for the caller and duplicate the registry path */
1911 ServicePath[i] = ExAllocatePool(NonPagedPool, sizeof(UNICODE_STRING));
1912 RtlDuplicateUnicodeString(RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE,
1913 &DriverEntry->RegistryPath,
1914 ServicePath[i]);
1915 }
1916
1917 /* Terminate the list */
1918 ServicePath[i] = NULL;
1919
1920 EndPath:
1921 /* Free the driver list if we had one */
1922 if (!IsListEmpty(&DriverList)) CmpFreeDriverList(Hive, &DriverList);
1923
1924 /* Unlock the registry */
1925 CmpUnlockRegistry();
1926
1927 /* Close the key handle and dereference the object, then return the path */
1928 ObDereferenceObject(KeyBody);
1929 NtClose(KeyHandle);
1930 return ServicePath;
1931 }
1932
1933 VOID
1934 NTAPI
1935 CmpLockRegistryExclusive(VOID)
1936 {
1937 /* Enter a critical region and lock the registry */
1938 KeEnterCriticalRegion();
1939 ExAcquireResourceExclusiveLite(&CmpRegistryLock, TRUE);
1940
1941 /* Sanity check */
1942 ASSERT(CmpFlushStarveWriters == 0);
1943 RtlGetCallersAddress(&CmpRegistryLockCaller, &CmpRegistryLockCallerCaller);
1944 }
1945
1946 VOID
1947 NTAPI
1948 CmpLockRegistry(VOID)
1949 {
1950 /* Enter a critical region */
1951 KeEnterCriticalRegion();
1952
1953 /* Check if we have to starve writers */
1954 if (CmpFlushStarveWriters)
1955 {
1956 /* Starve exlusive waiters */
1957 ExAcquireSharedStarveExclusive(&CmpRegistryLock, TRUE);
1958 }
1959 else
1960 {
1961 /* Just grab the lock */
1962 ExAcquireResourceSharedLite(&CmpRegistryLock, TRUE);
1963 }
1964 }
1965
1966 BOOLEAN
1967 NTAPI
1968 CmpTestRegistryLock(VOID)
1969 {
1970 /* Test the lock */
1971 return !ExIsResourceAcquiredSharedLite(&CmpRegistryLock) ? FALSE : TRUE;
1972 }
1973
1974 BOOLEAN
1975 NTAPI
1976 CmpTestRegistryLockExclusive(VOID)
1977 {
1978 /* Test the lock */
1979 return !ExIsResourceAcquiredExclusiveLite(&CmpRegistryLock) ? FALSE : TRUE;
1980 }
1981
1982 VOID
1983 NTAPI
1984 CmpLockHiveFlusherExclusive(IN PCMHIVE Hive)
1985 {
1986 /* Lock the flusher. We should already be in a critical section */
1987 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive);
1988 ASSERT((ExIsResourceAcquiredShared(Hive->FlusherLock) == 0) &&
1989 (ExIsResourceAcquiredExclusiveLite(Hive->FlusherLock) == 0));
1990 ExAcquireResourceExclusiveLite(Hive->FlusherLock, TRUE);
1991 }
1992
1993 VOID
1994 NTAPI
1995 CmpLockHiveFlusherShared(IN PCMHIVE Hive)
1996 {
1997 /* Lock the flusher. We should already be in a critical section */
1998 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive);
1999 ASSERT((ExIsResourceAcquiredShared(Hive->FlusherLock) == 0) &&
2000 (ExIsResourceAcquiredExclusiveLite(Hive->FlusherLock) == 0));
2001 ExAcquireResourceSharedLite(Hive->FlusherLock, TRUE);
2002 }
2003
2004 VOID
2005 NTAPI
2006 CmpUnlockHiveFlusher(IN PCMHIVE Hive)
2007 {
2008 /* Sanity check */
2009 CMP_ASSERT_REGISTRY_LOCK_OR_LOADING(Hive);
2010 CMP_ASSERT_FLUSH_LOCK(Hive);
2011
2012 /* Release the lock */
2013 ExReleaseResourceLite(Hive->FlusherLock);
2014 }
2015
2016 BOOLEAN
2017 NTAPI
2018 CmpTestHiveFlusherLockShared(IN PCMHIVE Hive)
2019 {
2020 /* Test the lock */
2021 return !ExIsResourceAcquiredSharedLite(Hive->FlusherLock) ? FALSE : TRUE;
2022 }
2023
2024 BOOLEAN
2025 NTAPI
2026 CmpTestHiveFlusherLockExclusive(IN PCMHIVE Hive)
2027 {
2028 /* Test the lock */
2029 return !ExIsResourceAcquiredExclusiveLite(Hive->FlusherLock) ? FALSE : TRUE;
2030 }
2031
2032 VOID
2033 NTAPI
2034 CmpUnlockRegistry(VOID)
2035 {
2036 /* Sanity check */
2037 CMP_ASSERT_REGISTRY_LOCK();
2038
2039 /* Check if we should flush the registry */
2040 if (CmpFlushOnLockRelease)
2041 {
2042 /* The registry should be exclusively locked for this */
2043 CMP_ASSERT_EXCLUSIVE_REGISTRY_LOCK();
2044
2045 /* Flush the registry */
2046 CmpDoFlushAll(TRUE);
2047 CmpFlushOnLockRelease = FALSE;
2048 }
2049 else
2050 {
2051 /* Lazy flush the registry */
2052 CmpLazyFlush();
2053 }
2054
2055 /* Release the lock and leave the critical region */
2056 ExReleaseResourceLite(&CmpRegistryLock);
2057 KeLeaveCriticalRegion();
2058 }
2059
2060 VOID
2061 NTAPI
2062 CmpAcquireTwoKcbLocksExclusiveByKey(IN ULONG ConvKey1,
2063 IN ULONG ConvKey2)
2064 {
2065 ULONG Index1, Index2;
2066
2067 /* Sanity check */
2068 CMP_ASSERT_REGISTRY_LOCK();
2069
2070 /* Get hash indexes */
2071 Index1 = GET_HASH_INDEX(ConvKey1);
2072 Index2 = GET_HASH_INDEX(ConvKey2);
2073
2074 /* See which one is highest */
2075 if (Index1 < Index2)
2076 {
2077 /* Grab them in the proper order */
2078 CmpAcquireKcbLockExclusiveByKey(ConvKey1);
2079 CmpAcquireKcbLockExclusiveByKey(ConvKey2);
2080 }
2081 else
2082 {
2083 /* Grab the second one first, then the first */
2084 CmpAcquireKcbLockExclusiveByKey(ConvKey2);
2085 if (Index1 != Index2) CmpAcquireKcbLockExclusiveByKey(ConvKey1);
2086 }
2087 }
2088
2089 VOID
2090 NTAPI
2091 CmpReleaseTwoKcbLockByKey(IN ULONG ConvKey1,
2092 IN ULONG ConvKey2)
2093 {
2094 ULONG Index1, Index2;
2095
2096 /* Sanity check */
2097 CMP_ASSERT_REGISTRY_LOCK();
2098
2099 /* Get hash indexes */
2100 Index1 = GET_HASH_INDEX(ConvKey1);
2101 Index2 = GET_HASH_INDEX(ConvKey2);
2102 ASSERT((GET_HASH_ENTRY(CmpCacheTable, ConvKey2).Owner == KeGetCurrentThread()) ||
2103 (CmpTestRegistryLockExclusive()));
2104
2105 /* See which one is highest */
2106 if (Index1 < Index2)
2107 {
2108 /* Grab them in the proper order */
2109 ASSERT((GET_HASH_ENTRY(CmpCacheTable, ConvKey1).Owner == KeGetCurrentThread()) ||
2110 (CmpTestRegistryLockExclusive()));
2111 CmpReleaseKcbLockByKey(ConvKey2);
2112 CmpReleaseKcbLockByKey(ConvKey1);
2113 }
2114 else
2115 {
2116 /* Release the first one first, then the second */
2117 if (Index1 != Index2)
2118 {
2119 ASSERT((GET_HASH_ENTRY(CmpCacheTable, ConvKey1).Owner == KeGetCurrentThread()) ||
2120 (CmpTestRegistryLockExclusive()));
2121 CmpReleaseKcbLockByKey(ConvKey1);
2122 }
2123 CmpReleaseKcbLockByKey(ConvKey2);
2124 }
2125 }
2126
2127 VOID
2128 NTAPI
2129 CmShutdownSystem(VOID)
2130 {
2131 PLIST_ENTRY ListEntry;
2132 PCMHIVE Hive;
2133
2134 /* Kill the workers */
2135 if (!CmFirstTime) CmpShutdownWorkers();
2136
2137 /* Flush all hives */
2138 CmpLockRegistryExclusive();
2139 CmpDoFlushAll(TRUE);
2140
2141 /* Close all hive files */
2142 ListEntry = CmpHiveListHead.Flink;
2143 while (ListEntry != &CmpHiveListHead)
2144 {
2145 Hive = CONTAINING_RECORD(ListEntry, CMHIVE, HiveList);
2146
2147 CmpCloseHiveFiles(Hive);
2148
2149 ListEntry = ListEntry->Flink;
2150 }
2151
2152 CmpUnlockRegistry();
2153 }
2154
2155 VOID
2156 NTAPI
2157 CmpSetVersionData(VOID)
2158 {
2159 NTSTATUS Status;
2160 OBJECT_ATTRIBUTES ObjectAttributes;
2161 UNICODE_STRING KeyName;
2162 UNICODE_STRING ValueName;
2163 UNICODE_STRING ValueData;
2164 ANSI_STRING TempString;
2165 HANDLE SoftwareKeyHandle = NULL;
2166 HANDLE MicrosoftKeyHandle = NULL;
2167 HANDLE WindowsNtKeyHandle = NULL;
2168 HANDLE CurrentVersionKeyHandle = NULL;
2169 WCHAR Buffer[128]; // Buffer large enough to contain a full ULONG in decimal representation,
2170 // and the full 'CurrentType' string.
2171
2172 /*
2173 * Open the 'HKLM\Software\Microsoft\Windows NT\CurrentVersion' key
2174 * (create the intermediate subkeys if needed).
2175 */
2176
2177 RtlInitUnicodeString(&KeyName, L"\\REGISTRY\\MACHINE\\SOFTWARE");
2178 InitializeObjectAttributes(&ObjectAttributes,
2179 &KeyName,
2180 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2181 NULL,
2182 NULL);
2183 Status = NtCreateKey(&SoftwareKeyHandle,
2184 KEY_CREATE_SUB_KEY,
2185 &ObjectAttributes,
2186 0,
2187 NULL,
2188 0,
2189 NULL);
2190 if (!NT_SUCCESS(Status))
2191 {
2192 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2193 return;
2194 }
2195
2196 RtlInitUnicodeString(&KeyName, L"Microsoft");
2197 InitializeObjectAttributes(&ObjectAttributes,
2198 &KeyName,
2199 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2200 SoftwareKeyHandle,
2201 NULL);
2202 Status = NtCreateKey(&MicrosoftKeyHandle,
2203 KEY_CREATE_SUB_KEY,
2204 &ObjectAttributes,
2205 0,
2206 NULL,
2207 0,
2208 NULL);
2209 if (!NT_SUCCESS(Status))
2210 {
2211 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2212 goto Quit;
2213 }
2214
2215 RtlInitUnicodeString(&KeyName, L"Windows NT");
2216 InitializeObjectAttributes(&ObjectAttributes,
2217 &KeyName,
2218 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2219 MicrosoftKeyHandle,
2220 NULL);
2221 Status = NtCreateKey(&WindowsNtKeyHandle,
2222 KEY_CREATE_SUB_KEY,
2223 &ObjectAttributes,
2224 0,
2225 NULL,
2226 0,
2227 NULL);
2228 if (!NT_SUCCESS(Status))
2229 {
2230 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2231 goto Quit;
2232 }
2233
2234 RtlInitUnicodeString(&KeyName, L"CurrentVersion");
2235 InitializeObjectAttributes(&ObjectAttributes,
2236 &KeyName,
2237 OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
2238 WindowsNtKeyHandle,
2239 NULL);
2240 Status = NtCreateKey(&CurrentVersionKeyHandle,
2241 KEY_CREATE_SUB_KEY | KEY_SET_VALUE,
2242 &ObjectAttributes,
2243 0,
2244 NULL,
2245 0,
2246 NULL);
2247 if (!NT_SUCCESS(Status))
2248 {
2249 DPRINT1("Failed to create key %wZ (Status: %08lx)\n", &KeyName, Status);
2250 goto Quit;
2251 }
2252
2253 /* Set the 'CurrentVersion' value */
2254 RtlInitUnicodeString(&ValueName, L"CurrentVersion");
2255 NtSetValueKey(CurrentVersionKeyHandle,
2256 &ValueName,
2257 0,
2258 REG_SZ,
2259 CmVersionString.Buffer,
2260 CmVersionString.Length + sizeof(WCHAR));
2261
2262 /* Set the 'CurrentBuildNumber' value */
2263 RtlInitUnicodeString(&ValueName, L"CurrentBuildNumber");
2264 RtlInitEmptyUnicodeString(&ValueData, Buffer, sizeof(Buffer));
2265 RtlIntegerToUnicodeString(NtBuildNumber & 0xFFFF, 10, &ValueData);
2266 NtSetValueKey(CurrentVersionKeyHandle,
2267 &ValueName,
2268 0,
2269 REG_SZ,
2270 ValueData.Buffer,
2271 ValueData.Length + sizeof(WCHAR));
2272
2273 /* Set the 'BuildLab' value */
2274 RtlInitUnicodeString(&ValueName, L"BuildLab");
2275 RtlInitAnsiString(&TempString, NtBuildLab);
2276 Status = RtlAnsiStringToUnicodeString(&ValueData, &TempString, FALSE);
2277 if (NT_SUCCESS(Status))
2278 {
2279 NtSetValueKey(CurrentVersionKeyHandle,
2280 &ValueName,
2281 0,
2282 REG_SZ,
2283 ValueData.Buffer,
2284 ValueData.Length + sizeof(WCHAR));
2285 }
2286
2287 /* Set the 'CurrentType' value */
2288 RtlInitUnicodeString(&ValueName, L"CurrentType");
2289
2290 swprintf(Buffer, L"%s %s",
2291 #ifdef CONFIG_SMP
2292 L"Multiprocessor"
2293 #else
2294 L"Uniprocessor"
2295 #endif
2296 ,
2297 #if (DBG == 1)
2298 L"Checked"
2299 #else
2300 L"Free"
2301 #endif
2302 );
2303 RtlInitUnicodeString(&ValueData, Buffer);
2304 NtSetValueKey(CurrentVersionKeyHandle,
2305 &ValueName,
2306 0,
2307 REG_SZ,
2308 ValueData.Buffer,
2309 ValueData.Length + sizeof(WCHAR));
2310
2311 /* Set the 'CSDVersion' value */
2312 RtlInitUnicodeString(&ValueName, L"CSDVersion");
2313 if (CmCSDVersionString.Length != 0)
2314 {
2315 NtSetValueKey(CurrentVersionKeyHandle,
2316 &ValueName,
2317 0,
2318 REG_SZ,
2319 CmCSDVersionString.Buffer,
2320 CmCSDVersionString.Length + sizeof(WCHAR));
2321 }
2322 else
2323 {
2324 NtDeleteValueKey(CurrentVersionKeyHandle, &ValueName);
2325 }
2326
2327 /* Set the 'CSDBuildNumber' value */
2328 RtlInitUnicodeString(&ValueName, L"CSDBuildNumber");
2329 if (CmNtSpBuildNumber != 0)
2330 {
2331 RtlInitEmptyUnicodeString(&ValueData, Buffer, sizeof(Buffer));
2332 RtlIntegerToUnicodeString(CmNtSpBuildNumber, 10, &ValueData);
2333 NtSetValueKey(CurrentVersionKeyHandle,
2334 &ValueName,
2335 0,
2336 REG_SZ,
2337 ValueData.Buffer,
2338 ValueData.Length + sizeof(WCHAR));
2339 }
2340 else
2341 {
2342 NtDeleteValueKey(CurrentVersionKeyHandle, &ValueName);
2343 }
2344
2345 /* Set the 'SystemRoot' value */
2346 RtlInitUnicodeString(&ValueName, L"SystemRoot");
2347 NtSetValueKey(CurrentVersionKeyHandle,
2348 &ValueName,
2349 0,
2350 REG_SZ,
2351 NtSystemRoot.Buffer,
2352 NtSystemRoot.Length + sizeof(WCHAR));
2353
2354 Quit:
2355 /* Close the keys */
2356 if (CurrentVersionKeyHandle != NULL)
2357 NtClose(CurrentVersionKeyHandle);
2358
2359 if (WindowsNtKeyHandle != NULL)
2360 NtClose(WindowsNtKeyHandle);
2361
2362 if (MicrosoftKeyHandle != NULL)
2363 NtClose(MicrosoftKeyHandle);
2364
2365 if (SoftwareKeyHandle != NULL)
2366 NtClose(SoftwareKeyHandle);
2367 }
2368
2369 /* EOF */