3e2066dc4823649c9b7663ab2a001c8f83f2bb1c
[reactos.git] / reactos / ntoskrnl / ex / init.c
1 /*
2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ex/init.c
5 * PURPOSE: Executive Initialization Code
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
7 * Eric Kohl
8 */
9
10 /* INCLUDES ******************************************************************/
11
12 #include <ntoskrnl.h>
13 #define NDEBUG
14 #include <debug.h>
15 #include "ntstrsafe.h"
16
17 /* Temporary hack */
18 BOOLEAN
19 NTAPI
20 MmArmInitSystem(
21 IN ULONG Phase,
22 IN PLOADER_PARAMETER_BLOCK LoaderBlock
23 );
24
25 typedef struct _INIT_BUFFER
26 {
27 WCHAR DebugBuffer[256];
28 CHAR VersionBuffer[256];
29 CHAR BootlogHeader[256];
30 CHAR VersionNumber[24];
31 RTL_USER_PROCESS_INFORMATION ProcessInfo;
32 WCHAR RegistryBuffer[256];
33 } INIT_BUFFER, *PINIT_BUFFER;
34
35 /* DATA **********************************************************************/
36
37 /* NT Version Info */
38 ULONG NtMajorVersion = VER_PRODUCTMAJORVERSION;
39 ULONG NtMinorVersion = VER_PRODUCTMINORVERSION;
40 #if DBG
41 ULONG NtBuildNumber = VER_PRODUCTBUILD | 0xC0000000;
42 #else
43 ULONG NtBuildNumber = VER_PRODUCTBUILD;
44 #endif
45
46 /* NT System Info */
47 ULONG NtGlobalFlag;
48 ULONG ExSuiteMask;
49
50 /* Cm Version Info */
51 ULONG CmNtSpBuildNumber;
52 ULONG CmNtCSDVersion;
53 ULONG CmNtCSDReleaseType;
54 UNICODE_STRING CmVersionString;
55 UNICODE_STRING CmCSDVersionString;
56 CHAR NtBuildLab[] = KERNEL_VERSION_BUILD_STR;
57
58 /* Init flags and settings */
59 ULONG ExpInitializationPhase;
60 BOOLEAN ExpInTextModeSetup;
61 BOOLEAN IoRemoteBootClient;
62 ULONG InitSafeBootMode;
63 BOOLEAN InitIsWinPEMode, InitWinPEModeType;
64
65 /* NT Boot Path */
66 UNICODE_STRING NtSystemRoot;
67
68 /* NT Initial User Application */
69 WCHAR NtInitialUserProcessBuffer[128] = L"\\SystemRoot\\System32\\smss.exe";
70 ULONG NtInitialUserProcessBufferLength = sizeof(NtInitialUserProcessBuffer) -
71 sizeof(WCHAR);
72 ULONG NtInitialUserProcessBufferType = REG_SZ;
73
74 /* Boot NLS information */
75 PVOID ExpNlsTableBase;
76 ULONG ExpAnsiCodePageDataOffset, ExpOemCodePageDataOffset;
77 ULONG ExpUnicodeCaseTableDataOffset;
78 NLSTABLEINFO ExpNlsTableInfo;
79 SIZE_T ExpNlsTableSize;
80 PVOID ExpNlsSectionPointer;
81
82 /* CMOS Timer Sanity */
83 BOOLEAN ExCmosClockIsSane = TRUE;
84 BOOLEAN ExpRealTimeIsUniversal;
85
86 /* FUNCTIONS ****************************************************************/
87
88 NTSTATUS
89 NTAPI
90 INIT_FUNCTION
91 ExpCreateSystemRootLink(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
92 {
93 UNICODE_STRING LinkName;
94 OBJECT_ATTRIBUTES ObjectAttributes;
95 HANDLE LinkHandle;
96 NTSTATUS Status;
97 ANSI_STRING AnsiName;
98 CHAR Buffer[256];
99 ANSI_STRING TargetString;
100 UNICODE_STRING TargetName;
101
102 /* Initialize the ArcName tree */
103 RtlInitUnicodeString(&LinkName, L"\\ArcName");
104 InitializeObjectAttributes(&ObjectAttributes,
105 &LinkName,
106 OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
107 NULL,
108 SePublicDefaultUnrestrictedSd);
109
110 /* Create it */
111 Status = NtCreateDirectoryObject(&LinkHandle,
112 DIRECTORY_ALL_ACCESS,
113 &ObjectAttributes);
114 if (!NT_SUCCESS(Status))
115 {
116 /* Failed */
117 KeBugCheckEx(SYMBOLIC_INITIALIZATION_FAILED, Status, 1, 0, 0);
118 }
119
120 /* Close the LinkHandle */
121 NtClose(LinkHandle);
122
123 /* Initialize the Device tree */
124 RtlInitUnicodeString(&LinkName, L"\\Device");
125 InitializeObjectAttributes(&ObjectAttributes,
126 &LinkName,
127 OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
128 NULL,
129 SePublicDefaultUnrestrictedSd);
130
131 /* Create it */
132 Status = NtCreateDirectoryObject(&LinkHandle,
133 DIRECTORY_ALL_ACCESS,
134 &ObjectAttributes);
135 if (!NT_SUCCESS(Status))
136 {
137 /* Failed */
138 KeBugCheckEx(SYMBOLIC_INITIALIZATION_FAILED, Status, 2, 0, 0);
139 }
140
141 /* Close the LinkHandle */
142 ObCloseHandle(LinkHandle, KernelMode);
143
144 /* Create the system root symlink name */
145 RtlInitAnsiString(&AnsiName, "\\SystemRoot");
146 Status = RtlAnsiStringToUnicodeString(&LinkName, &AnsiName, TRUE);
147 if (!NT_SUCCESS(Status))
148 {
149 /* Failed */
150 KeBugCheckEx(SYMBOLIC_INITIALIZATION_FAILED, Status, 3, 0, 0);
151 }
152
153 /* Initialize the attributes for the link */
154 InitializeObjectAttributes(&ObjectAttributes,
155 &LinkName,
156 OBJ_CASE_INSENSITIVE | OBJ_PERMANENT,
157 NULL,
158 SePublicDefaultUnrestrictedSd);
159
160 /* Build the ARC name */
161 sprintf(Buffer,
162 "\\ArcName\\%s%s",
163 LoaderBlock->ArcBootDeviceName,
164 LoaderBlock->NtBootPathName);
165 Buffer[strlen(Buffer) - 1] = ANSI_NULL;
166
167 /* Convert it to Unicode */
168 RtlInitString(&TargetString, Buffer);
169 Status = RtlAnsiStringToUnicodeString(&TargetName,
170 &TargetString,
171 TRUE);
172 if (!NT_SUCCESS(Status))
173 {
174 /* We failed, bugcheck */
175 KeBugCheckEx(SYMBOLIC_INITIALIZATION_FAILED, Status, 4, 0, 0);
176 }
177
178 /* Create it */
179 Status = NtCreateSymbolicLinkObject(&LinkHandle,
180 SYMBOLIC_LINK_ALL_ACCESS,
181 &ObjectAttributes,
182 &TargetName);
183
184 /* Free the strings */
185 RtlFreeUnicodeString(&LinkName);
186 RtlFreeUnicodeString(&TargetName);
187
188 /* Check if creating the link failed */
189 if (!NT_SUCCESS(Status))
190 {
191 /* Failed */
192 KeBugCheckEx(SYMBOLIC_INITIALIZATION_FAILED, Status, 5, 0, 0);
193 }
194
195 /* Close the handle and return success */
196 ObCloseHandle(LinkHandle, KernelMode);
197 return STATUS_SUCCESS;
198 }
199
200 VOID
201 NTAPI
202 INIT_FUNCTION
203 ExpInitNls(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
204 {
205 LARGE_INTEGER SectionSize;
206 NTSTATUS Status;
207 HANDLE NlsSection;
208 PVOID SectionBase = NULL;
209 SIZE_T ViewSize = 0;
210 LARGE_INTEGER SectionOffset = {{0, 0}};
211 PLIST_ENTRY ListHead, NextEntry;
212 PMEMORY_ALLOCATION_DESCRIPTOR MdBlock;
213 ULONG NlsTablesEncountered = 0;
214 ULONG NlsTableSizes[3]; /* 3 NLS tables */
215
216 /* Check if this is boot-time phase 0 initialization */
217 if (!ExpInitializationPhase)
218 {
219 /* Loop the memory descriptors */
220 ListHead = &LoaderBlock->MemoryDescriptorListHead;
221 NextEntry = ListHead->Flink;
222 while (NextEntry != ListHead)
223 {
224 /* Get the current block */
225 MdBlock = CONTAINING_RECORD(NextEntry,
226 MEMORY_ALLOCATION_DESCRIPTOR,
227 ListEntry);
228
229 /* Check if this is an NLS block */
230 if (MdBlock->MemoryType == LoaderNlsData)
231 {
232 /* Increase the table size */
233 ExpNlsTableSize += MdBlock->PageCount * PAGE_SIZE;
234
235 /* FreeLdr-specific */
236 NlsTableSizes[NlsTablesEncountered] = MdBlock->PageCount * PAGE_SIZE;
237 NlsTablesEncountered++;
238 ASSERT(NlsTablesEncountered < 4);
239 }
240
241 /* Go to the next block */
242 NextEntry = MdBlock->ListEntry.Flink;
243 }
244
245 /* Allocate the a new buffer since loader memory will be freed */
246 ExpNlsTableBase = ExAllocatePoolWithTag(NonPagedPool,
247 ExpNlsTableSize,
248 'iltR');
249 if (!ExpNlsTableBase) KeBugCheck(PHASE0_INITIALIZATION_FAILED);
250
251 /* Copy the codepage data in its new location. */
252 if (NlsTablesEncountered == 1)
253 {
254 /* Ntldr-way boot process */
255 RtlCopyMemory(ExpNlsTableBase,
256 LoaderBlock->NlsData->AnsiCodePageData,
257 ExpNlsTableSize);
258 }
259 else
260 {
261 /*
262 * In NT, the memory blocks are contiguous, but in ReactOS they aren't,
263 * so unless someone fixes FreeLdr, we'll have to use this icky hack.
264 */
265 RtlCopyMemory(ExpNlsTableBase,
266 LoaderBlock->NlsData->AnsiCodePageData,
267 NlsTableSizes[0]);
268
269 RtlCopyMemory((PVOID)((ULONG_PTR)ExpNlsTableBase + NlsTableSizes[0]),
270 LoaderBlock->NlsData->OemCodePageData,
271 NlsTableSizes[1]);
272
273 RtlCopyMemory((PVOID)((ULONG_PTR)ExpNlsTableBase + NlsTableSizes[0] +
274 NlsTableSizes[1]),
275 LoaderBlock->NlsData->UnicodeCodePageData,
276 NlsTableSizes[2]);
277 /* End of Hack */
278 }
279
280 /* Initialize and reset the NLS TAbles */
281 RtlInitNlsTables((PVOID)((ULONG_PTR)ExpNlsTableBase +
282 ExpAnsiCodePageDataOffset),
283 (PVOID)((ULONG_PTR)ExpNlsTableBase +
284 ExpOemCodePageDataOffset),
285 (PVOID)((ULONG_PTR)ExpNlsTableBase +
286 ExpUnicodeCaseTableDataOffset),
287 &ExpNlsTableInfo);
288 RtlResetRtlTranslations(&ExpNlsTableInfo);
289 return;
290 }
291
292 /* Set the section size */
293 SectionSize.QuadPart = ExpNlsTableSize;
294
295 /* Create the NLS Section */
296 Status = ZwCreateSection(&NlsSection,
297 SECTION_ALL_ACCESS,
298 NULL,
299 &SectionSize,
300 PAGE_READWRITE,
301 SEC_COMMIT,
302 NULL);
303 if (!NT_SUCCESS(Status))
304 {
305 /* Failed */
306 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 1, 0, 0);
307 }
308
309 /* Get a pointer to the section */
310 Status = ObReferenceObjectByHandle(NlsSection,
311 SECTION_ALL_ACCESS,
312 MmSectionObjectType,
313 KernelMode,
314 &ExpNlsSectionPointer,
315 NULL);
316 ObCloseHandle(NlsSection, KernelMode);
317 if (!NT_SUCCESS(Status))
318 {
319 /* Failed */
320 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 2, 0, 0);
321 }
322
323 /* Map the NLS Section in system space */
324 Status = MmMapViewInSystemSpace(ExpNlsSectionPointer,
325 &SectionBase,
326 &ExpNlsTableSize);
327 if (!NT_SUCCESS(Status))
328 {
329 /* Failed */
330 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 3, 0, 0);
331 }
332
333 /* Copy the codepage data in its new location. */
334 ASSERT(SectionBase > MmSystemRangeStart);
335 RtlCopyMemory(SectionBase, ExpNlsTableBase, ExpNlsTableSize);
336
337 /* Free the previously allocated buffer and set the new location */
338 ExFreePoolWithTag(ExpNlsTableBase, 'iltR');
339 ExpNlsTableBase = SectionBase;
340
341 /* Initialize the NLS Tables */
342 RtlInitNlsTables((PVOID)((ULONG_PTR)ExpNlsTableBase +
343 ExpAnsiCodePageDataOffset),
344 (PVOID)((ULONG_PTR)ExpNlsTableBase +
345 ExpOemCodePageDataOffset),
346 (PVOID)((ULONG_PTR)ExpNlsTableBase +
347 ExpUnicodeCaseTableDataOffset),
348 &ExpNlsTableInfo);
349 RtlResetRtlTranslations(&ExpNlsTableInfo);
350
351 /* Reset the base to 0 */
352 SectionBase = NULL;
353
354 /* Map the section in the system process */
355 Status = MmMapViewOfSection(ExpNlsSectionPointer,
356 PsGetCurrentProcess(),
357 &SectionBase,
358 0L,
359 0L,
360 &SectionOffset,
361 &ViewSize,
362 ViewShare,
363 0L,
364 PAGE_READWRITE);
365 if (!NT_SUCCESS(Status))
366 {
367 /* Failed */
368 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 5, 0, 0);
369 }
370
371 /* Copy the table into the system process and set this as the base */
372 RtlCopyMemory(SectionBase, ExpNlsTableBase, ExpNlsTableSize);
373 ExpNlsTableBase = SectionBase;
374 }
375
376 VOID
377 NTAPI
378 INIT_FUNCTION
379 ExpLoadInitialProcess(IN PINIT_BUFFER InitBuffer,
380 OUT PRTL_USER_PROCESS_PARAMETERS *ProcessParameters,
381 OUT PCHAR *ProcessEnvironment)
382 {
383 NTSTATUS Status;
384 SIZE_T Size;
385 PWSTR p;
386 UNICODE_STRING NullString = RTL_CONSTANT_STRING(L"");
387 UNICODE_STRING SmssName, Environment, SystemDriveString, DebugString;
388 PVOID EnvironmentPtr = NULL;
389 PRTL_USER_PROCESS_INFORMATION ProcessInformation;
390 PRTL_USER_PROCESS_PARAMETERS ProcessParams = NULL;
391
392 NullString.Length = sizeof(WCHAR);
393
394 /* Use the initial buffer, after the strings */
395 ProcessInformation = &InitBuffer->ProcessInfo;
396
397 /* Allocate memory for the process parameters */
398 Size = sizeof(*ProcessParams) + ((MAX_PATH * 6) * sizeof(WCHAR));
399 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
400 (PVOID*)&ProcessParams,
401 0,
402 &Size,
403 MEM_COMMIT,
404 PAGE_READWRITE);
405 if (!NT_SUCCESS(Status))
406 {
407 /* Failed, display error */
408 p = InitBuffer->DebugBuffer;
409 _snwprintf(p,
410 256 * sizeof(WCHAR),
411 L"INIT: Unable to allocate Process Parameters. 0x%lx",
412 Status);
413 RtlInitUnicodeString(&DebugString, p);
414 ZwDisplayString(&DebugString);
415
416 /* Bugcheck the system */
417 KeBugCheckEx(SESSION1_INITIALIZATION_FAILED, Status, 0, 0, 0);
418 }
419
420 /* Setup the basic header, and give the process the low 1MB to itself */
421 ProcessParams->Length = Size;
422 ProcessParams->MaximumLength = Size;
423 ProcessParams->Flags = RTL_USER_PROCESS_PARAMETERS_NORMALIZED |
424 RTL_USER_PROCESS_PARAMETERS_RESERVE_1MB;
425
426 /* Allocate a page for the environment */
427 Size = PAGE_SIZE;
428 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
429 &EnvironmentPtr,
430 0,
431 &Size,
432 MEM_COMMIT,
433 PAGE_READWRITE);
434 if (!NT_SUCCESS(Status))
435 {
436 /* Failed, display error */
437 p = InitBuffer->DebugBuffer;
438 _snwprintf(p,
439 256 * sizeof(WCHAR),
440 L"INIT: Unable to allocate Process Environment. 0x%lx",
441 Status);
442 RtlInitUnicodeString(&DebugString, p);
443 ZwDisplayString(&DebugString);
444
445 /* Bugcheck the system */
446 KeBugCheckEx(SESSION2_INITIALIZATION_FAILED, Status, 0, 0, 0);
447 }
448
449 /* Write the pointer */
450 ProcessParams->Environment = EnvironmentPtr;
451
452 /* Make a buffer for the DOS path */
453 p = (PWSTR)(ProcessParams + 1);
454 ProcessParams->CurrentDirectory.DosPath.Buffer = p;
455 ProcessParams->CurrentDirectory.DosPath.MaximumLength = MAX_PATH *
456 sizeof(WCHAR);
457
458 /* Copy the DOS path */
459 RtlCopyUnicodeString(&ProcessParams->CurrentDirectory.DosPath,
460 &NtSystemRoot);
461
462 /* Make a buffer for the DLL Path */
463 p = (PWSTR)((PCHAR)ProcessParams->CurrentDirectory.DosPath.Buffer +
464 ProcessParams->CurrentDirectory.DosPath.MaximumLength);
465 ProcessParams->DllPath.Buffer = p;
466 ProcessParams->DllPath.MaximumLength = MAX_PATH * sizeof(WCHAR);
467
468 /* Copy the DLL path and append the system32 directory */
469 RtlCopyUnicodeString(&ProcessParams->DllPath,
470 &ProcessParams->CurrentDirectory.DosPath);
471 RtlAppendUnicodeToString(&ProcessParams->DllPath, L"\\System32");
472
473 /* Make a buffer for the image name */
474 p = (PWSTR)((PCHAR)ProcessParams->DllPath.Buffer +
475 ProcessParams->DllPath.MaximumLength);
476 ProcessParams->ImagePathName.Buffer = p;
477 ProcessParams->ImagePathName.MaximumLength = MAX_PATH * sizeof(WCHAR);
478
479 /* Make sure the buffer is a valid string which within the given length */
480 if ((NtInitialUserProcessBufferType != REG_SZ) ||
481 ((NtInitialUserProcessBufferLength != MAXULONG) &&
482 ((NtInitialUserProcessBufferLength < sizeof(WCHAR)) ||
483 (NtInitialUserProcessBufferLength >
484 sizeof(NtInitialUserProcessBuffer) - sizeof(WCHAR)))))
485 {
486 /* Invalid initial process string, bugcheck */
487 KeBugCheckEx(SESSION2_INITIALIZATION_FAILED,
488 STATUS_INVALID_PARAMETER,
489 NtInitialUserProcessBufferType,
490 NtInitialUserProcessBufferLength,
491 sizeof(NtInitialUserProcessBuffer));
492 }
493
494 /* Cut out anything after a space */
495 p = NtInitialUserProcessBuffer;
496 while ((*p) && (*p != L' ')) p++;
497
498 /* Set the image path length */
499 ProcessParams->ImagePathName.Length =
500 (USHORT)((PCHAR)p - (PCHAR)NtInitialUserProcessBuffer);
501
502 /* Copy the actual buffer */
503 RtlCopyMemory(ProcessParams->ImagePathName.Buffer,
504 NtInitialUserProcessBuffer,
505 ProcessParams->ImagePathName.Length);
506
507 /* Null-terminate it */
508 ProcessParams->ImagePathName.Buffer[ProcessParams->ImagePathName.Length /
509 sizeof(WCHAR)] = UNICODE_NULL;
510
511 /* Make a buffer for the command line */
512 p = (PWSTR)((PCHAR)ProcessParams->ImagePathName.Buffer +
513 ProcessParams->ImagePathName.MaximumLength);
514 ProcessParams->CommandLine.Buffer = p;
515 ProcessParams->CommandLine.MaximumLength = MAX_PATH * sizeof(WCHAR);
516
517 /* Add the image name to the command line */
518 RtlAppendUnicodeToString(&ProcessParams->CommandLine,
519 NtInitialUserProcessBuffer);
520
521 /* Create the environment string */
522 RtlInitEmptyUnicodeString(&Environment,
523 ProcessParams->Environment,
524 (USHORT)Size);
525
526 /* Append the DLL path to it */
527 RtlAppendUnicodeToString(&Environment, L"Path=" );
528 RtlAppendUnicodeStringToString(&Environment, &ProcessParams->DllPath);
529 RtlAppendUnicodeStringToString(&Environment, &NullString);
530
531 /* Create the system drive string */
532 SystemDriveString = NtSystemRoot;
533 SystemDriveString.Length = 2 * sizeof(WCHAR);
534
535 /* Append it to the environment */
536 RtlAppendUnicodeToString(&Environment, L"SystemDrive=");
537 RtlAppendUnicodeStringToString(&Environment, &SystemDriveString);
538 RtlAppendUnicodeStringToString(&Environment, &NullString);
539
540 /* Append the system root to the environment */
541 RtlAppendUnicodeToString(&Environment, L"SystemRoot=");
542 RtlAppendUnicodeStringToString(&Environment, &NtSystemRoot);
543 RtlAppendUnicodeStringToString(&Environment, &NullString);
544
545 /* Prepare the prefetcher */
546 //CcPfBeginBootPhase(150);
547
548 /* Create SMSS process */
549 SmssName = ProcessParams->ImagePathName;
550 Status = RtlCreateUserProcess(&SmssName,
551 OBJ_CASE_INSENSITIVE,
552 RtlDeNormalizeProcessParams(ProcessParams),
553 NULL,
554 NULL,
555 NULL,
556 FALSE,
557 NULL,
558 NULL,
559 ProcessInformation);
560 if (!NT_SUCCESS(Status))
561 {
562 /* Failed, display error */
563 p = InitBuffer->DebugBuffer;
564 _snwprintf(p,
565 256 * sizeof(WCHAR),
566 L"INIT: Unable to create Session Manager. 0x%lx",
567 Status);
568 RtlInitUnicodeString(&DebugString, p);
569 ZwDisplayString(&DebugString);
570
571 /* Bugcheck the system */
572 KeBugCheckEx(SESSION3_INITIALIZATION_FAILED, Status, 0, 0, 0);
573 }
574
575 /* Resume the thread */
576 Status = ZwResumeThread(ProcessInformation->ThreadHandle, NULL);
577 if (!NT_SUCCESS(Status))
578 {
579 /* Failed, display error */
580 p = InitBuffer->DebugBuffer;
581 _snwprintf(p,
582 256 * sizeof(WCHAR),
583 L"INIT: Unable to resume Session Manager. 0x%lx",
584 Status);
585 RtlInitUnicodeString(&DebugString, p);
586 ZwDisplayString(&DebugString);
587
588 /* Bugcheck the system */
589 KeBugCheckEx(SESSION4_INITIALIZATION_FAILED, Status, 0, 0, 0);
590 }
591
592 /* Return success */
593 *ProcessParameters = ProcessParams;
594 *ProcessEnvironment = EnvironmentPtr;
595 }
596
597 ULONG
598 NTAPI
599 INIT_FUNCTION
600 ExComputeTickCountMultiplier(IN ULONG ClockIncrement)
601 {
602 ULONG MsRemainder = 0, MsIncrement;
603 ULONG IncrementRemainder;
604 ULONG i;
605
606 /* Count the number of milliseconds for each clock interrupt */
607 MsIncrement = ClockIncrement / (10 * 1000);
608
609 /* Count the remainder from the division above, with 24-bit precision */
610 IncrementRemainder = ClockIncrement - (MsIncrement * (10 * 1000));
611 for (i= 0; i < 24; i++)
612 {
613 /* Shift the remainders */
614 MsRemainder <<= 1;
615 IncrementRemainder <<= 1;
616
617 /* Check if we've went past 1 ms */
618 if (IncrementRemainder >= (10 * 1000))
619 {
620 /* Increase the remainder by one, and substract from increment */
621 IncrementRemainder -= (10 * 1000);
622 MsRemainder |= 1;
623 }
624 }
625
626 /* Return the increment */
627 return (MsIncrement << 24) | MsRemainder;
628 }
629
630 BOOLEAN
631 NTAPI
632 INIT_FUNCTION
633 ExpInitSystemPhase0(VOID)
634 {
635 /* Initialize EXRESOURCE Support */
636 ExpResourceInitialization();
637
638 /* Initialize the environment lock */
639 ExInitializeFastMutex(&ExpEnvironmentLock);
640
641 /* Initialize the lookaside lists and locks */
642 ExpInitLookasideLists();
643
644 /* Initialize the Firmware Table resource and listhead */
645 InitializeListHead(&ExpFirmwareTableProviderListHead);
646 ExInitializeResourceLite(&ExpFirmwareTableResource);
647
648 /* Set the suite mask to maximum and return */
649 ExSuiteMask = 0xFFFFFFFF;
650 return TRUE;
651 }
652
653 BOOLEAN
654 NTAPI
655 INIT_FUNCTION
656 ExpInitSystemPhase1(VOID)
657 {
658 /* Initialize worker threads */
659 ExpInitializeWorkerThreads();
660
661 /* Initialize pushlocks */
662 ExpInitializePushLocks();
663
664 /* Initialize events and event pairs */
665 ExpInitializeEventImplementation();
666 ExpInitializeEventPairImplementation();
667
668 /* Initialize callbacks */
669 ExpInitializeCallbacks();
670
671 /* Initialize mutants */
672 ExpInitializeMutantImplementation();
673
674 /* Initialize semaphores */
675 ExpInitializeSemaphoreImplementation();
676
677 /* Initialize timers */
678 ExpInitializeTimerImplementation();
679
680 /* Initialize profiling */
681 ExpInitializeProfileImplementation();
682
683 /* Initialize UUIDs */
684 ExpInitUuids();
685
686 /* Initialize Win32K */
687 ExpWin32kInit();
688 return TRUE;
689 }
690
691 BOOLEAN
692 NTAPI
693 INIT_FUNCTION
694 ExInitSystem(VOID)
695 {
696 /* Check the initialization phase */
697 switch (ExpInitializationPhase)
698 {
699 case 0:
700
701 /* Do Phase 0 */
702 return ExpInitSystemPhase0();
703
704 case 1:
705
706 /* Do Phase 1 */
707 return ExpInitSystemPhase1();
708
709 default:
710
711 /* Don't know any other phase! Bugcheck! */
712 KeBugCheck(UNEXPECTED_INITIALIZATION_CALL);
713 return FALSE;
714 }
715 }
716
717 BOOLEAN
718 NTAPI
719 INIT_FUNCTION
720 ExpIsLoaderValid(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
721 {
722 PLOADER_PARAMETER_EXTENSION Extension;
723
724 /* Get the loader extension */
725 Extension = LoaderBlock->Extension;
726
727 /* Validate the size (larger structures are OK, we'll just ignore them) */
728 if (Extension->Size < sizeof(LOADER_PARAMETER_EXTENSION)) return FALSE;
729
730 /* Don't validate upper versions */
731 if (Extension->MajorVersion > VER_PRODUCTMAJORVERSION) return TRUE;
732
733 /* Fail if this is NT 4 */
734 if (Extension->MajorVersion < VER_PRODUCTMAJORVERSION) return FALSE;
735
736 /* Fail if this is XP */
737 if (Extension->MinorVersion < VER_PRODUCTMINORVERSION) return FALSE;
738
739 /* This is 2003 or newer, approve it */
740 return TRUE;
741 }
742
743 VOID
744 NTAPI
745 INIT_FUNCTION
746 ExpLoadBootSymbols(IN PLOADER_PARAMETER_BLOCK LoaderBlock)
747 {
748 ULONG i = 0;
749 PLIST_ENTRY NextEntry;
750 ULONG Count, Length;
751 PWCHAR Name;
752 PLDR_DATA_TABLE_ENTRY LdrEntry;
753 BOOLEAN OverFlow = FALSE;
754 CHAR NameBuffer[256];
755 STRING SymbolString;
756
757 /* Loop the driver list */
758 NextEntry = LoaderBlock->LoadOrderListHead.Flink;
759 while (NextEntry != &LoaderBlock->LoadOrderListHead)
760 {
761 /* Skip the first two images */
762 if (i >= 2)
763 {
764 /* Get the entry */
765 LdrEntry = CONTAINING_RECORD(NextEntry,
766 LDR_DATA_TABLE_ENTRY,
767 InLoadOrderLinks);
768 if (LdrEntry->FullDllName.Buffer[0] == L'\\')
769 {
770 /* We have a name, read its data */
771 Name = LdrEntry->FullDllName.Buffer;
772 Length = LdrEntry->FullDllName.Length / sizeof(WCHAR);
773
774 /* Check if our buffer can hold it */
775 if (sizeof(NameBuffer) < Length + sizeof(ANSI_NULL))
776 {
777 /* It's too long */
778 OverFlow = TRUE;
779 }
780 else
781 {
782 /* Copy the name */
783 Count = 0;
784 do
785 {
786 /* Copy the character */
787 NameBuffer[Count++] = (CHAR)*Name++;
788 } while (Count < Length);
789
790 /* Null-terminate */
791 NameBuffer[Count] = ANSI_NULL;
792 }
793 }
794 else
795 {
796 /* This should be a driver, check if it fits */
797 if (sizeof(NameBuffer) <
798 (sizeof("\\System32\\Drivers\\") +
799 NtSystemRoot.Length / sizeof(WCHAR) - sizeof(UNICODE_NULL) +
800 LdrEntry->BaseDllName.Length / sizeof(WCHAR) +
801 sizeof(ANSI_NULL)))
802 {
803 /* Buffer too small */
804 OverFlow = TRUE;
805 while (TRUE);
806 }
807 else
808 {
809 /* Otherwise build the name. HACKED for GCC :( */
810 sprintf(NameBuffer,
811 "%S\\System32\\Drivers\\%S",
812 &SharedUserData->NtSystemRoot[2],
813 LdrEntry->BaseDllName.Buffer);
814 }
815 }
816
817 /* Check if the buffer was ok */
818 if (!OverFlow)
819 {
820 /* Initialize the STRING for the debugger */
821 RtlInitString(&SymbolString, NameBuffer);
822
823 /* Load the symbols */
824 DbgLoadImageSymbols(&SymbolString,
825 LdrEntry->DllBase,
826 (ULONG_PTR)ZwCurrentProcess());
827 }
828 }
829
830 /* Go to the next entry */
831 i++;
832 NextEntry = NextEntry->Flink;
833 }
834 }
835
836 VOID
837 NTAPI
838 INIT_FUNCTION
839 ExBurnMemory(IN PLOADER_PARAMETER_BLOCK LoaderBlock,
840 IN ULONG PagesToDestroy,
841 IN TYPE_OF_MEMORY MemoryType)
842 {
843 PLIST_ENTRY ListEntry;
844 PMEMORY_ALLOCATION_DESCRIPTOR MemDescriptor;
845
846 DPRINT1("Burn RAM amount: %d pages\n", PagesToDestroy);
847
848 /* Loop the memory descriptors, beginning at the end */
849 for (ListEntry = LoaderBlock->MemoryDescriptorListHead.Blink;
850 ListEntry != &LoaderBlock->MemoryDescriptorListHead;
851 ListEntry = ListEntry->Blink)
852 {
853 /* Get the memory descriptor structure */
854 MemDescriptor = CONTAINING_RECORD(ListEntry,
855 MEMORY_ALLOCATION_DESCRIPTOR,
856 ListEntry);
857
858 /* Is memory free there or is it temporary? */
859 if (MemDescriptor->MemoryType == LoaderFree ||
860 MemDescriptor->MemoryType == LoaderFirmwareTemporary)
861 {
862 /* Check if the descriptor has more pages than we want */
863 if (MemDescriptor->PageCount > PagesToDestroy)
864 {
865 /* Change block's page count, ntoskrnl doesn't care much */
866 MemDescriptor->PageCount -= PagesToDestroy;
867 break;
868 }
869 else
870 {
871 /* Change block type */
872 MemDescriptor->MemoryType = MemoryType;
873 PagesToDestroy -= MemDescriptor->PageCount;
874
875 /* Check if we are done */
876 if (PagesToDestroy == 0) break;
877 }
878 }
879 }
880 }
881
882 VOID
883 NTAPI
884 INIT_FUNCTION
885 ExpInitializeExecutive(IN ULONG Cpu,
886 IN PLOADER_PARAMETER_BLOCK LoaderBlock)
887 {
888 PNLS_DATA_BLOCK NlsData;
889 CHAR Buffer[256];
890 ANSI_STRING AnsiPath;
891 NTSTATUS Status;
892 PCHAR CommandLine, PerfMem;
893 ULONG PerfMemUsed;
894 PLDR_DATA_TABLE_ENTRY NtosEntry;
895 PMESSAGE_RESOURCE_ENTRY MsgEntry;
896 ANSI_STRING CsdString;
897 SIZE_T Remaining = 0;
898 PCHAR RcEnd = NULL;
899 CHAR VersionBuffer [65];
900
901 /* Validate Loader */
902 if (!ExpIsLoaderValid(LoaderBlock))
903 {
904 /* Invalid loader version */
905 KeBugCheckEx(MISMATCHED_HAL,
906 3,
907 LoaderBlock->Extension->Size,
908 LoaderBlock->Extension->MajorVersion,
909 LoaderBlock->Extension->MinorVersion);
910 }
911
912 /* Initialize PRCB pool lookaside pointers */
913 ExInitPoolLookasidePointers();
914
915 /* Check if this is an application CPU */
916 if (Cpu)
917 {
918 /* Then simply initialize it with HAL */
919 if (!HalInitSystem(ExpInitializationPhase, LoaderBlock))
920 {
921 /* Initialization failed */
922 KeBugCheck(HAL_INITIALIZATION_FAILED);
923 }
924
925 /* We're done */
926 return;
927 }
928
929 /* Assume no text-mode or remote boot */
930 ExpInTextModeSetup = FALSE;
931 IoRemoteBootClient = FALSE;
932
933 /* Check if we have a setup loader block */
934 if (LoaderBlock->SetupLdrBlock)
935 {
936 /* Check if this is text-mode setup */
937 if (LoaderBlock->SetupLdrBlock->Flags & SETUPLDR_TEXT_MODE) ExpInTextModeSetup = TRUE;
938
939 /* Check if this is network boot */
940 if (LoaderBlock->SetupLdrBlock->Flags & SETUPLDR_REMOTE_BOOT)
941 {
942 /* Set variable */
943 IoRemoteBootClient = TRUE;
944
945 /* Make sure we're actually booting off the network */
946 ASSERT(!_memicmp(LoaderBlock->ArcBootDeviceName, "net(0)", 6));
947 }
948 }
949
950 /* Set phase to 0 */
951 ExpInitializationPhase = 0;
952
953 /* Get boot command line */
954 CommandLine = LoaderBlock->LoadOptions;
955 if (CommandLine)
956 {
957 /* Upcase it for comparison and check if we're in performance mode */
958 _strupr(CommandLine);
959 PerfMem = strstr(CommandLine, "PERFMEM");
960 if (PerfMem)
961 {
962 /* Check if the user gave a number of bytes to use */
963 PerfMem = strstr(PerfMem, "=");
964 if (PerfMem)
965 {
966 /* Read the number of pages we'll use */
967 PerfMemUsed = atol(PerfMem + 1) * (1024 * 1024 / PAGE_SIZE);
968 if (PerfMem)
969 {
970 /* FIXME: TODO */
971 DPRINT1("BBT performance mode not yet supported."
972 "/PERFMEM option ignored.\n");
973 }
974 }
975 }
976
977 /* Check if we're burning memory */
978 PerfMem = strstr(CommandLine, "BURNMEMORY");
979 if (PerfMem)
980 {
981 /* Check if the user gave a number of bytes to use */
982 PerfMem = strstr(PerfMem, "=");
983 if (PerfMem)
984 {
985 /* Read the number of pages we'll use */
986 PerfMemUsed = atol(PerfMem + 1) * (1024 * 1024 / PAGE_SIZE);
987 if (PerfMemUsed) ExBurnMemory(LoaderBlock, PerfMemUsed, LoaderBad);
988 }
989 }
990 }
991
992 /* Setup NLS Base and offsets */
993 NlsData = LoaderBlock->NlsData;
994 ExpNlsTableBase = NlsData->AnsiCodePageData;
995 ExpAnsiCodePageDataOffset = 0;
996 ExpOemCodePageDataOffset = ((ULONG_PTR)NlsData->OemCodePageData -
997 (ULONG_PTR)NlsData->AnsiCodePageData);
998 ExpUnicodeCaseTableDataOffset = ((ULONG_PTR)NlsData->UnicodeCodePageData -
999 (ULONG_PTR)NlsData->AnsiCodePageData);
1000
1001 /* Initialize the NLS Tables */
1002 RtlInitNlsTables((PVOID)((ULONG_PTR)ExpNlsTableBase +
1003 ExpAnsiCodePageDataOffset),
1004 (PVOID)((ULONG_PTR)ExpNlsTableBase +
1005 ExpOemCodePageDataOffset),
1006 (PVOID)((ULONG_PTR)ExpNlsTableBase +
1007 ExpUnicodeCaseTableDataOffset),
1008 &ExpNlsTableInfo);
1009 RtlResetRtlTranslations(&ExpNlsTableInfo);
1010
1011 /* Now initialize the HAL */
1012 if (!HalInitSystem(ExpInitializationPhase, LoaderBlock))
1013 {
1014 /* HAL failed to initialize, bugcheck */
1015 KeBugCheck(HAL_INITIALIZATION_FAILED);
1016 }
1017
1018 /* Make sure interrupts are active now */
1019 _enable();
1020
1021 /* Clear the crypto exponent */
1022 SharedUserData->CryptoExponent = 0;
1023
1024 /* Set global flags for the checked build */
1025 #if DBG
1026 NtGlobalFlag |= FLG_ENABLE_CLOSE_EXCEPTIONS |
1027 FLG_ENABLE_KDEBUG_SYMBOL_LOAD;
1028 #endif
1029
1030 /* Setup NT System Root Path */
1031 sprintf(Buffer, "C:%s", LoaderBlock->NtBootPathName);
1032
1033 /* Convert to ANSI_STRING and null-terminate it */
1034 RtlInitString(&AnsiPath, Buffer);
1035 Buffer[--AnsiPath.Length] = ANSI_NULL;
1036
1037 /* Get the string from KUSER_SHARED_DATA's buffer */
1038 RtlInitEmptyUnicodeString(&NtSystemRoot,
1039 SharedUserData->NtSystemRoot,
1040 sizeof(SharedUserData->NtSystemRoot));
1041
1042 /* Now fill it in */
1043 Status = RtlAnsiStringToUnicodeString(&NtSystemRoot, &AnsiPath, FALSE);
1044 if (!NT_SUCCESS(Status)) KeBugCheck(SESSION3_INITIALIZATION_FAILED);
1045
1046 /* Setup bugcheck messages */
1047 KiInitializeBugCheck();
1048
1049 /* Setup initial system settings */
1050 CmGetSystemControlValues(LoaderBlock->RegistryBase, CmControlVector);
1051
1052 /* Load static defaults for Service Pack 1 and add our SVN revision */
1053 CmNtCSDVersion = 0x100 | (KERNEL_VERSION_BUILD_HEX << 16);
1054 CmNtCSDReleaseType = 0;
1055
1056 /* Set Service Pack data for Service Pack 1 */
1057 CmNtSpBuildNumber = 1830;
1058 if (!(CmNtCSDVersion & 0xFFFF0000))
1059 {
1060 /* Check the release type */
1061 if (CmNtCSDReleaseType == 1) CmNtSpBuildNumber |= 1830 << 16;
1062 }
1063
1064 /* Add loaded CmNtGlobalFlag value */
1065 NtGlobalFlag |= CmNtGlobalFlag;
1066
1067 /* Initialize the executive at phase 0 */
1068 if (!ExInitSystem()) KeBugCheck(PHASE0_INITIALIZATION_FAILED);
1069
1070 /* Initialize the memory manager at phase 0 */
1071 if (!MmArmInitSystem(0, LoaderBlock)) KeBugCheck(PHASE0_INITIALIZATION_FAILED);
1072
1073 /* Load boot symbols */
1074 ExpLoadBootSymbols(LoaderBlock);
1075
1076 /* Check if we should break after symbol load */
1077 if (KdBreakAfterSymbolLoad) DbgBreakPointWithStatus(DBG_STATUS_CONTROL_C);
1078
1079 /* Check if this loader is compatible with NT 5.2 */
1080 if (LoaderBlock->Extension->Size >= sizeof(LOADER_PARAMETER_EXTENSION))
1081 {
1082 /* Setup headless terminal settings */
1083 HeadlessInit(LoaderBlock);
1084 }
1085
1086 /* Set system ranges */
1087 SharedUserData->Reserved1 = (ULONG_PTR)MmHighestUserAddress;
1088 SharedUserData->Reserved3 = (ULONG_PTR)MmSystemRangeStart;
1089
1090 /* Make a copy of the NLS Tables */
1091 ExpInitNls(LoaderBlock);
1092
1093 /* Get the kernel's load entry */
1094 NtosEntry = CONTAINING_RECORD(LoaderBlock->LoadOrderListHead.Flink,
1095 LDR_DATA_TABLE_ENTRY,
1096 InLoadOrderLinks);
1097
1098 /* Check if this is a service pack */
1099 if (CmNtCSDVersion & 0xFFFF)
1100 {
1101 /* Get the service pack string */
1102 Status = RtlFindMessage(NtosEntry->DllBase,
1103 11,
1104 0,
1105 WINDOWS_NT_CSD_STRING,
1106 &MsgEntry);
1107 if (NT_SUCCESS(Status))
1108 {
1109 /* Setup the string */
1110 RtlInitAnsiString(&CsdString, (PCHAR)MsgEntry->Text);
1111
1112 /* Remove trailing newline */
1113 while ((CsdString.Length > 0) &&
1114 ((CsdString.Buffer[CsdString.Length - 1] == '\r') ||
1115 (CsdString.Buffer[CsdString.Length - 1] == '\n')))
1116 {
1117 /* Skip the trailing character */
1118 CsdString.Length--;
1119 }
1120
1121 /* Fill the buffer with version information */
1122 Status = RtlStringCbPrintfA(Buffer,
1123 sizeof(Buffer),
1124 "%Z %u%c",
1125 &CsdString,
1126 (CmNtCSDVersion & 0xFF00) >> 8,
1127 (CmNtCSDVersion & 0xFF) ?
1128 'A' + (CmNtCSDVersion & 0xFF) - 1 :
1129 ANSI_NULL);
1130 }
1131 else
1132 {
1133 /* Build default string */
1134 Status = RtlStringCbPrintfA(Buffer,
1135 sizeof(Buffer),
1136 "CSD %04x",
1137 CmNtCSDVersion);
1138 }
1139
1140 /* Check for success */
1141 if (!NT_SUCCESS(Status))
1142 {
1143 /* Fail */
1144 KeBugCheckEx(PHASE0_INITIALIZATION_FAILED, Status, 0, 0, 0);
1145 }
1146 }
1147 else
1148 {
1149 /* Then this is a beta */
1150 Status = RtlStringCbCopyExA(Buffer,
1151 sizeof(Buffer),
1152 VER_PRODUCTBETA_STR,
1153 NULL,
1154 &Remaining,
1155 0);
1156 if (!NT_SUCCESS(Status))
1157 {
1158 /* Fail */
1159 KeBugCheckEx(PHASE0_INITIALIZATION_FAILED, Status, 0, 0, 0);
1160 }
1161
1162 /* Update length */
1163 CmCSDVersionString.MaximumLength = sizeof(Buffer) - (USHORT)Remaining;
1164 }
1165
1166 /* Check if we have an RC number */
1167 if (CmNtCSDVersion & 0xFFFF0000)
1168 {
1169 /* Check if we have no version data yet */
1170 if (!(*Buffer))
1171 {
1172 /* Set defaults */
1173 Remaining = sizeof(Buffer);
1174 RcEnd = Buffer;
1175 }
1176 else
1177 {
1178 /* Add comma and space */
1179 Status = RtlStringCbCatExA(Buffer,
1180 sizeof(Buffer),
1181 ", ",
1182 &RcEnd,
1183 &Remaining,
1184 0);
1185 if (!NT_SUCCESS(Status))
1186 {
1187 /* Fail */
1188 KeBugCheckEx(PHASE0_INITIALIZATION_FAILED, Status, 0, 0, 0);
1189 }
1190 }
1191
1192 /* Add the version format string */
1193 Status = RtlStringCbPrintfA(RcEnd,
1194 Remaining,
1195 "v. %u",
1196 (CmNtCSDVersion & 0xFFFF0000) >> 16);
1197 if (!NT_SUCCESS(Status))
1198 {
1199 /* Fail */
1200 KeBugCheckEx(PHASE0_INITIALIZATION_FAILED, Status, 0, 0, 0);
1201 }
1202 }
1203
1204 /* Now setup the final string */
1205 RtlInitAnsiString(&CsdString, Buffer);
1206 Status = RtlAnsiStringToUnicodeString(&CmCSDVersionString,
1207 &CsdString,
1208 TRUE);
1209 if (!NT_SUCCESS(Status))
1210 {
1211 /* Fail */
1212 KeBugCheckEx(PHASE0_INITIALIZATION_FAILED, Status, 0, 0, 0);
1213 }
1214
1215 /* Add our version */
1216 Status = RtlStringCbPrintfA(VersionBuffer,
1217 sizeof(VersionBuffer),
1218 "%u.%u",
1219 VER_PRODUCTMAJORVERSION,
1220 VER_PRODUCTMINORVERSION);
1221 if (!NT_SUCCESS(Status))
1222 {
1223 /* Fail */
1224 KeBugCheckEx(PHASE0_INITIALIZATION_FAILED, Status, 0, 0, 0);
1225 }
1226
1227 /* Build the final version string */
1228 RtlCreateUnicodeStringFromAsciiz(&CmVersionString, VersionBuffer);
1229
1230 /* Check if the user wants a kernel stack trace database */
1231 if (NtGlobalFlag & FLG_KERNEL_STACK_TRACE_DB)
1232 {
1233 /* FIXME: TODO */
1234 DPRINT1("Kernel-mode stack trace support not yet present."
1235 "FLG_KERNEL_STACK_TRACE_DB flag ignored.\n");
1236 }
1237
1238 /* Check if he wanted exception logging */
1239 if (NtGlobalFlag & FLG_ENABLE_EXCEPTION_LOGGING)
1240 {
1241 /* FIXME: TODO */
1242 DPRINT1("Kernel-mode exception logging support not yet present."
1243 "FLG_ENABLE_EXCEPTION_LOGGING flag ignored.\n");
1244 }
1245
1246 /* Initialize the Handle Table */
1247 ExpInitializeHandleTables();
1248
1249 #if DBG
1250 /* On checked builds, allocate the system call count table */
1251 KeServiceDescriptorTable[0].Count =
1252 ExAllocatePoolWithTag(NonPagedPool,
1253 KiServiceLimit * sizeof(ULONG),
1254 'llaC');
1255
1256 /* Use it for the shadow table too */
1257 KeServiceDescriptorTableShadow[0].Count = KeServiceDescriptorTable[0].Count;
1258
1259 /* Make sure allocation succeeded */
1260 if (KeServiceDescriptorTable[0].Count)
1261 {
1262 /* Zero the call counts to 0 */
1263 RtlZeroMemory(KeServiceDescriptorTable[0].Count,
1264 KiServiceLimit * sizeof(ULONG));
1265 }
1266 #endif
1267
1268 /* Create the Basic Object Manager Types to allow new Object Types */
1269 if (!ObInitSystem()) KeBugCheck(OBJECT_INITIALIZATION_FAILED);
1270
1271 /* Load basic Security for other Managers */
1272 if (!SeInitSystem()) KeBugCheck(SECURITY_INITIALIZATION_FAILED);
1273
1274 /* Initialize the Process Manager */
1275 if (!PsInitSystem(LoaderBlock)) KeBugCheck(PROCESS_INITIALIZATION_FAILED);
1276
1277 /* Initialize the PnP Manager */
1278 if (!PpInitSystem()) KeBugCheck(PP0_INITIALIZATION_FAILED);
1279
1280 /* Initialize the User-Mode Debugging Subsystem */
1281 DbgkInitialize();
1282
1283 /* Calculate the tick count multiplier */
1284 ExpTickCountMultiplier = ExComputeTickCountMultiplier(KeMaximumIncrement);
1285 SharedUserData->TickCountMultiplier = ExpTickCountMultiplier;
1286
1287 /* Set the OS Version */
1288 SharedUserData->NtMajorVersion = NtMajorVersion;
1289 SharedUserData->NtMinorVersion = NtMinorVersion;
1290
1291 /* Set the machine type */
1292 SharedUserData->ImageNumberLow = IMAGE_FILE_MACHINE_NATIVE;
1293 SharedUserData->ImageNumberHigh = IMAGE_FILE_MACHINE_NATIVE;
1294 }
1295
1296 VOID
1297 NTAPI
1298 INIT_FUNCTION
1299 Phase1InitializationDiscard(IN PVOID Context)
1300 {
1301 PLOADER_PARAMETER_BLOCK LoaderBlock = Context;
1302 NTSTATUS Status, MsgStatus;
1303 TIME_FIELDS TimeFields;
1304 LARGE_INTEGER SystemBootTime, UniversalBootTime, OldTime, Timeout;
1305 BOOLEAN SosEnabled, NoGuiBoot, ResetBias = FALSE, AlternateShell = FALSE;
1306 PLDR_DATA_TABLE_ENTRY NtosEntry;
1307 PMESSAGE_RESOURCE_ENTRY MsgEntry;
1308 PCHAR CommandLine, Y2KHackRequired, SafeBoot, Environment;
1309 PCHAR StringBuffer, EndBuffer, BeginBuffer, MpString = "";
1310 PINIT_BUFFER InitBuffer;
1311 ANSI_STRING TempString;
1312 ULONG LastTzBias, Length, YearHack = 0, Disposition, MessageCode = 0;
1313 SIZE_T Size;
1314 PRTL_USER_PROCESS_INFORMATION ProcessInfo;
1315 KEY_VALUE_PARTIAL_INFORMATION KeyPartialInfo;
1316 UNICODE_STRING KeyName, DebugString;
1317 OBJECT_ATTRIBUTES ObjectAttributes;
1318 HANDLE KeyHandle, OptionHandle;
1319 PRTL_USER_PROCESS_PARAMETERS ProcessParameters = NULL;
1320
1321 /* Allocate the initialization buffer */
1322 InitBuffer = ExAllocatePoolWithTag(NonPagedPool,
1323 sizeof(INIT_BUFFER),
1324 'tinI');
1325 if (!InitBuffer)
1326 {
1327 /* Bugcheck */
1328 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, STATUS_NO_MEMORY, 8, 0, 0);
1329 }
1330
1331 /* Set to phase 1 */
1332 ExpInitializationPhase = 1;
1333
1334 /* Set us at maximum priority */
1335 KeSetPriorityThread(KeGetCurrentThread(), HIGH_PRIORITY);
1336
1337 /* Do Phase 1 HAL Initialization */
1338 if (!HalInitSystem(1, LoaderBlock)) KeBugCheck(HAL1_INITIALIZATION_FAILED);
1339
1340 /* Get the command line and upcase it */
1341 CommandLine = _strupr(LoaderBlock->LoadOptions);
1342
1343 /* Check if GUI Boot is enabled */
1344 NoGuiBoot = (strstr(CommandLine, "NOGUIBOOT")) ? TRUE: FALSE;
1345
1346 /* Get the SOS setting */
1347 SosEnabled = strstr(CommandLine, "SOS") ? TRUE: FALSE;
1348
1349 /* Setup the boot driver */
1350 InbvEnableBootDriver(!NoGuiBoot);
1351 InbvDriverInitialize(LoaderBlock, 18);
1352
1353 /* Check if GUI boot is enabled */
1354 if (!NoGuiBoot)
1355 {
1356 /* It is, display the boot logo and enable printing strings */
1357 InbvEnableDisplayString(SosEnabled);
1358 DisplayBootBitmap(SosEnabled);
1359 }
1360 else
1361 {
1362 /* Release display ownership if not using GUI boot */
1363 InbvNotifyDisplayOwnershipLost(NULL);
1364
1365 /* Don't allow boot-time strings */
1366 InbvEnableDisplayString(FALSE);
1367 }
1368
1369 /* Check if this is LiveCD (WinPE) mode */
1370 if (strstr(CommandLine, "MININT"))
1371 {
1372 /* Setup WinPE Settings */
1373 InitIsWinPEMode = TRUE;
1374 InitWinPEModeType |= (strstr(CommandLine, "INRAM")) ? 0x80000000 : 1;
1375 }
1376
1377 /* Get the kernel's load entry */
1378 NtosEntry = CONTAINING_RECORD(LoaderBlock->LoadOrderListHead.Flink,
1379 LDR_DATA_TABLE_ENTRY,
1380 InLoadOrderLinks);
1381
1382 /* Find the banner message */
1383 MsgStatus = RtlFindMessage(NtosEntry->DllBase,
1384 11,
1385 0,
1386 WINDOWS_NT_BANNER,
1387 &MsgEntry);
1388
1389 /* Setup defaults and check if we have a version string */
1390 StringBuffer = InitBuffer->VersionBuffer;
1391 BeginBuffer = StringBuffer;
1392 EndBuffer = StringBuffer;
1393 Size = 256;
1394 if (CmCSDVersionString.Length)
1395 {
1396 /* Print the version string */
1397 Status = RtlStringCbPrintfExA(StringBuffer,
1398 255,
1399 &EndBuffer,
1400 &Size,
1401 0,
1402 ": %wZ",
1403 &CmCSDVersionString);
1404 if (!NT_SUCCESS(Status))
1405 {
1406 /* Bugcheck */
1407 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 7, 0, 0);
1408 }
1409 }
1410 else
1411 {
1412 /* No version */
1413 Size = 255;
1414 }
1415
1416 /* Null-terminate the string */
1417 *EndBuffer++ = ANSI_NULL;
1418
1419 /* Build the version number */
1420 StringBuffer = InitBuffer->VersionNumber;
1421 Status = RtlStringCbPrintfA(StringBuffer,
1422 24,
1423 "%u.%u",
1424 VER_PRODUCTMAJORVERSION,
1425 VER_PRODUCTMINORVERSION);
1426 if (!NT_SUCCESS(Status))
1427 {
1428 /* Bugcheck */
1429 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 7, 0, 0);
1430 }
1431
1432 /* Check if we had found a banner message */
1433 if (NT_SUCCESS(MsgStatus))
1434 {
1435 /* Create the banner message */
1436 Status = RtlStringCbPrintfA(EndBuffer,
1437 Size,
1438 (PCHAR)MsgEntry->Text,
1439 StringBuffer,
1440 NtBuildNumber & 0xFFFF,
1441 BeginBuffer);
1442 if (!NT_SUCCESS(Status))
1443 {
1444 /* Bugcheck */
1445 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 7, 0, 0);
1446 }
1447 }
1448 else
1449 {
1450 /* Use hard-coded banner message */
1451 Status = RtlStringCbCopyA(EndBuffer, Size, "REACTOS (R)\n");
1452 if (!NT_SUCCESS(Status))
1453 {
1454 /* Bugcheck */
1455 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 7, 0, 0);
1456 }
1457 }
1458
1459 /* Display the version string on-screen */
1460 InbvDisplayString(EndBuffer);
1461
1462 /* Initialize Power Subsystem in Phase 0 */
1463 if (!PoInitSystem(0)) KeBugCheck(INTERNAL_POWER_ERROR);
1464
1465 /* Check for Y2K hack */
1466 Y2KHackRequired = strstr(CommandLine, "YEAR");
1467 if (Y2KHackRequired) Y2KHackRequired = strstr(Y2KHackRequired, "=");
1468 if (Y2KHackRequired) YearHack = atol(Y2KHackRequired + 1);
1469
1470 /* Query the clock */
1471 if ((ExCmosClockIsSane) && (HalQueryRealTimeClock(&TimeFields)))
1472 {
1473 /* Check if we're using the Y2K hack */
1474 if (Y2KHackRequired) TimeFields.Year = (CSHORT)YearHack;
1475
1476 /* Convert to time fields */
1477 RtlTimeFieldsToTime(&TimeFields, &SystemBootTime);
1478 UniversalBootTime = SystemBootTime;
1479
1480 /* Check if real time is GMT */
1481 if (!ExpRealTimeIsUniversal)
1482 {
1483 /* Check if we don't have a valid bias */
1484 if (ExpLastTimeZoneBias == MAXULONG)
1485 {
1486 /* Reset */
1487 ResetBias = TRUE;
1488 ExpLastTimeZoneBias = ExpAltTimeZoneBias;
1489 }
1490
1491 /* Calculate the bias in seconds */
1492 ExpTimeZoneBias.QuadPart = Int32x32To64(ExpLastTimeZoneBias * 60,
1493 10000000);
1494
1495 /* Set the boot time-zone bias */
1496 SharedUserData->TimeZoneBias.High2Time = ExpTimeZoneBias.HighPart;
1497 SharedUserData->TimeZoneBias.LowPart = ExpTimeZoneBias.LowPart;
1498 SharedUserData->TimeZoneBias.High1Time = ExpTimeZoneBias.HighPart;
1499
1500 /* Convert the boot time to local time, and set it */
1501 UniversalBootTime.QuadPart = SystemBootTime.QuadPart +
1502 ExpTimeZoneBias.QuadPart;
1503 }
1504
1505 /* Update the system time */
1506 KeSetSystemTime(&UniversalBootTime, &OldTime, FALSE, NULL);
1507
1508 /* Do system callback */
1509 PoNotifySystemTimeSet();
1510
1511 /* Remember this as the boot time */
1512 KeBootTime = UniversalBootTime;
1513 KeBootTimeBias = 0;
1514 }
1515
1516 /* Initialize all processors */
1517 if (!HalAllProcessorsStarted()) KeBugCheck(HAL1_INITIALIZATION_FAILED);
1518
1519 #ifdef CONFIG_SMP
1520 /* HACK: We should use RtlFindMessage and not only fallback to this */
1521 MpString = "MultiProcessor Kernel\r\n";
1522 #endif
1523
1524 /* Setup the "MP" String */
1525 RtlInitAnsiString(&TempString, MpString);
1526
1527 /* Make sure to remove the \r\n if we actually have a string */
1528 while ((TempString.Length > 0) &&
1529 ((TempString.Buffer[TempString.Length - 1] == '\r') ||
1530 (TempString.Buffer[TempString.Length - 1] == '\n')))
1531 {
1532 /* Skip the trailing character */
1533 TempString.Length--;
1534 }
1535
1536 /* Get the information string from our resource file */
1537 MsgStatus = RtlFindMessage(NtosEntry->DllBase,
1538 11,
1539 0,
1540 KeNumberProcessors > 1 ?
1541 WINDOWS_NT_INFO_STRING_PLURAL :
1542 WINDOWS_NT_INFO_STRING,
1543 &MsgEntry);
1544
1545 /* Get total RAM size */
1546 Size = MmNumberOfPhysicalPages * PAGE_SIZE / 1024 / 1024;
1547
1548 /* Create the string */
1549 StringBuffer = InitBuffer->VersionBuffer;
1550 Status = RtlStringCbPrintfA(StringBuffer,
1551 256,
1552 NT_SUCCESS(MsgStatus) ?
1553 (PCHAR)MsgEntry->Text :
1554 "%u System Processor [%u MB Memory] %Z\n",
1555 KeNumberProcessors,
1556 Size,
1557 &TempString);
1558 if (!NT_SUCCESS(Status))
1559 {
1560 /* Bugcheck */
1561 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 4, 0, 0);
1562 }
1563
1564 /* Display RAM and CPU count */
1565 InbvDisplayString(StringBuffer);
1566
1567 /* Update the progress bar */
1568 InbvUpdateProgressBar(5);
1569
1570 /* Call OB initialization again */
1571 if (!ObInitSystem()) KeBugCheck(OBJECT1_INITIALIZATION_FAILED);
1572
1573 /* Initialize Basic System Objects and Worker Threads */
1574 if (!ExInitSystem()) KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, 0, 0, 1, 0);
1575
1576 /* Initialize the later stages of the kernel */
1577 if (!KeInitSystem()) KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, 0, 0, 2, 0);
1578
1579 /* Call KD Providers at Phase 1 */
1580 if (!KdInitSystem(ExpInitializationPhase, KeLoaderBlock))
1581 {
1582 /* Failed, bugcheck */
1583 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, 0, 0, 3, 0);
1584 }
1585
1586 /* Initialize the SRM in Phase 1 */
1587 if (!SeInitSystem()) KeBugCheck(SECURITY1_INITIALIZATION_FAILED);
1588
1589 /* Update the progress bar */
1590 InbvUpdateProgressBar(10);
1591
1592 /* Create SystemRoot Link */
1593 Status = ExpCreateSystemRootLink(LoaderBlock);
1594 if (!NT_SUCCESS(Status))
1595 {
1596 /* Failed to create the system root link */
1597 KeBugCheckEx(SYMBOLIC_INITIALIZATION_FAILED, Status, 0, 0, 0);
1598 }
1599
1600 /* Set up Region Maps, Sections and the Paging File */
1601 if (!MmInitSystem(1, LoaderBlock)) KeBugCheck(MEMORY1_INITIALIZATION_FAILED);
1602
1603 /* Create NLS section */
1604 ExpInitNls(LoaderBlock);
1605
1606 /* Initialize Cache Views */
1607 if (!CcInitializeCacheManager()) KeBugCheck(CACHE_INITIALIZATION_FAILED);
1608
1609 /* Initialize the Registry */
1610 if (!CmInitSystem1()) KeBugCheck(CONFIG_INITIALIZATION_FAILED);
1611
1612 /* Initialize Prefetcher */
1613 CcPfInitializePrefetcher();
1614
1615 /* Update progress bar */
1616 InbvUpdateProgressBar(15);
1617
1618 /* Update timezone information */
1619 LastTzBias = ExpLastTimeZoneBias;
1620 ExRefreshTimeZoneInformation(&SystemBootTime);
1621
1622 /* Check if we're resetting timezone data */
1623 if (ResetBias)
1624 {
1625 /* Convert the local time to system time */
1626 ExLocalTimeToSystemTime(&SystemBootTime, &UniversalBootTime);
1627 KeBootTime = UniversalBootTime;
1628 KeBootTimeBias = 0;
1629
1630 /* Set the new time */
1631 KeSetSystemTime(&UniversalBootTime, &OldTime, FALSE, NULL);
1632 }
1633 else
1634 {
1635 /* Check if the timezone switched and update the time */
1636 if (LastTzBias != ExpLastTimeZoneBias) ZwSetSystemTime(NULL, NULL);
1637 }
1638
1639 /* Initialize the File System Runtime Library */
1640 if (!FsRtlInitSystem()) KeBugCheck(FILE_INITIALIZATION_FAILED);
1641
1642 /* Initialize range lists */
1643 RtlInitializeRangeListPackage();
1644
1645 /* Report all resources used by HAL */
1646 HalReportResourceUsage();
1647
1648 /* Call the debugger DLL */
1649 KdDebuggerInitialize1(LoaderBlock);
1650
1651 /* Setup PnP Manager in phase 1 */
1652 if (!PpInitSystem()) KeBugCheck(PP1_INITIALIZATION_FAILED);
1653
1654 /* Update progress bar */
1655 InbvUpdateProgressBar(20);
1656
1657 /* Initialize LPC */
1658 if (!LpcInitSystem()) KeBugCheck(LPC_INITIALIZATION_FAILED);
1659
1660 /* Make sure we have a command line */
1661 if (CommandLine)
1662 {
1663 /* Check if this is a safe mode boot */
1664 SafeBoot = strstr(CommandLine, "SAFEBOOT:");
1665 if (SafeBoot)
1666 {
1667 /* Check what kind of boot this is */
1668 SafeBoot += 9;
1669 if (!strncmp(SafeBoot, "MINIMAL", 7))
1670 {
1671 /* Minimal mode */
1672 InitSafeBootMode = 1;
1673 SafeBoot += 7;
1674 MessageCode = BOOTING_IN_SAFEMODE_MINIMAL;
1675 }
1676 else if (!strncmp(SafeBoot, "NETWORK", 7))
1677 {
1678 /* With Networking */
1679 InitSafeBootMode = 2;
1680 SafeBoot += 7;
1681 MessageCode = BOOTING_IN_SAFEMODE_NETWORK;
1682 }
1683 else if (!strncmp(SafeBoot, "DSREPAIR", 8))
1684 {
1685 /* Domain Server Repair */
1686 InitSafeBootMode = 3;
1687 SafeBoot += 8;
1688 MessageCode = BOOTING_IN_SAFEMODE_DSREPAIR;
1689
1690 }
1691 else
1692 {
1693 /* Invalid */
1694 InitSafeBootMode = 0;
1695 }
1696
1697 /* Check if there's any settings left */
1698 if (*SafeBoot)
1699 {
1700 /* Check if an alternate shell was requested */
1701 if (!strncmp(SafeBoot, "(ALTERNATESHELL)", 16))
1702 {
1703 /* Remember this for later */
1704 AlternateShell = TRUE;
1705 }
1706 }
1707
1708 /* Find the message to print out */
1709 Status = RtlFindMessage(NtosEntry->DllBase,
1710 11,
1711 0,
1712 MessageCode,
1713 &MsgEntry);
1714 if (NT_SUCCESS(Status))
1715 {
1716 /* Display it */
1717 InbvDisplayString((PCHAR)MsgEntry->Text);
1718 }
1719 }
1720 }
1721
1722 /* Make sure we have a command line */
1723 if (CommandLine)
1724 {
1725 /* Check if bootlogging is enabled */
1726 if (strstr(CommandLine, "BOOTLOG"))
1727 {
1728 /* Find the message to print out */
1729 Status = RtlFindMessage(NtosEntry->DllBase,
1730 11,
1731 0,
1732 BOOTLOG_ENABLED,
1733 &MsgEntry);
1734 if (NT_SUCCESS(Status))
1735 {
1736 /* Display it */
1737 InbvDisplayString((PCHAR)MsgEntry->Text);
1738 }
1739
1740 /* Setup boot logging */
1741 //IopInitializeBootLogging(LoaderBlock, InitBuffer->BootlogHeader);
1742 }
1743 }
1744
1745 /* Setup the Executive in Phase 2 */
1746 //ExInitSystemPhase2();
1747
1748 /* Update progress bar */
1749 InbvUpdateProgressBar(25);
1750
1751 #ifdef _WINKD_
1752 /* No KD Time Slip is pending */
1753 KdpTimeSlipPending = 0;
1754 #endif
1755
1756 /* Initialize in-place execution support */
1757 XIPInit(LoaderBlock);
1758
1759 /* Set maximum update to 75% */
1760 InbvSetProgressBarSubset(25, 75);
1761
1762 /* Initialize the I/O Subsystem */
1763 if (!IoInitSystem(LoaderBlock)) KeBugCheck(IO1_INITIALIZATION_FAILED);
1764
1765 /* Set maximum update to 100% */
1766 InbvSetProgressBarSubset(0, 100);
1767
1768 /* Are we in safe mode? */
1769 if (InitSafeBootMode)
1770 {
1771 /* Open the safe boot key */
1772 RtlInitUnicodeString(&KeyName,
1773 L"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET"
1774 L"\\CONTROL\\SAFEBOOT");
1775 InitializeObjectAttributes(&ObjectAttributes,
1776 &KeyName,
1777 OBJ_CASE_INSENSITIVE,
1778 NULL,
1779 NULL);
1780 Status = ZwOpenKey(&KeyHandle, KEY_ALL_ACCESS, &ObjectAttributes);
1781 if (NT_SUCCESS(Status))
1782 {
1783 /* First check if we have an alternate shell */
1784 if (AlternateShell)
1785 {
1786 /* Make sure that the registry has one setup */
1787 RtlInitUnicodeString(&KeyName, L"AlternateShell");
1788 Status = NtQueryValueKey(KeyHandle,
1789 &KeyName,
1790 KeyValuePartialInformation,
1791 &KeyPartialInfo,
1792 sizeof(KeyPartialInfo),
1793 &Length);
1794 if (!NT_SUCCESS(Status)) AlternateShell = FALSE;
1795 }
1796
1797 /* Create the option key */
1798 RtlInitUnicodeString(&KeyName, L"Option");
1799 InitializeObjectAttributes(&ObjectAttributes,
1800 &KeyName,
1801 OBJ_CASE_INSENSITIVE,
1802 KeyHandle,
1803 NULL);
1804 Status = ZwCreateKey(&OptionHandle,
1805 KEY_ALL_ACCESS,
1806 &ObjectAttributes,
1807 0,
1808 NULL,
1809 REG_OPTION_VOLATILE,
1810 &Disposition);
1811 NtClose(KeyHandle);
1812
1813 /* Check if the key create worked */
1814 if (NT_SUCCESS(Status))
1815 {
1816 /* Write the safe boot type */
1817 RtlInitUnicodeString(&KeyName, L"OptionValue");
1818 NtSetValueKey(OptionHandle,
1819 &KeyName,
1820 0,
1821 REG_DWORD,
1822 &InitSafeBootMode,
1823 sizeof(InitSafeBootMode));
1824
1825 /* Check if we have to use an alternate shell */
1826 if (AlternateShell)
1827 {
1828 /* Remember this for later */
1829 Disposition = TRUE;
1830 RtlInitUnicodeString(&KeyName, L"UseAlternateShell");
1831 NtSetValueKey(OptionHandle,
1832 &KeyName,
1833 0,
1834 REG_DWORD,
1835 &Disposition,
1836 sizeof(Disposition));
1837 }
1838
1839 /* Close the options key handle */
1840 NtClose(OptionHandle);
1841 }
1842 }
1843 }
1844
1845 /* Are we in Win PE mode? */
1846 if (InitIsWinPEMode)
1847 {
1848 /* Open the safe control key */
1849 RtlInitUnicodeString(&KeyName,
1850 L"\\REGISTRY\\MACHINE\\SYSTEM\\CURRENTCONTROLSET"
1851 L"\\CONTROL");
1852 InitializeObjectAttributes(&ObjectAttributes,
1853 &KeyName,
1854 OBJ_CASE_INSENSITIVE,
1855 NULL,
1856 NULL);
1857 Status = ZwOpenKey(&KeyHandle, KEY_ALL_ACCESS, &ObjectAttributes);
1858 if (!NT_SUCCESS(Status))
1859 {
1860 /* Bugcheck */
1861 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 6, 0, 0);
1862 }
1863
1864 /* Create the MiniNT key */
1865 RtlInitUnicodeString(&KeyName, L"MiniNT");
1866 InitializeObjectAttributes(&ObjectAttributes,
1867 &KeyName,
1868 OBJ_CASE_INSENSITIVE,
1869 KeyHandle,
1870 NULL);
1871 Status = ZwCreateKey(&OptionHandle,
1872 KEY_ALL_ACCESS,
1873 &ObjectAttributes,
1874 0,
1875 NULL,
1876 REG_OPTION_VOLATILE,
1877 &Disposition);
1878 if (!NT_SUCCESS(Status))
1879 {
1880 /* Bugcheck */
1881 KeBugCheckEx(PHASE1_INITIALIZATION_FAILED, Status, 6, 0, 0);
1882 }
1883
1884 /* Close the handles */
1885 NtClose(KeyHandle);
1886 NtClose(OptionHandle);
1887 }
1888
1889 /* FIXME: This doesn't do anything for now */
1890 MmArmInitSystem(2, LoaderBlock);
1891
1892 /* Update progress bar */
1893 InbvUpdateProgressBar(80);
1894
1895 /* Initialize VDM support */
1896 #if defined(_M_IX86)
1897 KeI386VdmInitialize();
1898 #endif
1899
1900 /* Initialize Power Subsystem in Phase 1*/
1901 if (!PoInitSystem(1)) KeBugCheck(INTERNAL_POWER_ERROR);
1902
1903 /* Initialize the Process Manager at Phase 1 */
1904 if (!PsInitSystem(LoaderBlock)) KeBugCheck(PROCESS1_INITIALIZATION_FAILED);
1905
1906 /* Update progress bar */
1907 InbvUpdateProgressBar(85);
1908
1909 /* Make sure nobody touches the loader block again */
1910 if (LoaderBlock == KeLoaderBlock) KeLoaderBlock = NULL;
1911 LoaderBlock = Context = NULL;
1912
1913 /* Update progress bar */
1914 InbvUpdateProgressBar(90);
1915
1916 /* Launch initial process */
1917 DPRINT1("Free non-cache pages: %lx\n", MmAvailablePages + MiMemoryConsumers[MC_CACHE].PagesUsed);
1918 ProcessInfo = &InitBuffer->ProcessInfo;
1919 ExpLoadInitialProcess(InitBuffer, &ProcessParameters, &Environment);
1920
1921 /* Update progress bar */
1922 InbvUpdateProgressBar(100);
1923
1924 /* Allow strings to be displayed */
1925 InbvEnableDisplayString(TRUE);
1926
1927 /* Wait 5 seconds for it to initialize */
1928 Timeout.QuadPart = Int32x32To64(5, -10000000);
1929 Status = ZwWaitForSingleObject(ProcessInfo->ProcessHandle, FALSE, &Timeout);
1930 if (InbvBootDriverInstalled) FinalizeBootLogo();
1931 if (Status == STATUS_SUCCESS)
1932 {
1933 /* Failed, display error */
1934 RtlInitUnicodeString(&DebugString, L"INIT: Session Manager terminated.");
1935 ZwDisplayString(&DebugString);
1936
1937 /* Bugcheck the system if SMSS couldn't initialize */
1938 KeBugCheck(SESSION5_INITIALIZATION_FAILED);
1939 }
1940
1941 /* Close process handles */
1942 ZwClose(ProcessInfo->ThreadHandle);
1943 ZwClose(ProcessInfo->ProcessHandle);
1944
1945 /* Free the initial process environment */
1946 Size = 0;
1947 ZwFreeVirtualMemory(NtCurrentProcess(),
1948 (PVOID*)&Environment,
1949 &Size,
1950 MEM_RELEASE);
1951
1952 /* Free the initial process parameters */
1953 Size = 0;
1954 ZwFreeVirtualMemory(NtCurrentProcess(),
1955 (PVOID*)&ProcessParameters,
1956 &Size,
1957 MEM_RELEASE);
1958
1959 /* Increase init phase */
1960 ExpInitializationPhase++;
1961
1962 /* Free the boot buffer */
1963 ExFreePool(InitBuffer);
1964 DPRINT1("Free non-cache pages: %lx\n", MmAvailablePages + MiMemoryConsumers[MC_CACHE].PagesUsed);
1965 }
1966
1967 VOID
1968 NTAPI
1969 Phase1Initialization(IN PVOID Context)
1970 {
1971 /* Do the .INIT part of Phase 1 which we can free later */
1972 Phase1InitializationDiscard(Context);
1973
1974 /* Jump into zero page thread */
1975 MmZeroPageThread();
1976 }