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

Archive Download this file

Revision: 1441