Chameleon

Chameleon Svn Source Tree

Root/branches/azimutz/trunkAutoResolution/i386/boot2/boot.c

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 "gui.h"
60#include "platform.h"
61#include "autoresolution.h" //autoresolution
62#include "edid.h"//||
63#include "modules.h"
64
65long gBootMode; /* defaults to 0 == kBootModeNormal */
66bool gOverrideKernel;
67static char gBootKernelCacheFile[512];
68static char gCacheNameAdler[64 + 256];
69char *gPlatformName = gCacheNameAdler;
70char gRootDevice[512];
71char gMKextName[512];
72char gMacOSVersion[8];
73bool gEnableCDROMRescan;
74bool gScanSingleDrive;
75
76int bvCount = 0;
77//intmenucount = 0;
78int gDeviceCount = 0;
79
80BVRef bvr;
81BVRef menuBVR;
82BVRef bvChain;
83bool useGUI;
84
85//static void selectBiosDevice(void);
86static unsigned long Adler32(unsigned char *buffer, long length);
87static bool checkOSVersion(const char * version);
88static bool getOSVersion();
89
90static bool gUnloadPXEOnExit = false;
91
92/*
93 * How long to wait (in seconds) to load the
94 * kernel after displaying the "boot:" prompt.
95 */
96#define kBootErrorTimeout 5
97
98
99//==========================================================================
100// Zero the BSS.
101
102static void zeroBSS(void)
103{
104extern char _DATA__bss__begin, _DATA__bss__end;
105extern char _DATA__common__begin, _DATA__common__end;
106
107bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
108bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
109}
110
111//==========================================================================
112// Malloc error function
113
114static void malloc_error(char *addr, size_t size, const char *file, int line)
115{
116stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
117}
118
119//==========================================================================
120//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
121//
122void initialize_runtime(void)
123{
124zeroBSS();
125malloc_init(0, 0, 0, malloc_error);
126}
127
128//==========================================================================
129// execKernel - Load the kernel image (mach-o) and jump to its entry point.
130
131static int ExecKernel(void *binary)
132{
133entry_t kernelEntry;
134int ret;
135
136bootArgs->kaddr = bootArgs->ksize = 0;
137execute_hook("ExecKernel", (void*)binary, NULL, NULL, NULL);
138
139ret = DecodeKernel(binary,
140 &kernelEntry,
141 (char **) &bootArgs->kaddr,
142 (int *)&bootArgs->ksize );
143
144if ( ret != 0 )
145return ret;
146
147// Reserve space for boot args
148reserveKernBootStruct();
149
150// Notify modules that the kernel has been decoded
151execute_hook("DecodedKernel", (void*)binary, NULL, NULL, NULL);
152
153 setupFakeEfi();
154
155// Load boot drivers from the specifed root path.
156 //if (!gHaveKernelCache)
157 LoadDrivers("/");
158
159 execute_hook("DriversLoaded", (void*)binary, NULL, NULL, NULL);
160
161clearActivityIndicator();
162
163if (gErrors) {
164printf("Errors encountered while starting up the computer.\n");
165printf("Pausing %d seconds...\n", kBootErrorTimeout);
166sleep(kBootErrorTimeout);
167}
168
169md0Ramdisk();
170
171verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
172
173// Cleanup the PXE base code.
174
175if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
176if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
177{
178printf("nbpUnloadBaseCode error %d\n", (int) ret);
179sleep(2);
180}
181}
182
183bool dummyVal;
184if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->chameleonConfig) && dummyVal) {
185printf("(Wait) ");
186pause();
187}
188
189usb_loop();
190
191//autoresolution - Check if user disabled AutoResolution at the boot prompt.
192getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig); //Azi: bootConfig ??
193
194// User disabled AutoResolution at boot prompt...
195if ((gAutoResolution == false) && map)
196{
197// restore and close Vbios for patch cancelation.
198restoreVbios(map);
199closeVbios(map);
200}
201
202//Azi: while testing, i didn't got any problems when booting without
203// closing Vbios... closing it just in case. (check again later!)
204if ((gAutoResolution == true) && map)
205{
206closeVbios(map);
207
208// gAutoResolution was just set to false on closeVbios();
209// we need it to be "true" for drawBootGraphics().
210gAutoResolution = true;
211}
212
213//Azi: closing Vbios after "if (gVerboseMode)" stuff eliminates the need for setting
214// AutoResolution = true above; but creates another bug when booting in TextMode with -v arg.
215// Simptoms include: staring some seconds at a nicely drawn white screen, after boot prompt.
216// Think i'm just going to end up removing setting gAutoResolution = false
217// on closeVbios().. the more i think, the less sense it makes doing it there!!
218//autoresolution - end
219
220 if (checkOSVersion("10.7"))
221 {
222 execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);// Notify modules that the kernel is about to be started
223 }
224 else
225 {
226 execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgsPreLion, NULL, NULL);// Notify modules that the kernel is about to be started
227 }
228
229// If we were in text mode, switch to graphics mode.
230// This will draw the boot graphics unless we are in
231// verbose mode.
232
233if(gVerboseMode)
234 setVideoMode( GRAPHICS_MODE, 0 );
235else
236 drawBootGraphics();
237
238setupBooterLog();
239
240finalizeBootStruct();
241
242 if (checkOSVersion("10.7")) {
243
244// Masking out so that Lion doesn't doublefault
245outb(0x21, 0xff);/* Maskout all interrupts Pic1 */
246outb(0xa1, 0xff);/* Maskout all interrupts Pic2 */
247
248// Jump to kernel's entry point. There's no going back now.
249
250startprog( kernelEntry, bootArgs );
251}
252else {
253// Jump to kernel's entry point. There's no going back now.
254
255startprog( kernelEntry, bootArgsPreLion );
256}
257
258// Not reached
259return 0;
260}
261
262//==========================================================================
263// This is the entrypoint from real-mode which functions exactly as it did
264// before. Multiboot does its own runtime initialization, does some of its
265// own things, and then calls common_boot.
266void boot(int biosdev)
267{
268initialize_runtime();
269// Enable A20 gate before accessing memory above 1Mb.
270enableA20();
271common_boot(biosdev);
272}
273
274//==========================================================================
275// The 'main' function for the booter. Called by boot0 when booting
276// from a block device, or by the network booter.
277//
278// arguments:
279// biosdev - Value passed from boot1/NBP to specify the device
280// that the booter was loaded from.
281//
282// If biosdev is kBIOSDevNetwork, then this function will return if
283// booting was unsuccessful. This allows the PXE firmware to try the
284// next boot device on its list.
285void common_boot(int biosdev)
286{
287 int status;
288 char *bootFile;
289 unsigned long adler32;
290 bool quiet;
291 bool firstRun = true;
292 bool instantMenu;
293 bool rescanPrompt;
294 unsigned int allowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot;
295 unsigned int denyBVFlags = kBVFlagEFISystem;
296
297 // Set reminder to unload the PXE base code. Neglect to unload
298 // the base code will result in a hang or kernel panic.
299 gUnloadPXEOnExit = true;
300
301 // Record the device that the booter was loaded from.
302 gBIOSDev = biosdev & kBIOSDevMask;
303
304 // Initialize boot info structure.
305 initKernBootStruct();
306
307initBooterLog();
308
309 // Setup VGA text mode.
310 // Not sure if it is safe to call setVideoMode() before the
311 // config table has been loaded. Call video_mode() instead.
312#if DEBUG
313 printf("before video_mode\n");
314#endif
315 video_mode( 2 ); // 80x25 mono text mode.
316#if DEBUG
317 printf("after video_mode\n");
318#endif
319
320 // Scan and record the system's hardware information.
321 scan_platform();
322
323 // First get info for boot volume.
324 scanBootVolumes(gBIOSDev, 0);
325 bvChain = getBVChainForBIOSDev(gBIOSDev);
326 setBootGlobals(bvChain);
327
328 // Load boot.plist config file
329 status = loadChameleonConfig(&bootInfo->chameleonConfig);
330
331 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) {
332 gBootMode |= kBootModeQuiet;
333 }
334
335 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
336 if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) {
337 firstRun = false;
338 }
339
340 // Loading preboot ramdisk if exists.
341 loadPrebootRAMDisk();
342
343 // Disable rescan option by default
344 gEnableCDROMRescan = false;
345
346 // Enable it with Rescan=y in system config
347 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig) && gEnableCDROMRescan) {
348 gEnableCDROMRescan = true;
349 }
350
351 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
352 rescanPrompt = false;
353 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
354 gEnableCDROMRescan = promptForRescanOption();
355 }
356
357 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
358 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig) && gScanSingleDrive) {
359 gScanSingleDrive = true;
360 }
361
362 // Create a list of partitions on device(s).
363 if (gScanSingleDrive) {
364 scanBootVolumes(gBIOSDev, &bvCount);
365 } else {
366 scanDisks(gBIOSDev, &bvCount);
367 }
368
369 // Create a separated bvr chain using the specified filters.
370 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
371
372 gBootVolume = selectBootVolume(bvChain);
373
374// Intialize module system
375init_module_system();
376
377#if DEBUG
378 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
379 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
380 getchar();
381#endif
382
383useGUI = true;
384// Override useGUI default
385getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig);
386
387//autoresolution - default to false
388// http://forum.voodooprojects.org/index.php/topic,1227.0.html
389gAutoResolution = false;
390
391// Check if user enabled AutoResolution on Boot.plist...
392getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
393
394// Patch the Video Bios with the extracted resolution, before initGui.
395if (gAutoResolution == true)
396{
397paramsAR[3] = 0;
398
399// Open the Vbios and store Vbios or Tables
400//Azi: doing this only if gAutoResolution = true
401map = openVbios(CT_UNKWN);
402
403//Get resolution from Graphics Mode key...
404int count = getNumberArrayFromProperty(kGraphicsModeKey, paramsAR, 4);
405// ... or EDID.
406if (count < 3)
407{
408getResolution(paramsAR); //Azi: hum...
409// check the DEBUG/PRINT stuff... also on TEXT MODE (this is not printing to screen). ???
410// don't forget we now have boot-log and it prints fine there.
411//Azi:autoresolution - these PRINT replace a previous existing #ifdef AUTORES_DEBUG
412// and were moved from gui.c, initGUI().
413PRINT("Resolution: %dx%d (EDID)\n",paramsAR[0], paramsAR[1]);
414}
415else //Azi: check theme.plist ??
416{
417PRINT("Resolution: %dx%d (Graphics Mode key)\n",paramsAR[0], paramsAR[1]);
418
419//Azi: hum...
420if ( paramsAR[2] == 256 ) paramsAR[2] = 8;
421if ( paramsAR[2] == 555 ) paramsAR[2] = 16;
422if ( paramsAR[2] == 888 ) paramsAR[2] = 32;
423}
424
425// perfom the actual Vbios patching
426if (paramsAR[0] != 0 && paramsAR[1] != 0)
427{
428patchVbios(map, paramsAR[0], paramsAR[1], paramsAR[2], 0, 0);
429}
430
431//Azi: passing resolution for TEXT MODE "verbose" boot. (check again later!)***
432if (bootArgs->Video.v_display == VGA_TEXT_MODE)
433{
434gui.screen.width = paramsAR[0];
435gui.screen.height = paramsAR[1];
436}
437
438// If the patch is working properly, we're almost done (we need? to close Vbios).
439// If not and it's just a matter of wrong resolution, we can try re-apply the patch;
440// see "case kF2Key:", options.c.
441}
442//autoresolution - end
443
444if (useGUI && initGUI())
445{
446// initGUI() returned with an error, disabling GUI.
447useGUI = false;
448}
449
450 setBootGlobals(bvChain);
451
452 // Parse args, load and start kernel.
453 while (1) {
454 const char *val;
455 int len;
456 int trycache;
457 long flags, cachetime, kerneltime, exttime, sleeptime, time;
458 int ret = -1;
459 void *binary = (void *)kLoadAddr;
460 bool tryresume;
461 bool tryresumedefault;
462 bool forceresume;
463bool usecache = false;//true;
464
465 // additional variable for testing alternate kernel image locations on boot helper partitions.
466 char bootFileSpec[512];
467
468 // Initialize globals.
469
470 sysConfigValid = false;
471 gErrors = false;
472
473 status = getBootOptions(firstRun);
474 firstRun = false;
475 if (status == -1) continue;
476
477 status = processBootOptions();
478 // Status==1 means to chainboot
479 if ( status == 1 ) break;
480 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
481 if ( status == -1 )
482 {
483 // gBootVolume == NULL usually means the user hit escape.
484 if(gBootVolume == NULL)
485 {
486 freeFilteredBVChain(bvChain);
487
488 if (gEnableCDROMRescan)
489 rescanBIOSDevice(gBIOSDev);
490
491 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
492 setBootGlobals(bvChain);
493 setupDeviceList(&bootInfo->themeConfig);
494 }
495 continue;
496 }
497
498 // Other status (e.g. 0) means that we should proceed with boot.
499
500// Turn off any GUI elements
501if( bootArgs->Video.v_display == GRAPHICS_MODE )
502{
503gui.devicelist.draw = false;
504gui.bootprompt.draw = false;
505gui.menu.draw = false;
506gui.infobox.draw = false;
507gui.logo.draw = false;
508drawBackground();
509updateVRAM();
510}
511
512//Azi: autoresolution stuff moved to ExecKernel();
513// Closing Vbios here without restoring it, causes an allocation error.
514
515// Find out which version mac os we're booting.
516getOSVersion();
517
518if (platformCPUFeature(CPU_FEATURE_EM64T)) {
519archCpuType = CPU_TYPE_X86_64;
520} else {
521archCpuType = CPU_TYPE_I386;
522}
523if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) {
524if (strncmp(val, "i386", 4) == 0) {
525archCpuType = CPU_TYPE_I386;
526}
527}
528
529 if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) {
530if (strncmp(val, "i386", 4) == 0) {
531archCpuType = CPU_TYPE_I386;
532}
533}
534
535 //archCpuType = CPU_TYPE_I386;
536
537// Notify moduals that we are attempting to boot
538execute_hook("PreBoot", NULL, NULL, NULL, NULL);
539
540if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) {
541tryresume = true;
542tryresumedefault = true;
543} else {
544tryresumedefault = false;
545}
546
547if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) {
548forceresume = false;
549}
550
551if (forceresume) {
552tryresume = true;
553tryresumedefault = false;
554}
555
556while (tryresume) {
557const char *tmp;
558BVRef bvr;
559if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig))
560val="/private/var/vm/sleepimage";
561
562// Do this first to be sure that root volume is mounted
563ret = GetFileInfo(0, val, &flags, &sleeptime);
564
565if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
566break;
567
568// Can't check if it was hibernation Wake=y is required
569if (bvr->modTime == 0 && tryresumedefault)
570break;
571
572if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
573break;
574
575if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
576printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
577break;
578}
579
580HibernateBoot((char *)val);
581break;
582}
583
584getBoolForKey(kUseKernelCache, &usecache, &bootInfo->chameleonConfig);
585if(usecache) {
586if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
587 if(val[0] == '\\')
588 {
589 len--;
590 val++;
591 }
592 strlcpy(gBootKernelCacheFile, val, len+1);
593}
594else {
595//Lion
596if (checkOSVersion("10.7")) {
597sprintf(gBootKernelCacheFile, "%skernelcache", kDefaultCachePathSnow);
598}
599// Snow Leopard
600else if (checkOSVersion("10.6")) {
601sprintf(gBootKernelCacheFile, "kernelcache_%s", (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64");
602int lnam = sizeof(gBootKernelCacheFile) + 9; //with adler32
603//Slice - TODO ???
604// e.g. kernelcache_i386.E102928C.qSs0 = "unsaved" cache file.
605//
606// See kext_tools-180.2.1/kextcache_main.c:
607// "Source directory has changed since starting; "
608 // "not saving cache file %s."
609// or
610// "Source kernel has changed since starting; "
611 // "not saving cache file %s."
612
613char* name;
614long prev_time = 0;
615
616struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow);
617
618while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0)
619{
620if(((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time && strstr(name, gBootKernelCacheFile) && (name[lnam] != '.'))
621{
622sprintf(gBootKernelCacheFile, "%s%s", kDefaultCachePathSnow, name);
623prev_time = time;
624}
625}
626}
627else {
628// Reset cache name.
629bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
630
631sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->chameleonConfig);
632
633adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
634
635sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePathLeo, adler32);
636}
637}
638}
639
640 // Check for cache file.
641 trycache = (usecache &&
642((gBootMode & kBootModeSafe) == 0) &&
643 !gOverrideKernel &&
644 (gBootFileType == kBlockDeviceType) &&
645 (gMKextName[0] == '\0') &&
646 (gBootKernelCacheFile[0] != '\0'));
647
648verbose("Loading Darwin %s\n", gMacOSVersion);
649
650 if (trycache) do {
651 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
652 if(ret != 0) kerneltime = 0;
653 else if ((flags & kFileTypeMask) != kFileTypeFlat) {
654 trycache = 0;
655 break;
656 }
657
658 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
659 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
660 || (cachetime < kerneltime)) {
661 trycache = 0;
662 break;
663 }
664 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
665 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
666 && (cachetime < exttime)) {
667 trycache = 0;
668 break;
669 }
670 if (ret == 0 && kerneltime > exttime) {
671 exttime = kerneltime;
672 }
673 if (ret == 0 && cachetime != (exttime + 1)) {
674 trycache = 0;
675 break;
676 }
677 } while (0);
678
679 do {
680 if (trycache) {
681 bootFile = gBootKernelCacheFile;
682
683verbose("Loading kernel cache %s\n", bootFile);
684
685 if (checkOSVersion("10.7")) {
686 ret = LoadThinFatFile(bootFile, &binary);
687}
688else {
689 ret = LoadFile(bootFile);
690binary = (void *)kLoadAddr;
691}
692
693 if (ret >= 0)
694 break;
695
696verbose("Kernel cache did not load %s\n ", bootFile);
697 }
698
699 bootFile = bootInfo->bootFile;
700
701 // Try to load kernel image from alternate locations on boot helper partitions.
702 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
703 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
704 if (ret == -1)
705 {
706 sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
707 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
708 if (ret == -1)
709 {
710 sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
711 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
712 if (ret == -1)
713 {
714 // No alternate location found, using the original kernel image path.
715 strcpy(bootFileSpec, bootFile);
716 }
717 }
718 }
719
720 if (checkOSVersion("10.7"))
721 {
722 //Lion, dont load kernel if haz cache
723 if (!trycache) {
724 verbose("Loading kernel %s\n", bootFileSpec);
725 ret = LoadThinFatFile(bootFileSpec, &binary);
726 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) {
727 archCpuType = CPU_TYPE_I386;
728 ret = LoadThinFatFile(bootFileSpec, &binary);
729 }
730 }
731else ret = 1;
732 }
733else {
734 //Snow Leopard or older
735 verbose("Loading kernel %s\n", bootFileSpec);
736 ret = LoadThinFatFile(bootFileSpec, &binary);
737 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) {
738 archCpuType = CPU_TYPE_I386;
739 ret = LoadThinFatFile(bootFileSpec, &binary);
740 }
741 }
742 } while (0);
743
744 clearActivityIndicator();
745#if DEBUG
746 printf("Pausing...");
747 sleep(8);
748#endif
749
750 if (ret <= 0) {
751printf("Can't find %s\n", bootFile);
752
753sleep(1);
754
755 if (gBootFileType == kNetworkDeviceType) {
756 // Return control back to PXE. Don't unload PXE base code.
757 gUnloadPXEOnExit = false;
758 break;
759 }
760 } else {
761 /* Won't return if successful. */
762 ret = ExecKernel(binary);
763 }
764 }
765
766 // chainboot
767 if (status==1) {
768if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
769setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
770}
771 }
772
773 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
774nbpUnloadBaseCode();
775 }
776}
777
778/*!
779 Selects a new BIOS device, taking care to update the global state appropriately.
780 */
781/*
782static void selectBiosDevice(void)
783{
784 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
785 CacheReset();
786 diskFreeMap(oldMap);
787 oldMap = NULL;
788
789 int dev = selectAlternateBootDevice(gBIOSDev);
790
791 BVRef bvchain = scanBootVolumes(dev, 0);
792 BVRef bootVol = selectBootVolume(bvchain);
793 gBootVolume = bootVol;
794 setRootVolume(bootVol);
795 gBIOSDev = dev;
796}
797*/
798
799bool checkOSVersion(const char * version)
800{
801return ((gMacOSVersion[0] == version[0]) && (gMacOSVersion[1] == version[1]) && (gMacOSVersion[2] == version[2]) && (gMacOSVersion[3] == version[3]));
802}
803
804bool getOSVersion()
805{
806bool valid = false;
807config_file_t systemVersion;
808const char *val;
809int len;
810
811if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
812{
813valid = true;
814}
815else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
816{
817valid = true;
818}
819
820if (valid)
821{
822if (getValueForKey(kProductVersion, &val, &len, &systemVersion))
823{
824// getValueForKey uses const char for val
825// so copy it and trim
826*gMacOSVersion = '\0';
827strncat(gMacOSVersion, val, MIN(len, 4));
828}
829else
830valid = false;
831}
832
833return valid;
834}
835
836#define BASE 65521L /* largest prime smaller than 65536 */
837#define NMAX 5000
838// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
839
840#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
841#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
842#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
843#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
844#define DO16(buf) DO8(buf,0); DO8(buf,8);
845
846unsigned long Adler32(unsigned char *buf, long len)
847{
848 unsigned long s1 = 1; // adler & 0xffff;
849 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
850 unsigned long result;
851 int k;
852
853 while (len > 0) {
854 k = len < NMAX ? len : NMAX;
855 len -= k;
856 while (k >= 16) {
857 DO16(buf);
858 buf += 16;
859 k -= 16;
860 }
861 if (k != 0) do {
862 s1 += *buf++;
863 s2 += s1;
864 } while (--k);
865 s1 %= BASE;
866 s2 %= BASE;
867 }
868 result = (s2 << 16) | s1;
869 return OSSwapHostToBigInt32(result);
870}
871

Archive Download this file

Revision: 1155