Chameleon

Chameleon Svn Source Tree

Root/branches/meklort/i386/boot2/boot.c

Source at commit 533 created 13 years 7 months ago.
By meklort, GUI module should now work in the four main cases (combo of embededtheme and /Extra/Themes). Only tested on my machines.
1/*
2 * Copyright (c) 1999-2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Portions Copyright (c) 1999-2003 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 2.0 (the "License"). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
12 * this file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON- INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
20 * under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24/*
25 * Mach Operating System
26 * Copyright (c) 1990 Carnegie-Mellon University
27 * Copyright (c) 1989 Carnegie-Mellon University
28 * All rights reserved. The CMU software License Agreement specifies
29 * the terms and conditions for use and redistribution.
30 */
31
32/*
33 * INTEL CORPORATION PROPRIETARY INFORMATION
34 *
35 * This software is supplied under the terms of a license agreement or
36 * nondisclosure agreement with Intel Corporation and may not be copied
37 * nor disclosed except in accordance with the terms of that agreement.
38 *
39 * Copyright 1988, 1989 by Intel Corporation
40 */
41
42/*
43 * Copyright 1993 NeXT Computer, Inc.
44 * All rights reserved.
45 */
46
47/*
48 * Completely reworked by Sam Streeper (sam_s@NeXT.com)
49 * Reworked again by Curtis Galloway (galloway@NeXT.com)
50 */
51
52
53#include "boot.h"
54#include "bootstruct.h"
55#include "fake_efi.h"
56#include "sl.h"
57#include "libsa.h"
58#include "ramdisk.h"
59#include "platform.h"
60#include "modules.h"
61
62long gBootMode; /* defaults to 0 == kBootModeNormal */
63bool gOverrideKernel;
64static char gBootKernelCacheFile[512];
65static char gCacheNameAdler[64 + 256];
66char *gPlatformName = gCacheNameAdler;
67char gRootDevice[512];
68char gMKextName[512];
69char gMacOSVersion[8];
70bool gEnableCDROMRescan;
71bool gScanSingleDrive;
72
73int bvCount = 0;
74//intmenucount = 0;
75int gDeviceCount = 0;
76
77boolrecoveryMode = false;
78
79BVRef bvr;
80BVRef menuBVR;
81BVRef bvChain;
82
83//static void selectBiosDevice(void);
84static unsigned long Adler32(unsigned char *buffer, long length);
85static bool getOSVersion(char *str);
86
87static bool gUnloadPXEOnExit = false;
88
89/*
90 * How long to wait (in seconds) to load the
91 * kernel after displaying the "boot:" prompt.
92 */
93#define kBootErrorTimeout 5
94
95/*
96 * Default path to kernel cache file
97 */
98#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/kernelcache"
99
100//==========================================================================
101// Zero the BSS.
102
103static void zeroBSS(void)
104{
105extern char _DATA__bss__begin, _DATA__bss__end;
106extern char _DATA__common__begin, _DATA__common__end;
107
108bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
109bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
110}
111
112//==========================================================================
113// Malloc error function
114
115static void malloc_error(char *addr, size_t size, const char *file, int line)
116{
117stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
118}
119
120//==========================================================================
121//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
122//
123void initialize_runtime(void)
124{
125zeroBSS();
126malloc_init(0, 0, 0, malloc_error);
127}
128
129//==========================================================================
130// execKernel - Load the kernel image (mach-o) and jump to its entry point.
131
132static int ExecKernel(void *binary)
133{
134 entry_t kernelEntry;
135 int ret;
136
137 bootArgs->kaddr = bootArgs->ksize = 0;
138
139 ret = DecodeKernel(binary,
140 &kernelEntry,
141 (char **) &bootArgs->kaddr,
142 (int *)&bootArgs->ksize );
143
144 if ( ret != 0 )
145 return ret;
146
147 // Reserve space for boot args
148 reserveKernBootStruct();
149
150 // Load boot drivers from the specifed root path.
151
152 if (!gHaveKernelCache) {
153LoadDrivers("/");
154 }
155
156 clearActivityIndicator();
157
158 if (gErrors) {
159 printf("Errors encountered while starting up the computer.\n");
160 printf("Pausing %d seconds...\n", kBootErrorTimeout);
161 sleep(kBootErrorTimeout);
162 }
163
164md0Ramdisk();
165
166 setupFakeEfi();
167
168 md0Ramdisk();
169
170 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
171
172 // Cleanup the PXE base code.
173
174 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
175if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
176 {
177 printf("nbpUnloadBaseCode error %d\n", (int) ret);
178 sleep(2);
179 }
180 }
181
182 bool dummyVal;
183if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
184printf("Press any key to continue...");
185getc();
186}
187
188usb_loop();
189
190 // If we were in text mode, switch to graphics mode.
191 // This will draw the boot graphics unless we are in
192 // verbose mode.
193
194 if(gVerboseMode)
195{
196if (bootArgs->Video.v_display == VGA_TEXT_MODE)
197{
198setVideoMode( GRAPHICS_MODE, 0 );
199}
200
201}
202
203setupBooterLog();
204
205 finalizeBootStruct();
206
207usb_loop();
208
209execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);// Notify modules that the kernel is about to be started
210
211// Jump to kernel's entry point. There's no going back now.
212 startprog( kernelEntry, bootArgs );
213
214 // Not reached
215
216 return 0;
217}
218
219//==========================================================================
220// This is the entrypoint from real-mode which functions exactly as it did
221// before. Multiboot does its own runtime initialization, does some of its
222// own things, and then calls common_boot.
223void boot(int biosdev)
224{
225initialize_runtime();
226// Enable A20 gate before accessing memory above 1Mb.
227enableA20();
228common_boot(biosdev);
229}
230
231//==========================================================================
232// The 'main' function for the booter. Called by boot0 when booting
233// from a block device, or by the network booter.
234//
235// arguments:
236// biosdev - Value passed from boot1/NBP to specify the device
237// that the booter was loaded from.
238//
239// If biosdev is kBIOSDevNetwork, then this function will return if
240// booting was unsuccessful. This allows the PXE firmware to try the
241// next boot device on its list.
242void common_boot(int biosdev)
243{
244 int status;
245 char *bootFile;
246 unsigned long adler32;
247 bool quiet;
248 bool firstRun = true;
249 bool instantMenu;
250 bool rescanPrompt;
251 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
252 unsigned int denyBVFlags = kBVFlagEFISystem;
253
254 // Set reminder to unload the PXE base code. Neglect to unload
255 // the base code will result in a hang or kernel panic.
256 gUnloadPXEOnExit = true;
257
258 // Record the device that the booter was loaded from.
259 gBIOSDev = biosdev & kBIOSDevMask;
260
261 // Initialize boot info structure.
262 initKernBootStruct();
263
264initBooterLog();
265
266 // Setup VGA text mode.
267 // Not sure if it is safe to call setVideoMode() before the
268 // config table has been loaded. Call video_mode() instead.
269#if DEBUG
270 printf("before video_mode\n");
271#endif
272 video_mode( 2 ); // 80x25 mono text mode.
273#if DEBUG
274 printf("after video_mode\n");
275#endif
276
277 // Scan and record the system's hardware information.
278 scan_platform();
279
280 // First get info for boot volume.
281 scanBootVolumes(gBIOSDev, 0);
282 bvChain = getBVChainForBIOSDev(gBIOSDev);
283 setBootGlobals(bvChain);
284
285 // Load boot.plist config file
286 status = loadSystemConfig(&bootInfo->bootConfig);
287
288 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) {
289 gBootMode |= kBootModeQuiet;
290 }
291
292 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
293 if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) {
294 firstRun = false;
295 }
296
297
298// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
299 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) {
300 gScanSingleDrive = true;
301 }
302
303// Create a list of partitions on device(s).
304 if (gScanSingleDrive) {
305scanBootVolumes(gBIOSDev, &bvCount);
306 } else {
307scanDisks(gBIOSDev, &bvCount);
308 }
309
310// Create a separated bvr chain using the specified filters.
311 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
312gBootVolume = selectBootVolume(bvChain);
313
314
315// Intialize module system
316if(init_module_system())
317{
318load_all_modules();
319}
320
321
322
323 // Loading preboot ramdisk if exists.
324 loadPrebootRAMDisk();
325
326 // Disable rescan option by default
327 gEnableCDROMRescan = false;
328
329 // Enable it with Rescan=y in system config
330 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) {
331 gEnableCDROMRescan = true;
332 }
333
334 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
335 rescanPrompt = false;
336 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
337 gEnableCDROMRescan = promptForRescanOption();
338 }
339
340
341
342
343#if DEBUG
344 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
345 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
346 getc();
347#endif
348
349
350
351 setBootGlobals(bvChain);
352
353 // Parse args, load and start kernel.
354 while (1) {
355 const char *val;
356 int len;
357 int trycache;
358 long flags, cachetime, kerneltime, exttime, sleeptime, time;
359 int ret = -1;
360 void *binary = (void *)kLoadAddr;
361 bool tryresume;
362 bool tryresumedefault;
363 bool forceresume;
364
365 // additional variable for testing alternate kernel image locations on boot helper partitions.
366 char bootFileSpec[512];
367
368 // Initialize globals.
369
370 sysConfigValid = false;
371 gErrors = false;
372
373 status = getBootOptions(firstRun);
374 firstRun = false;
375 if (status == -1) continue;
376
377 status = processBootOptions();
378 // Status==1 means to chainboot
379 if ( status == 1 ) break;
380 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
381 if ( status == -1 )
382 {
383// gBootVolume == NULL usually means the user hit escape.
384if(gBootVolume == NULL)
385{
386freeFilteredBVChain(bvChain);
387
388if (gEnableCDROMRescan)
389rescanBIOSDevice(gBIOSDev);
390
391bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
392setBootGlobals(bvChain);
393}
394continue;
395 }
396
397
398
399 // Other status (e.g. 0) means that we should proceed with boot.
400
401// Notify moduals that we are attempting to boot
402execute_hook("PreBoot", NULL, NULL, NULL, NULL);
403
404// Find out which version mac os we're booting.
405getOSVersion(gMacOSVersion);
406
407if (platformCPUFeature(CPU_FEATURE_EM64T)) {
408archCpuType = CPU_TYPE_X86_64;
409} else {
410archCpuType = CPU_TYPE_I386;
411}
412if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) {
413if (strncmp(val, "i386", 4) == 0) {
414archCpuType = CPU_TYPE_I386;
415}
416}
417
418if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) {
419tryresume = true;
420tryresumedefault = true;
421} else {
422tryresumedefault = false;
423}
424
425if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) {
426forceresume = false;
427}
428
429if (forceresume) {
430tryresume = true;
431tryresumedefault = false;
432}
433
434while (tryresume) {
435const char *tmp;
436BVRef bvr;
437if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig))
438val="/private/var/vm/sleepimage";
439
440// Do this first to be sure that root volume is mounted
441ret = GetFileInfo(0, val, &flags, &sleeptime);
442
443if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
444break;
445
446// Can't check if it was hibernation Wake=y is required
447if (bvr->modTime == 0 && tryresumedefault)
448break;
449
450if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
451break;
452
453if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
454printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
455break;
456}
457
458HibernateBoot((char *)val);
459break;
460}
461
462 // Reset cache name.
463 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
464
465 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
466
467 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
468
469 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
470 strlcpy(gBootKernelCacheFile, val, len+1);
471 } else {
472 sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePath, adler32);
473 }
474
475 // Check for cache file.
476 trycache = (((gBootMode & kBootModeSafe) == 0) &&
477 !gOverrideKernel &&
478 (gBootFileType == kBlockDeviceType) &&
479 (gMKextName[0] == '\0') &&
480 (gBootKernelCacheFile[0] != '\0'));
481
482verbose("Loading Darwin %s\n", gMacOSVersion);
483
484 if (trycache) do {
485
486 // if we haven't found the kernel yet, don't use the cache
487 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
488 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
489 trycache = 0;
490 break;
491 }
492 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
493 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
494 || (cachetime < kerneltime)) {
495 trycache = 0;
496 break;
497 }
498 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
499 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
500 && (cachetime < exttime)) {
501 trycache = 0;
502 break;
503 }
504 if (kerneltime > exttime) {
505 exttime = kerneltime;
506 }
507 if (cachetime != (exttime + 1)) {
508 trycache = 0;
509 break;
510 }
511 } while (0);
512
513 do {
514 if (trycache) {
515 bootFile = gBootKernelCacheFile;
516 verbose("Loading kernel cache %s\n", bootFile);
517 ret = LoadFile(bootFile);
518 binary = (void *)kLoadAddr;
519 if (ret >= 0) {
520 break;
521 }
522 }
523 bootFile = bootInfo->bootFile;
524
525 // Try to load kernel image from alternate locations on boot helper partitions.
526 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
527 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
528 if (ret == -1)
529 {
530sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
531ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
532if (ret == -1)
533{
534sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
535ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
536if (ret == -1)
537{
538// Not found any alternate locations, using the original kernel image path.
539strcpy(bootFileSpec, bootFile);
540}
541}
542 }
543
544 verbose("Loading kernel %s\n", bootFileSpec);
545 ret = LoadThinFatFile(bootFileSpec, &binary);
546 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
547 {
548archCpuType = CPU_TYPE_I386;
549ret = LoadThinFatFile(bootFileSpec, &binary);
550 }
551
552 } while (0);
553
554 clearActivityIndicator();
555#if DEBUG
556 printf("Pausing...");
557 sleep(8);
558#endif
559
560 if (ret <= 0) {
561printf("Can't find %s\n", bootFile);
562
563sleep(1);
564
565 if (gBootFileType == kNetworkDeviceType) {
566 // Return control back to PXE. Don't unload PXE base code.
567 gUnloadPXEOnExit = false;
568 break;
569 }
570 } else {
571 /* Won't return if successful. */
572// Notify modules that ExecKernel is about to be called
573execute_hook("ExecKernel", binary, NULL, NULL, NULL);
574 ret = ExecKernel(binary);
575 }
576 }
577
578 // chainboot
579 if (status==1) {
580if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
581setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
582}
583 }
584
585 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
586nbpUnloadBaseCode();
587 }
588}
589
590/*!
591 Selects a new BIOS device, taking care to update the global state appropriately.
592 */
593/*
594 static void selectBiosDevice(void)
595 {
596 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
597 CacheReset();
598 diskFreeMap(oldMap);
599 oldMap = NULL;
600
601 int dev = selectAlternateBootDevice(gBIOSDev);
602
603 BVRef bvchain = scanBootVolumes(dev, 0);
604 BVRef bootVol = selectBootVolume(bvchain);
605 gBootVolume = bootVol;
606 setRootVolume(bootVol);
607 gBIOSDev = dev;
608 }
609 */
610
611static bool getOSVersion(char *str)
612{
613bool valid = false;
614config_file_t systemVersion;
615const char *val;
616int len;
617
618if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
619{
620valid = true;
621}
622else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
623{
624valid = true;
625}
626
627if (valid)
628{
629if (getValueForKey(kProductVersion, &val, &len, &systemVersion))
630{
631// getValueForKey uses const char for val
632// so copy it and trim
633*str = '\0';
634strncat(str, val, MIN(len, 4));
635}
636else
637valid = false;
638}
639
640return valid;
641}
642
643#define BASE 65521L /* largest prime smaller than 65536 */
644#define NMAX 5000
645// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
646
647#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
648#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
649#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
650#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
651#define DO16(buf) DO8(buf,0); DO8(buf,8);
652
653unsigned long Adler32(unsigned char *buf, long len)
654{
655 unsigned long s1 = 1; // adler & 0xffff;
656 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
657 unsigned long result;
658 int k;
659
660 while (len > 0) {
661 k = len < NMAX ? len : NMAX;
662 len -= k;
663 while (k >= 16) {
664 DO16(buf);
665 buf += 16;
666 k -= 16;
667 }
668 if (k != 0) do {
669 s1 += *buf++;
670 s2 += s1;
671 } while (--k);
672 s1 %= BASE;
673 s2 %= BASE;
674 }
675 result = (s2 << 16) | s1;
676 return OSSwapHostToBigInt32(result);
677}
678

Archive Download this file

Revision: 533