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