Create the AHCI branch for Aman's work
[reactos.git] / boot / freeldr / freeldr / ntldr / winldr.c
1 /*
2 * FreeLoader
3 *
4 * Copyright (C) 1998-2003 Brian Palmer <brianp@sginet.com>
5 * Copyright (C) 2006 Aleksey Bragin <aleksey@reactos.org>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include <freeldr.h>
23 #include "registry.h"
24
25 #include <ndk/ldrtypes.h>
26
27 #include <debug.h>
28 DBG_DEFAULT_CHANNEL(WINDOWS);
29
30 //FIXME: Find a better way to retrieve ARC disk information
31 extern ULONG reactos_disk_count;
32 extern ARC_DISK_SIGNATURE reactos_arc_disk_info[];
33
34 extern ULONG LoaderPagesSpanned;
35 extern BOOLEAN AcpiPresent;
36
37 extern HEADLESS_LOADER_BLOCK LoaderRedirectionInformation;
38 extern BOOLEAN WinLdrTerminalConnected;
39 extern void WinLdrSetupEms(IN PCHAR BootOptions);
40
41 PLOADER_SYSTEM_BLOCK WinLdrSystemBlock;
42
43 // debug stuff
44 VOID DumpMemoryAllocMap(VOID);
45
46 // Init "phase 0"
47 VOID
48 AllocateAndInitLPB(PLOADER_PARAMETER_BLOCK *OutLoaderBlock)
49 {
50 PLOADER_PARAMETER_BLOCK LoaderBlock;
51
52 /* Allocate and zero-init the LPB */
53 WinLdrSystemBlock = MmAllocateMemoryWithType(sizeof(LOADER_SYSTEM_BLOCK),
54 LoaderSystemBlock);
55 if (WinLdrSystemBlock == NULL)
56 {
57 UiMessageBox("Failed to allocate memory for system block!");
58 return;
59 }
60
61 RtlZeroMemory(WinLdrSystemBlock, sizeof(LOADER_SYSTEM_BLOCK));
62
63 LoaderBlock = &WinLdrSystemBlock->LoaderBlock;
64 LoaderBlock->NlsData = &WinLdrSystemBlock->NlsDataBlock;
65
66 /* Init three critical lists, used right away */
67 InitializeListHead(&LoaderBlock->LoadOrderListHead);
68 InitializeListHead(&LoaderBlock->MemoryDescriptorListHead);
69 InitializeListHead(&LoaderBlock->BootDriverListHead);
70
71 *OutLoaderBlock = LoaderBlock;
72 }
73
74 // Init "phase 1"
75 VOID
76 WinLdrInitializePhase1(PLOADER_PARAMETER_BLOCK LoaderBlock,
77 LPCSTR Options,
78 LPCSTR SystemRoot,
79 LPCSTR BootPath,
80 USHORT VersionToBoot)
81 {
82 /* Examples of correct options and paths */
83 //CHAR Options[] = "/DEBUGPORT=COM1 /BAUDRATE=115200";
84 //CHAR Options[] = "/NODEBUG";
85 //CHAR SystemRoot[] = "\\WINNT\\";
86 //CHAR ArcBoot[] = "multi(0)disk(0)rdisk(0)partition(1)";
87
88 LPSTR LoadOptions, NewLoadOptions;
89 CHAR HalPath[] = "\\";
90 CHAR ArcBoot[256];
91 CHAR MiscFiles[256];
92 ULONG i;
93 ULONG_PTR PathSeparator;
94 PLOADER_PARAMETER_EXTENSION Extension;
95
96 /* Construct SystemRoot and ArcBoot from SystemPath */
97 PathSeparator = strstr(BootPath, "\\") - BootPath;
98 strncpy(ArcBoot, BootPath, PathSeparator);
99 ArcBoot[PathSeparator] = 0;
100
101 TRACE("ArcBoot: %s\n", ArcBoot);
102 TRACE("SystemRoot: %s\n", SystemRoot);
103 TRACE("Options: %s\n", Options);
104
105 /* Fill Arc BootDevice */
106 LoaderBlock->ArcBootDeviceName = WinLdrSystemBlock->ArcBootDeviceName;
107 strncpy(LoaderBlock->ArcBootDeviceName, ArcBoot, MAX_PATH);
108 LoaderBlock->ArcBootDeviceName = PaToVa(LoaderBlock->ArcBootDeviceName);
109
110 /* Fill Arc HalDevice, it matches ArcBoot path */
111 LoaderBlock->ArcHalDeviceName = WinLdrSystemBlock->ArcBootDeviceName;
112 LoaderBlock->ArcHalDeviceName = PaToVa(LoaderBlock->ArcHalDeviceName);
113
114 /* Fill SystemRoot */
115 LoaderBlock->NtBootPathName = WinLdrSystemBlock->NtBootPathName;
116 strncpy(LoaderBlock->NtBootPathName, SystemRoot, MAX_PATH);
117 LoaderBlock->NtBootPathName = PaToVa(LoaderBlock->NtBootPathName);
118
119 /* Fill NtHalPathName */
120 LoaderBlock->NtHalPathName = WinLdrSystemBlock->NtHalPathName;
121 strncpy(LoaderBlock->NtHalPathName, HalPath, MAX_PATH);
122 LoaderBlock->NtHalPathName = PaToVa(LoaderBlock->NtHalPathName);
123
124 /* Fill LoadOptions and strip the '/' commutator symbol in front of each option */
125 NewLoadOptions = LoadOptions = LoaderBlock->LoadOptions = WinLdrSystemBlock->LoadOptions;
126 strncpy(LoaderBlock->LoadOptions, Options, MAX_OPTIONS_LENGTH);
127
128 do
129 {
130 while (*LoadOptions == '/')
131 ++LoadOptions;
132
133 *NewLoadOptions++ = *LoadOptions;
134 } while (*LoadOptions++);
135
136 LoaderBlock->LoadOptions = PaToVa(LoaderBlock->LoadOptions);
137
138 /* Arc devices */
139 LoaderBlock->ArcDiskInformation = &WinLdrSystemBlock->ArcDiskInformation;
140 InitializeListHead(&LoaderBlock->ArcDiskInformation->DiskSignatureListHead);
141
142 /* Convert ARC disk information from freeldr to a correct format */
143 for (i = 0; i < reactos_disk_count; i++)
144 {
145 PARC_DISK_SIGNATURE_EX ArcDiskSig;
146
147 /* Allocate the ARC structure */
148 ArcDiskSig = FrLdrHeapAlloc(sizeof(ARC_DISK_SIGNATURE_EX), 'giSD');
149
150 /* Copy the data over */
151 ArcDiskSig->DiskSignature.Signature = reactos_arc_disk_info[i].Signature;
152 ArcDiskSig->DiskSignature.CheckSum = reactos_arc_disk_info[i].CheckSum;
153
154 /* Copy the ARC Name */
155 strncpy(ArcDiskSig->ArcName, reactos_arc_disk_info[i].ArcName, MAX_PATH);
156 ArcDiskSig->DiskSignature.ArcName = PaToVa(ArcDiskSig->ArcName);
157
158 /* Mark partition table as valid */
159 ArcDiskSig->DiskSignature.ValidPartitionTable = TRUE;
160
161 /* Insert into the list */
162 InsertTailList(&LoaderBlock->ArcDiskInformation->DiskSignatureListHead,
163 &ArcDiskSig->DiskSignature.ListEntry);
164 }
165
166 /* Convert all list's to Virtual address */
167
168 /* Convert the ArcDisks list to virtual address */
169 List_PaToVa(&LoaderBlock->ArcDiskInformation->DiskSignatureListHead);
170 LoaderBlock->ArcDiskInformation = PaToVa(LoaderBlock->ArcDiskInformation);
171
172 /* Convert configuration entries to VA */
173 ConvertConfigToVA(LoaderBlock->ConfigurationRoot);
174 LoaderBlock->ConfigurationRoot = PaToVa(LoaderBlock->ConfigurationRoot);
175
176 /* Convert all DTE into virtual addresses */
177 List_PaToVa(&LoaderBlock->LoadOrderListHead);
178
179 /* this one will be converted right before switching to
180 virtual paging mode */
181 //List_PaToVa(&LoaderBlock->MemoryDescriptorListHead);
182
183 /* Convert list of boot drivers */
184 List_PaToVa(&LoaderBlock->BootDriverListHead);
185
186 /* Initialize Extension now */
187 Extension = &WinLdrSystemBlock->Extension;
188 Extension->Size = sizeof(LOADER_PARAMETER_EXTENSION);
189 Extension->MajorVersion = (VersionToBoot & 0xFF00) >> 8;
190 Extension->MinorVersion = VersionToBoot & 0xFF;
191 Extension->Profile.Status = 2;
192
193 /* Check if ACPI is present */
194 if (AcpiPresent)
195 {
196 /* See KiRosFrldrLpbToNtLpb for details */
197 Extension->AcpiTable = (PVOID)1;
198 }
199
200 #ifdef _M_IX86
201 /* Set headless block pointer */
202 if (WinLdrTerminalConnected)
203 {
204 Extension->HeadlessLoaderBlock = &WinLdrSystemBlock->HeadlessLoaderBlock;
205 RtlCopyMemory(Extension->HeadlessLoaderBlock,
206 &LoaderRedirectionInformation,
207 sizeof(HEADLESS_LOADER_BLOCK));
208 Extension->HeadlessLoaderBlock = PaToVa(Extension->HeadlessLoaderBlock);
209 }
210 #endif
211 /* Load drivers database */
212 strcpy(MiscFiles, BootPath);
213 strcat(MiscFiles, "AppPatch\\drvmain.sdb");
214 Extension->DrvDBImage = PaToVa(WinLdrLoadModule(MiscFiles,
215 &Extension->DrvDBSize,
216 LoaderRegistryData));
217
218 /* Convert extension and setup block pointers */
219 LoaderBlock->Extension = PaToVa(Extension);
220
221 if (LoaderBlock->SetupLdrBlock)
222 LoaderBlock->SetupLdrBlock = PaToVa(LoaderBlock->SetupLdrBlock);
223
224 TRACE("WinLdrInitializePhase1() completed\n");
225 }
226
227 static BOOLEAN
228 WinLdrLoadDeviceDriver(PLIST_ENTRY LoadOrderListHead,
229 LPCSTR BootPath,
230 PUNICODE_STRING FilePath,
231 ULONG Flags,
232 PLDR_DATA_TABLE_ENTRY *DriverDTE)
233 {
234 CHAR FullPath[1024];
235 CHAR DriverPath[1024];
236 CHAR DllName[1024];
237 PCHAR DriverNamePos;
238 BOOLEAN Success;
239 PVOID DriverBase = NULL;
240
241 // Separate the path to file name and directory path
242 _snprintf(DriverPath, sizeof(DriverPath), "%wZ", FilePath);
243 DriverNamePos = strrchr(DriverPath, '\\');
244 if (DriverNamePos != NULL)
245 {
246 // Copy the name
247 strcpy(DllName, DriverNamePos+1);
248
249 // Cut out the name from the path
250 *(DriverNamePos+1) = 0;
251 }
252 else
253 {
254 // There is no directory in the path
255 strcpy(DllName, DriverPath);
256 DriverPath[0] = 0;
257 }
258
259 TRACE("DriverPath: %s, DllName: %s, LPB\n", DriverPath, DllName);
260
261 // Check if driver is already loaded
262 Success = WinLdrCheckForLoadedDll(LoadOrderListHead, DllName, DriverDTE);
263 if (Success)
264 {
265 // We've got the pointer to its DTE, just return success
266 return TRUE;
267 }
268
269 // It's not loaded, we have to load it
270 _snprintf(FullPath, sizeof(FullPath), "%s%wZ", BootPath, FilePath);
271 Success = WinLdrLoadImage(FullPath, LoaderBootDriver, &DriverBase);
272 if (!Success)
273 return FALSE;
274
275 // Allocate a DTE for it
276 Success = WinLdrAllocateDataTableEntry(LoadOrderListHead, DllName, DllName, DriverBase, DriverDTE);
277 if (!Success)
278 {
279 ERR("WinLdrAllocateDataTableEntry() failed\n");
280 return FALSE;
281 }
282
283 // Modify any flags, if needed
284 (*DriverDTE)->Flags |= Flags;
285
286 // Look for any dependencies it may have, and load them too
287 sprintf(FullPath,"%s%s", BootPath, DriverPath);
288 Success = WinLdrScanImportDescriptorTable(LoadOrderListHead, FullPath, *DriverDTE);
289 if (!Success)
290 {
291 ERR("WinLdrScanImportDescriptorTable() failed for %s\n", FullPath);
292 return FALSE;
293 }
294
295 return TRUE;
296 }
297
298 BOOLEAN
299 WinLdrLoadBootDrivers(PLOADER_PARAMETER_BLOCK LoaderBlock,
300 LPCSTR BootPath)
301 {
302 PLIST_ENTRY NextBd;
303 PBOOT_DRIVER_LIST_ENTRY BootDriver;
304 BOOLEAN Success;
305 BOOLEAN ret = TRUE;
306
307 // Walk through the boot drivers list
308 NextBd = LoaderBlock->BootDriverListHead.Flink;
309
310 while (NextBd != &LoaderBlock->BootDriverListHead)
311 {
312 BootDriver = CONTAINING_RECORD(NextBd, BOOT_DRIVER_LIST_ENTRY, Link);
313
314 TRACE("BootDriver %wZ DTE %08X RegPath: %wZ\n", &BootDriver->FilePath,
315 BootDriver->LdrEntry, &BootDriver->RegistryPath);
316
317 // Paths are relative (FIXME: Are they always relative?)
318
319 // Load it
320 Success = WinLdrLoadDeviceDriver(&LoaderBlock->LoadOrderListHead,
321 BootPath,
322 &BootDriver->FilePath,
323 0,
324 &BootDriver->LdrEntry);
325
326 if (Success)
327 {
328 // Convert the RegistryPath and DTE addresses to VA since we are not going to use it anymore
329 BootDriver->RegistryPath.Buffer = PaToVa(BootDriver->RegistryPath.Buffer);
330 BootDriver->FilePath.Buffer = PaToVa(BootDriver->FilePath.Buffer);
331 BootDriver->LdrEntry = PaToVa(BootDriver->LdrEntry);
332 }
333 else
334 {
335 // Loading failed - cry loudly
336 ERR("Can't load boot driver '%wZ'!\n", &BootDriver->FilePath);
337 UiMessageBox("Can't load boot driver '%wZ'!", &BootDriver->FilePath);
338 ret = FALSE;
339
340 // Remove it from the list and try to continue
341 RemoveEntryList(NextBd);
342 }
343
344 NextBd = BootDriver->Link.Flink;
345 }
346
347 return ret;
348 }
349
350 PVOID
351 WinLdrLoadModule(PCSTR ModuleName,
352 ULONG *Size,
353 TYPE_OF_MEMORY MemoryType)
354 {
355 ULONG FileId;
356 PVOID PhysicalBase;
357 FILEINFORMATION FileInfo;
358 ULONG FileSize;
359 ARC_STATUS Status;
360 ULONG BytesRead;
361
362 //CHAR ProgressString[256];
363
364 /* Inform user we are loading files */
365 //sprintf(ProgressString, "Loading %s...", FileName);
366 //UiDrawProgressBarCenter(1, 100, ProgressString);
367
368 TRACE("Loading module %s\n", ModuleName);
369 *Size = 0;
370
371 /* Open the image file */
372 Status = ArcOpen((PCHAR)ModuleName, OpenReadOnly, &FileId);
373 if (Status != ESUCCESS)
374 {
375 /* In case of errors, we just return, without complaining to the user */
376 return NULL;
377 }
378
379 /* Get this file's size */
380 Status = ArcGetFileInformation(FileId, &FileInfo);
381 if (Status != ESUCCESS)
382 {
383 ArcClose(FileId);
384 return NULL;
385 }
386 FileSize = FileInfo.EndingAddress.LowPart;
387 *Size = FileSize;
388
389 /* Allocate memory */
390 PhysicalBase = MmAllocateMemoryWithType(FileSize, MemoryType);
391 if (PhysicalBase == NULL)
392 {
393 ArcClose(FileId);
394 return NULL;
395 }
396
397 /* Load whole file */
398 Status = ArcRead(FileId, PhysicalBase, FileSize, &BytesRead);
399 ArcClose(FileId);
400 if (Status != ESUCCESS)
401 {
402 return NULL;
403 }
404
405 TRACE("Loaded %s at 0x%x with size 0x%x\n", ModuleName, PhysicalBase, FileSize);
406
407 return PhysicalBase;
408 }
409
410 USHORT
411 WinLdrDetectVersion(VOID)
412 {
413 LONG rc;
414 HKEY hKey;
415
416 rc = RegOpenKey(
417 NULL,
418 L"\\Registry\\Machine\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server",
419 &hKey);
420 if (rc != ERROR_SUCCESS)
421 {
422 // Key doesn't exist; assume NT 4.0
423 return _WIN32_WINNT_NT4;
424 }
425
426 // We may here want to read the value of ProductVersion
427 return _WIN32_WINNT_WS03;
428 }
429
430 static
431 BOOLEAN
432 LoadModule(
433 PLOADER_PARAMETER_BLOCK LoaderBlock,
434 PCCH Path,
435 PCCH File,
436 TYPE_OF_MEMORY MemoryType,
437 PLDR_DATA_TABLE_ENTRY *Dte,
438 BOOLEAN IsKdTransportDll,
439 ULONG Percentage)
440 {
441 BOOLEAN Success;
442 CHAR FullFileName[MAX_PATH];
443 CHAR ProgressString[256];
444 PVOID BaseAdress = NULL;
445
446 UiDrawBackdrop();
447 sprintf(ProgressString, "Loading %s...", File);
448 UiDrawProgressBarCenter(Percentage, 100, ProgressString);
449
450 strcpy(FullFileName, Path);
451 strcat(FullFileName, "SYSTEM32\\");
452 strcat(FullFileName, File);
453
454 Success = WinLdrLoadImage(FullFileName, MemoryType, &BaseAdress);
455 if (!Success)
456 {
457 TRACE("Loading %s failed\n", File);
458 return FALSE;
459 }
460 TRACE("%s loaded successfully at %p\n", File, BaseAdress);
461
462 strcpy(FullFileName, "WINDOWS\\SYSTEM32\\");
463 strcat(FullFileName, File);
464 /*
465 * Cheat about the base DLL name if we are loading
466 * the Kernel Debugger Transport DLL, to make the
467 * PE loader happy.
468 */
469 Success = WinLdrAllocateDataTableEntry(&LoaderBlock->LoadOrderListHead,
470 (IsKdTransportDll ? "KDCOM.DLL" : File),
471 FullFileName,
472 BaseAdress,
473 Dte);
474
475 return Success;
476 }
477
478 static
479 BOOLEAN
480 LoadWindowsCore(IN USHORT OperatingSystemVersion,
481 IN OUT PLOADER_PARAMETER_BLOCK LoaderBlock,
482 IN LPCSTR BootOptions,
483 IN LPCSTR BootPath,
484 IN OUT PLDR_DATA_TABLE_ENTRY* KernelDTE)
485 {
486 BOOLEAN Success;
487 CHAR DirPath[MAX_PATH];
488 CHAR KdTransportDllName[MAX_PATH];
489 PLDR_DATA_TABLE_ENTRY HalDTE, KdComDTE = NULL;
490
491 if (!KernelDTE) return FALSE;
492
493 /* Load the Kernel */
494 LoadModule(LoaderBlock, BootPath, "NTOSKRNL.EXE", LoaderSystemCode, KernelDTE, FALSE, 30);
495
496 /* Load the HAL */
497 LoadModule(LoaderBlock, BootPath, "HAL.DLL", LoaderHalCode, &HalDTE, FALSE, 45);
498
499 /* Load the Kernel Debugger Transport DLL */
500 if (OperatingSystemVersion > _WIN32_WINNT_WIN2K)
501 {
502 /*
503 * According to http://www.nynaeve.net/?p=173 :
504 * "[...] Another enhancement that could be done Microsoft-side would be
505 * a better interface for replacing KD transport modules. Right now, due
506 * to the fact that ntoskrnl is static linked to KDCOM.DLL, the OS loader
507 * has a hardcoded hack that interprets the KD type in the OS loader options,
508 * loads one of the (hardcoded filenames) "kdcom.dll", "kd1394.dll", or
509 * "kdusb2.dll" modules, and inserts them into the loaded module list under
510 * the name "kdcom.dll". [...]"
511 */
512
513 /*
514 * This loop replaces a dumb call to strstr(..., "DEBUGPORT=").
515 * Indeed I want it to be case-insensitive to allow "debugport="
516 * or "DeBuGpOrT=" or... , and I don't want it to match malformed
517 * command-line options, such as:
518 *
519 * "...foo DEBUGPORT=xxx bar..."
520 * "...foo/DEBUGPORT=xxx bar..."
521 * "...foo/DEBUGPORT=bar..."
522 *
523 * i.e. the "DEBUGPORT=" switch must start with a slash and be separated
524 * from the rest by whitespace, unless it begins the command-line, e.g.:
525 *
526 * "/DEBUGPORT=COM1 foo...bar..."
527 * "...foo /DEBUGPORT=USB bar..."
528 * or:
529 * "...foo /DEBUGPORT= bar..."
530 * (in that case, we default the port to COM).
531 */
532 while (BootOptions)
533 {
534 /* Skip possible initial whitespace */
535 BootOptions += strspn(BootOptions, " \t");
536
537 /* Check whether a new commutator starts and it is the DEBUGPORT one */
538 if (*BootOptions != '/' || _strnicmp(++BootOptions, "DEBUGPORT=", 10) != 0)
539 {
540 /* Search for another whitespace */
541 BootOptions = strpbrk(BootOptions, " \t");
542 continue;
543 }
544 else
545 {
546 /* We found the DEBUGPORT commutator. Move to the port name. */
547 BootOptions += 10;
548 break;
549 }
550 }
551
552 if (BootOptions)
553 {
554 /*
555 * We have found the DEBUGPORT commutator. Parse the port name.
556 * Format: /DEBUGPORT=COM1 or /DEBUGPORT=FILE:\Device\HarddiskX\PartitionY\debug.log or /DEBUGPORT=FOO
557 * If we only have /DEBUGPORT= (i.e. without any port name), defaults it to "COM".
558 */
559 strcpy(KdTransportDllName, "KD");
560 if (_strnicmp(BootOptions, "COM", 3) == 0 && '0' <= BootOptions[3] && BootOptions[3] <= '9')
561 {
562 strncat(KdTransportDllName, BootOptions, 3);
563 }
564 else
565 {
566 size_t i = strcspn(BootOptions, " \t:"); /* Skip valid separators: whitespace or colon */
567 if (i == 0)
568 strcat(KdTransportDllName, "COM");
569 else
570 strncat(KdTransportDllName, BootOptions, i);
571 }
572 strcat(KdTransportDllName, ".DLL");
573 _strupr(KdTransportDllName);
574
575 /*
576 * Load the transport DLL. Specify it to LoadModule so that it can
577 * change the base DLL name of the loaded transport DLL to the default
578 * "KDCOM.DLL" name, to make the PE loader happy.
579 */
580 LoadModule(LoaderBlock, BootPath, KdTransportDllName, LoaderSystemCode, &KdComDTE, TRUE, 60);
581 }
582 }
583
584 /* Load all referenced DLLs for Kernel, HAL and Kernel Debugger Transport DLL */
585 strcpy(DirPath, BootPath);
586 strcat(DirPath, "system32\\");
587 Success = WinLdrScanImportDescriptorTable(&LoaderBlock->LoadOrderListHead, DirPath, *KernelDTE);
588 Success &= WinLdrScanImportDescriptorTable(&LoaderBlock->LoadOrderListHead, DirPath, HalDTE);
589 if (KdComDTE)
590 {
591 Success &= WinLdrScanImportDescriptorTable(&LoaderBlock->LoadOrderListHead, DirPath, KdComDTE);
592 }
593
594 return Success;
595 }
596
597 VOID
598 LoadAndBootWindows(IN OperatingSystemItem* OperatingSystem,
599 IN USHORT OperatingSystemVersion)
600 {
601 ULONG_PTR SectionId;
602 PCSTR SectionName = OperatingSystem->SystemPartition;
603 CHAR SettingsValue[80];
604 BOOLEAN HasSection;
605 CHAR BootPath[MAX_PATH];
606 CHAR FileName[MAX_PATH];
607 CHAR BootOptions[256];
608 PCHAR File;
609 BOOLEAN Success;
610 PLOADER_PARAMETER_BLOCK LoaderBlock;
611
612 /* Get OS setting value */
613 SettingsValue[0] = ANSI_NULL;
614 IniOpenSection("Operating Systems", &SectionId);
615 IniReadSettingByName(SectionId, SectionName, SettingsValue, sizeof(SettingsValue));
616
617 /* Open the operating system section specified in the .ini file */
618 HasSection = IniOpenSection(SectionName, &SectionId);
619
620 UiDrawBackdrop();
621 UiDrawProgressBarCenter(1, 100, "Loading NT...");
622
623 /* Read the system path is set in the .ini file */
624 if (!HasSection ||
625 !IniReadSettingByName(SectionId, "SystemPath", BootPath, sizeof(BootPath)))
626 {
627 strcpy(BootPath, SectionName);
628 }
629
630 /*
631 * Check whether BootPath is a full path
632 * and if not, create a full boot path.
633 *
634 * See FsOpenFile for the technique used.
635 */
636 if (strrchr(BootPath, ')') == NULL)
637 {
638 /* Temporarily save the boot path */
639 strcpy(FileName, BootPath);
640
641 /* This is not a full path. Use the current (i.e. boot) device. */
642 MachDiskGetBootPath(BootPath, sizeof(BootPath));
643
644 /* Append a path separator if needed */
645 if (FileName[0] != '\\' && FileName[0] != '/')
646 strcat(BootPath, "\\");
647
648 /* Append the remaining path */
649 strcat(BootPath, FileName);
650 }
651
652 /* Append a backslash if needed */
653 if ((strlen(BootPath) == 0) || BootPath[strlen(BootPath) - 1] != '\\')
654 strcat(BootPath, "\\");
655
656 /* Read booting options */
657 if (!HasSection || !IniReadSettingByName(SectionId, "Options", BootOptions, sizeof(BootOptions)))
658 {
659 /* Get options after the title */
660 PCSTR p = SettingsValue;
661 while (*p == ' ' || *p == '"')
662 p++;
663 while (*p != '\0' && *p != '"')
664 p++;
665 strcpy(BootOptions, p);
666 TRACE("BootOptions: '%s'\n", BootOptions);
667 }
668
669 /* Append boot-time options */
670 AppendBootTimeOptions(BootOptions);
671
672 /* Check if a ramdisk file was given */
673 File = strstr(BootOptions, "/RDPATH=");
674 if (File)
675 {
676 /* Copy the file name and everything else after it */
677 strcpy(FileName, File + 8);
678
679 /* Null-terminate */
680 *strstr(FileName, " ") = ANSI_NULL;
681
682 /* Load the ramdisk */
683 if (!RamDiskLoadVirtualFile(FileName))
684 {
685 UiMessageBox("Failed to load RAM disk file %s", FileName);
686 return;
687 }
688 }
689
690 /* Let user know we started loading */
691 //UiDrawStatusText("Loading...");
692
693 TRACE("BootPath: '%s'\n", BootPath);
694
695 /* Allocate and minimalistic-initialize LPB */
696 AllocateAndInitLPB(&LoaderBlock);
697
698 /* Load Hive */
699 UiDrawBackdrop();
700 UiDrawProgressBarCenter(15, 100, "Loading system hive...");
701 Success = WinLdrInitSystemHive(LoaderBlock, BootPath);
702 TRACE("SYSTEM hive %s\n", (Success ? "loaded" : "not loaded"));
703
704 /* Load NLS data, OEM font, and prepare boot drivers list */
705 Success = WinLdrScanSystemHive(LoaderBlock, BootPath);
706 TRACE("SYSTEM hive %s\n", (Success ? "scanned" : "not scanned"));
707
708 /* Finish loading */
709 LoadAndBootWindowsCommon(OperatingSystemVersion,
710 LoaderBlock,
711 BootOptions,
712 BootPath,
713 FALSE);
714 }
715
716 VOID
717 LoadAndBootWindowsCommon(
718 USHORT OperatingSystemVersion,
719 PLOADER_PARAMETER_BLOCK LoaderBlock,
720 LPCSTR BootOptions,
721 LPCSTR BootPath,
722 BOOLEAN Setup)
723 {
724 PLOADER_PARAMETER_BLOCK LoaderBlockVA;
725 BOOLEAN Success;
726 PLDR_DATA_TABLE_ENTRY KernelDTE;
727 KERNEL_ENTRY_POINT KiSystemStartup;
728 LPCSTR SystemRoot;
729 TRACE("LoadAndBootWindowsCommon()\n");
730
731 #ifdef _M_IX86
732 /* Setup redirection support */
733 WinLdrSetupEms((PCHAR)BootOptions);
734 #endif
735
736 /* Convert BootPath to SystemRoot */
737 SystemRoot = strstr(BootPath, "\\");
738
739 /* Detect hardware */
740 LoaderBlock->ConfigurationRoot = MachHwDetect();
741
742 if (OperatingSystemVersion == 0)
743 OperatingSystemVersion = WinLdrDetectVersion();
744
745 /* Load the operating system core: the Kernel, the HAL and the Kernel Debugger Transport DLL */
746 Success = LoadWindowsCore(OperatingSystemVersion,
747 LoaderBlock,
748 BootOptions,
749 BootPath,
750 &KernelDTE);
751 if (!Success)
752 {
753 UiMessageBox("Error loading NTOS core.");
754 return;
755 }
756
757 /* Load boot drivers */
758 UiDrawBackdrop();
759 UiDrawProgressBarCenter(100, 100, "Loading boot drivers...");
760 Success = WinLdrLoadBootDrivers(LoaderBlock, BootPath);
761 TRACE("Boot drivers loading %s\n", Success ? "successful" : "failed");
762
763 /* Initialize Phase 1 - no drivers loading anymore */
764 WinLdrInitializePhase1(LoaderBlock,
765 BootOptions,
766 SystemRoot,
767 BootPath,
768 OperatingSystemVersion);
769
770 /* Save entry-point pointer and Loader block VAs */
771 KiSystemStartup = (KERNEL_ENTRY_POINT)KernelDTE->EntryPoint;
772 LoaderBlockVA = PaToVa(LoaderBlock);
773
774 /* "Stop all motors", change videomode */
775 MachPrepareForReactOS(Setup);
776
777 /* Cleanup ini file */
778 IniCleanup();
779
780 /* Debugging... */
781 //DumpMemoryAllocMap();
782
783 /* Do the machine specific initialization */
784 WinLdrSetupMachineDependent(LoaderBlock);
785
786 /* Map pages and create memory descriptors */
787 WinLdrSetupMemoryLayout(LoaderBlock);
788
789 /* Set processor context */
790 WinLdrSetProcessorContext();
791
792 /* Save final value of LoaderPagesSpanned */
793 LoaderBlock->Extension->LoaderPagesSpanned = LoaderPagesSpanned;
794
795 TRACE("Hello from paged mode, KiSystemStartup %p, LoaderBlockVA %p!\n",
796 KiSystemStartup, LoaderBlockVA);
797
798 // Zero KI_USER_SHARED_DATA page
799 memset((PVOID)KI_USER_SHARED_DATA, 0, MM_PAGE_SIZE);
800
801 WinLdrpDumpMemoryDescriptors(LoaderBlockVA);
802 WinLdrpDumpBootDriver(LoaderBlockVA);
803 #ifndef _M_AMD64
804 WinLdrpDumpArcDisks(LoaderBlockVA);
805 #endif
806
807 /* Pass control */
808 (*KiSystemStartup)(LoaderBlockVA);
809 }
810
811 VOID
812 WinLdrpDumpMemoryDescriptors(PLOADER_PARAMETER_BLOCK LoaderBlock)
813 {
814 PLIST_ENTRY NextMd;
815 PMEMORY_ALLOCATION_DESCRIPTOR MemoryDescriptor;
816
817 NextMd = LoaderBlock->MemoryDescriptorListHead.Flink;
818
819 while (NextMd != &LoaderBlock->MemoryDescriptorListHead)
820 {
821 MemoryDescriptor = CONTAINING_RECORD(NextMd, MEMORY_ALLOCATION_DESCRIPTOR, ListEntry);
822
823 TRACE("BP %08X PC %04X MT %d\n", MemoryDescriptor->BasePage,
824 MemoryDescriptor->PageCount, MemoryDescriptor->MemoryType);
825
826 NextMd = MemoryDescriptor->ListEntry.Flink;
827 }
828 }
829
830 VOID
831 WinLdrpDumpBootDriver(PLOADER_PARAMETER_BLOCK LoaderBlock)
832 {
833 PLIST_ENTRY NextBd;
834 PBOOT_DRIVER_LIST_ENTRY BootDriver;
835
836 NextBd = LoaderBlock->BootDriverListHead.Flink;
837
838 while (NextBd != &LoaderBlock->BootDriverListHead)
839 {
840 BootDriver = CONTAINING_RECORD(NextBd, BOOT_DRIVER_LIST_ENTRY, Link);
841
842 TRACE("BootDriver %wZ DTE %08X RegPath: %wZ\n", &BootDriver->FilePath,
843 BootDriver->LdrEntry, &BootDriver->RegistryPath);
844
845 NextBd = BootDriver->Link.Flink;
846 }
847 }
848
849 VOID
850 WinLdrpDumpArcDisks(PLOADER_PARAMETER_BLOCK LoaderBlock)
851 {
852 PLIST_ENTRY NextBd;
853 PARC_DISK_SIGNATURE ArcDisk;
854
855 NextBd = LoaderBlock->ArcDiskInformation->DiskSignatureListHead.Flink;
856
857 while (NextBd != &LoaderBlock->ArcDiskInformation->DiskSignatureListHead)
858 {
859 ArcDisk = CONTAINING_RECORD(NextBd, ARC_DISK_SIGNATURE, ListEntry);
860
861 TRACE("ArcDisk %s checksum: 0x%X, signature: 0x%X\n",
862 ArcDisk->ArcName, ArcDisk->CheckSum, ArcDisk->Signature);
863
864 NextBd = ArcDisk->ListEntry.Flink;
865 }
866 }