Chameleon

Chameleon Svn Source Tree

Root/branches/Bungo/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 * INTEL CORPORATION PROPRIETARY INFORMATION
33 *
34 * This software is supplied under the terms of a license agreement or
35 * nondisclosure agreement with Intel Corporation and may not be copied
36 * nor disclosed except in accordance with the terms of that agreement.
37 *
38 *Copyright 1988, 1989 by Intel Corporation
39 *
40 *
41 * Copyright 1993 NeXT Computer, Inc.
42 * All rights reserved.
43 *
44 * Completely reworked by Sam Streeper (sam_s@NeXT.com)
45 * Reworked again by Curtis Galloway (galloway@NeXT.com)
46 */
47
48#include "boot.h"
49#include "bootstruct.h"
50#include "fake_efi.h"
51#include "sl.h"
52#include "libsa.h"
53#include "ramdisk.h"
54#include "gui.h"
55#include "platform.h"
56#include "modules.h"
57#include "device_tree.h"
58
59#ifndef DEBUG_BOOT2
60#define DEBUG_BOOT2 0
61#endif
62
63#if DEBUG_BOOT2
64#define DBG(x...)printf(x)
65#else
66#define DBG(x...)msglog(x)
67#endif
68
69/*
70 * How long to wait (in seconds) to load the
71 * kernel after displaying the "boot:" prompt.
72 */
73#define kBootErrorTimeout 5
74
75boolgOverrideKernel;
76boolgEnableCDROMRescan;
77boolgScanSingleDrive;
78booluseGUI;
79
80static boolgUnloadPXEOnExit = false;
81
82static chargCacheNameAdler[64 + 256];
83char*gPlatformName = gCacheNameAdler;
84
85chargRootDevice[ROOT_DEVICE_SIZE];
86chargMKextName[512];
87intbvCount = 0;
88intgDeviceCount = 0;
89//intmenucount = 0;
90longgBootMode; /* defaults to 0 == kBootModeNormal */
91
92BVRefbvr;
93BVRefmenuBVR;
94BVRefbvChain;
95
96static unsigned longAdler32(unsigned char *buffer, long length);
97//static voidselectBiosDevice(void);
98
99/** options.c **/
100extern char* msgbuf;
101void showTextBuffer(char *buf, int size);
102
103//==========================================================================
104// Zero the BSS.
105
106static void zeroBSS(void)
107{
108extern char bss_start __asm("section$start$__DATA$__bss");
109extern char bss_end __asm("section$end$__DATA$__bss");
110extern char common_start __asm("section$start$__DATA$__common");
111extern char common_end __asm("section$end$__DATA$__common");
112
113bzero(&bss_start, (&bss_end - &bss_start));
114bzero(&common_start, (&common_end - &common_start));
115}
116
117//==========================================================================
118// Malloc error function
119
120static void malloc_error(char *addr, size_t size, const char *file, int line)
121{
122stop("\nMemory allocation error! Addr: 0x%x, Size: 0x%x, File: %s, Line: %d\n",
123 (unsigned)addr, (unsigned)size, file, line);
124}
125
126//==========================================================================
127//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
128//
129void initialize_runtime(void)
130{
131zeroBSS();
132malloc_init(0, 0, 0, malloc_error);
133}
134
135//==========================================================================
136// ExecKernel - Load the kernel image (mach-o) and jump to its entry point.
137
138static int ExecKernel(void *binary)
139{
140intret;
141entry_tkernelEntry;
142
143bootArgs->kaddr = bootArgs->ksize = 0;
144execute_hook("ExecKernel", (void *)binary, NULL, NULL, NULL);
145
146ret = DecodeKernel(binary,
147 &kernelEntry,
148 (char **) &bootArgs->kaddr,
149 (int *)&bootArgs->ksize);
150
151if ( ret != 0 )
152{
153return ret;
154}
155
156// Reserve space for boot args
157reserveKernBootStruct();
158
159// Notify modules that the kernel has been decoded
160execute_hook("DecodedKernel", (void *)binary, (void *)bootArgs->kaddr, (void *)bootArgs->ksize, NULL);
161
162setupFakeEfi();
163
164// Load boot drivers from the specifed root path.
165//if (!gHaveKernelCache)
166{
167LoadDrivers("/");
168}
169
170execute_hook("DriversLoaded", (void *)binary, NULL, NULL, NULL);
171
172clearActivityIndicator();
173
174if (gErrors)
175{
176printf("Errors encountered while starting up the computer.\n");
177printf("Pausing %d seconds...\n", kBootErrorTimeout);
178sleep(kBootErrorTimeout);
179}
180
181md0Ramdisk();
182
183// Cleanup the PXE base code.
184
185if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit )
186{
187if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
188{
189printf("nbpUnloadBaseCode error %d\n", (int)ret);
190sleep(2);
191}
192}
193
194bool dummyVal;
195if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->chameleonConfig) && dummyVal)
196{
197showTextBuffer(msgbuf, strlen(msgbuf));
198}
199
200usb_loop();
201
202// If we were in text mode, switch to graphics mode.
203// This will draw the boot graphics unless we are in
204// verbose mode.
205if (gVerboseMode)
206{
207setVideoMode(GRAPHICS_MODE, 0);
208}
209else
210{
211drawBootGraphics();
212}
213
214getCurrentEDID();
215
216verbose("GUI Graphics: %dx%dx%d.\n", gui.screen.width, gui.screen.height, bootArgs->Video.v_depth);
217verbose("Boot Graphics: %dx%dx%d, mode=0x%04X.\n", bootArgs->Video.v_width, bootArgs->Video.v_height, bootArgs->Video.v_depth, getCurrentGraphicsMode());
218
219verbose("Starting Mac OS X %s [0x%08X], %s\n", gBootVolume->OSVersion, MacOSVerCurrent, gDarwinBuildVerStr);
220verbose("Boot Args: %s\n", bootArgs->CommandLine);
221#if DEBUG
222 pause("\n[DEBUG] ");
223#endif
224setupBooterLog();
225
226finalizeBootStruct();
227
228// Jump to kernel's entry point. There's no going back now.
229if (MacOSVerCurrent >= MacOSVer2Int("10.7"))
230//if (!((checkOSVersion("10.4")) || (checkOSVersion("10.5")) || (checkOSVersion("10.6"))) )
231{
232// Notify modules that the kernel is about to be started
233execute_hook("Kernel Start", (void *)kernelEntry, (void *)bootArgs, NULL, NULL);
234
235// Masking out so that Lion doesn't doublefault
236outb(0x21, 0xff);/* Maskout all interrupts Pic1 */
237outb(0xa1, 0xff);/* Maskout all interrupts Pic2 */
238
239startprog( kernelEntry, bootArgs );
240}
241else
242{
243// Notify modules that the kernel is about to be started
244execute_hook("Kernel Start", (void *)kernelEntry, (void*)bootArgsPreLion, NULL, NULL);
245
246startprog( kernelEntry, bootArgsPreLion );
247}
248
249// Not reached
250return 0;
251}
252
253
254//==========================================================================
255// LoadKernelCache - Try to load Kernel Cache.
256// return the length of the loaded cache file or -1 on error
257long LoadKernelCache(const char* cacheFile, void **binary)
258{
259charkernelCacheFile[512];
260charkernelCachePath[512];
261longflags, ret=-1;
262unsigned long adler32;
263u_int32_t time, cachetime, kerneltime, exttime;
264
265if((gBootMode & kBootModeSafe) != 0)
266{
267verbose("Kernel Cache ignored.\n");
268return -1;
269}
270
271// Use specify kernel cache file if not empty
272if (cacheFile[0] != 0)
273{
274strlcpy(kernelCacheFile, cacheFile, sizeof(kernelCacheFile));
275verbose("Specified kernel cache file path: %s\n", cacheFile);
276}
277else
278{
279// Lion, Mountain Lion Mavericks and Yosemite prelink kernel cache file
280if (MacOSVerCurrent >= MacOSVer2Int("10.7")) // OSX is Lion (10.7) or newer
281{
282snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%skernelcache", kDefaultCachePathSnow);
283verbose("Kernel Cache file path (Mac OS X 10.7 and newer): %s\n", kernelCacheFile);
284}
285// Snow Leopard prelink kernel cache file
286else
287{
288if (MacOSVerCurrent >= MacOSVer2Int("10.6")) // OSX is Snow (10.6)
289{
290snprintf(kernelCacheFile, sizeof(kernelCacheFile), "kernelcache_%s",
291(archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64");
292
293intlnam = strlen(kernelCacheFile) + 9; //with adler32
294char*name;
295u_int32_t prev_time = 0;
296
297struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow);
298
299/* TODO: handle error? */
300if (cacheDir)
301{
302while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0)
303{
304if (((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time
305&& strstr(name, kernelCacheFile) && (name[lnam] != '.'))
306{
307snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%s%s", kDefaultCachePathSnow, name);
308prev_time = time;
309}
310}
311verbose("Kernel Cache file path (Mac OS X 10.6.X): %s\n", kernelCacheFile);
312}
313closedir(cacheDir);
314}
315else
316{
317// Reset cache name.
318bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
319snprintf(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64, "%s,%s", gRootDevice, bootInfo->bootFile);
320adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
321snprintf(kernelCacheFile, sizeof(kernelCacheFile), "%s.%08lX", kDefaultCachePathLeo, adler32);
322verbose("Reseted kernel cache file path: %s\n", kernelCacheFile);
323}
324}
325}
326
327// Check if the kernel cache file exists
328ret = -1;
329
330// If boot from a boot helper partition check the kernel cache file on it
331if (gBootVolume->flags & kBVFlagBooter)
332{
333snprintf(kernelCachePath, sizeof(kernelCachePath), "/com.apple.boot.P/%s", kernelCacheFile);
334ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
335
336if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat))
337{
338snprintf(kernelCachePath, sizeof(kernelCachePath), "/com.apple.boot.R/%s", kernelCacheFile);
339ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
340
341if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat))
342{
343snprintf(kernelCachePath, sizeof(kernelCachePath), "/com.apple.boot.S/%s", kernelCacheFile);
344ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
345
346if ((ret == -1) || ((flags & kFileTypeMask) != kFileTypeFlat))
347{
348snprintf(kernelCachePath, sizeof(kernelCachePath), "/com.apple.recovery.boot/kernelcache", kernelCacheFile);
349ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
350
351if ((flags & kFileTypeMask) != kFileTypeFlat)
352{
353ret = -1;
354}
355}
356}
357}
358}
359
360// If not found, use the original kernel cache path.
361if (ret == -1)
362{
363strlcpy(kernelCachePath, kernelCacheFile, sizeof(kernelCachePath));
364ret = GetFileInfo(NULL, kernelCachePath, &flags, &cachetime);
365
366if ((flags & kFileTypeMask) != kFileTypeFlat)
367{
368ret = -1;
369}
370}
371
372// Exit if kernel cache file wasn't found
373if (ret == -1)
374{
375verbose("No Kernel Cache File '%s' found\n", kernelCacheFile);
376return -1;
377}
378
379// Check if the kernel cache file is more recent (mtime)
380// than the kernel file or the S/L/E directory
381ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
382
383// Check if the kernel file is more recent than the cache file
384if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeFlat) && (kerneltime > cachetime))
385{
386verbose("Kernel file '%s' is more recent than Kernel Cache '%s'! Ignoring Kernel Cache.\n", bootInfo->bootFile, kernelCacheFile);
387return -1;
388}
389
390ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
391
392// Check if the S/L/E directory time is more recent than the cache file
393if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory) && (exttime > cachetime))
394{
395verbose("Folder '/System/Library/Extensions' is more recent than Kernel Cache file '%s'! Ignoring Kernel Cache.\n", kernelCacheFile);
396return -1;
397}
398
399// Since the kernel cache file exists and is the most recent try to load it
400verbose("Loading Kernel Cache from: '%s%s' (%s)\n", gBootVolume->label, gBootVolume->altlabel, gBootVolume->type_name);
401
402ret = LoadThinFatFile(kernelCachePath, binary);
403#if DEBUG
404 pause("\n[DEBUG] ");
405#endif
406
407return ret; // ret contain the length of the binary
408}
409
410//==========================================================================
411// This is the entrypoint from real-mode which functions exactly as it did
412// before. Multiboot does its own runtime initialization, does some of its
413// own things, and then calls common_boot.
414void boot(int biosdev)
415{
416initialize_runtime();
417// Enable A20 gate before accessing memory above 1Mb.
418enableA20();
419common_boot(biosdev);
420}
421
422//==========================================================================
423// The 'main' function for the booter. Called by boot0 when booting
424// from a block device, or by the network booter.
425//
426// arguments:
427// biosdev - Value passed from boot1/NBP to specify the device
428// that the booter was loaded from.
429//
430// If biosdev is kBIOSDevNetwork, then this function will return if
431// booting was unsuccessful. This allows the PXE firmware to try the
432// next boot device on its list.
433void common_boot(int biosdev)
434{
435bool quiet;
436bool firstRun = true;
437bool instantMenu;
438bool rescanPrompt;
439intstatus;
440unsigned intallowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot;
441unsigned intdenyBVFlags = kBVFlagEFISystem;
442
443// Set reminder to unload the PXE base code. Neglect to unload
444// the base code will result in a hang or kernel panic.
445gUnloadPXEOnExit = true;
446
447// Record the device that the booter was loaded from.
448gBIOSDev = biosdev & kBIOSDevMask;
449
450// Initialize boot-log
451initBooterLog();
452
453// Initialize boot info structure.
454initKernBootStruct();
455
456// Setup VGA text mode.
457// Not sure if it is safe to call setVideoMode() before the
458// config table has been loaded. Call video_mode() instead.
459#if DEBUG
460printf("before video_mode\n");
461#endif
462video_mode( 2 ); // 80x25 mono text mode.
463#if DEBUG
464printf("after video_mode\n");
465#endif
466
467// Scan and record the system's hardware information.
468scan_platform();
469
470// First get info for boot volume.
471scanBootVolumes(gBIOSDev, 0);
472bvChain = getBVChainForBIOSDev(gBIOSDev);
473setBootGlobals(bvChain);
474
475// Load boot.plist config file
476status = loadChameleonConfig(&bootInfo->chameleonConfig, bvChain);
477
478if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet)
479{
480gBootMode |= kBootModeQuiet;
481}
482
483// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
484if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu)
485{
486firstRun = false;
487}
488
489// Loading preboot ramdisk if exists.
490loadPrebootRAMDisk();
491
492// Disable rescan option by default
493gEnableCDROMRescan = false;
494
495// Enable it with Rescan=y in system config
496if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig)&& gEnableCDROMRescan)
497{
498gEnableCDROMRescan = true;
499}
500
501// Disable rescanPrompt option by default
502rescanPrompt = false;
503
504// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
505if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev))
506{
507gEnableCDROMRescan = promptForRescanOption();
508}
509
510// Disable ScanSingleDrive option by default
511gScanSingleDrive = false;
512
513// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
514if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig) && gScanSingleDrive)
515{
516gScanSingleDrive = true;
517}
518
519// Create a list of partitions on device(s).
520if (gScanSingleDrive)
521{
522scanBootVolumes(gBIOSDev, &bvCount);
523}
524else
525{
526scanDisks(gBIOSDev, &bvCount);
527}
528
529// Create a separated bvr chain using the specified filters.
530bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
531
532gBootVolume = selectBootVolume(bvChain);
533
534// Intialize module system
535init_module_system();
536
537#if DEBUG
538if (gBootVolume)
539{
540verbose("Default: %d, ->biosdev: %d, ->part_no: %d ->flags: 0x%08X\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
541}
542else
543{
544verbose("Boot Volume not selected yet.\n");
545}
546verbose("bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: 0x%08X\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
547pause("\n[DEBUG] ");
548#endif
549
550useGUI = true;
551// Override useGUI default
552getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig);
553if (useGUI && initGUI())
554{
555// initGUI() returned with an error, disabling GUI.
556useGUI = false;
557}
558
559setBootGlobals(bvChain);
560
561// Parse args, load and start kernel.
562while (1)
563{
564booltryresume, tryresumedefault, forceresume;
565booluseKernelCache = true; // by default try to use the prelinked kernel
566const char*val;
567intlen, ret = -1;
568longflags;
569u_int32_tsleeptime, time;
570void*binary = (void *)kLoadAddr;
571
572charbootFile[sizeof(bootInfo->bootFile)];
573charbootFilePath[512];
574charkernelCacheFile[512];
575
576// Initialize globals.
577sysConfigValid = false;
578gErrors = false;
579
580status = getBootOptions(firstRun);
581firstRun = false;
582if (status == -1) continue;
583
584status = processBootOptions();
585// Status == 1 means to chainboot
586if ( status ==1 ) break;
587// Status == -1 means that the config file couldn't be loaded or that gBootVolume is NULL
588if ( status == -1 )
589{
590// gBootVolume == NULL usually means the user hit escape.
591if (gBootVolume == NULL)
592{
593freeFilteredBVChain(bvChain);
594
595if (gEnableCDROMRescan)
596rescanBIOSDevice(gBIOSDev);
597
598bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
599setBootGlobals(bvChain);
600setupDeviceList(&bootInfo->themeConfig);
601}
602continue;
603}
604
605// Other status (e.g. 0) means that we should proceed with boot.
606
607// Turn off any GUI elements
608if ( bootArgs->Video.v_display == GRAPHICS_MODE )
609{
610gui.devicelist.draw = false;
611gui.bootprompt.draw = false;
612gui.menu.draw = false;
613gui.infobox.draw = false;
614gui.logo.draw = false;
615drawBackground();
616updateVRAM();
617}
618
619if (platformCPUFeature(CPU_FEATURE_EM64T))
620{
621archCpuType = CPU_TYPE_X86_64;
622}
623else
624{
625archCpuType = CPU_TYPE_I386;
626}
627
628if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig))
629{
630if (strncmp(val, "i386", 4) == 0)
631{
632archCpuType = CPU_TYPE_I386;
633}
634}
635
636if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) {
637if (strncmp(val, "i386", 4) == 0)
638{
639archCpuType = CPU_TYPE_I386;
640}
641}
642
643// Notify modules that we are attempting to boot
644execute_hook("PreBoot", NULL, NULL, NULL, NULL);
645
646if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig))
647{
648tryresume = true;
649tryresumedefault = true;
650}
651else
652{
653tryresumedefault = false;
654}
655
656if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) {
657forceresume = false;
658}
659
660if (forceresume)
661{
662tryresume = true;
663tryresumedefault = false;
664}
665
666while (tryresume)
667{
668const char *tmp;
669BVRef bvr;
670if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig))
671val = "/private/var/vm/sleepimage";
672
673// Do this first to be sure that root volume is mounted
674ret = GetFileInfo(0, val, &flags, &sleeptime);
675
676if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
677break;
678
679// Can't check if it was hibernation Wake=y is required
680if (bvr->modTime == 0 && tryresumedefault)
681break;
682
683if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
684break;
685
686if (!forceresume && ((sleeptime+3)<bvr->modTime))
687{
688#if DEBUG
689printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",
690bvr->modTime-sleeptime);
691#endif
692break;
693}
694
695HibernateBoot((char *)val);
696break;
697}
698
699getBoolForKey(kUseKernelCache, &useKernelCache, &bootInfo->chameleonConfig);
700if (useKernelCache)
701{
702do
703{
704// Determine the name of the Kernel Cache
705if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig))
706{
707if (val[0] == '\\')
708{
709len--;
710val++;
711}
712/* FIXME: check len vs sizeof(kernelCacheFile) */
713strlcpy(kernelCacheFile, val, len + 1);
714}
715else
716{
717kernelCacheFile[0] = 0; // Use default kernel cache file
718}
719
720if (gOverrideKernel && kernelCacheFile[0] == 0)
721{
722verbose("Using a non default kernel (%s) without specifying 'Kernel Cache' path, KernelCache will not be used\n", bootInfo->bootFile);
723useKernelCache = false;
724break;
725}
726
727if (gMKextName[0] != 0)
728{
729verbose("Using a specific MKext Cache (%s), KernelCache will not be used\n", gMKextName);
730useKernelCache = false;
731break;
732}
733
734if (gBootFileType != kBlockDeviceType)
735{
736useKernelCache = false;
737}
738
739} while(0);
740}
741else
742{
743verbose("Kernel Cache using disabled by user.");
744}
745
746do
747{
748if (useKernelCache)
749{
750ret = LoadKernelCache(kernelCacheFile, &binary);
751if (ret >= 0)
752{
753break;
754}
755}
756
757bool bootFileWithDevice = false;
758// Check if bootFile start with a device ex: bt(0,0)/Extra/mach_kernel
759if (strncmp(bootInfo->bootFile,"bt(",3) == 0 ||
760strncmp(bootInfo->bootFile,"hd(",3) == 0 ||
761strncmp(bootInfo->bootFile,"rd(",3) == 0)
762bootFileWithDevice = true;
763
764// bootFile must start with a / if it not start with a device name
765if (!bootFileWithDevice && (bootInfo->bootFile)[0] != '/')
766{
767if (MacOSVerCurrent >= MacOSVer2Int("10.10")) // OSX is 10.10 or newer
768{
769snprintf(bootFile, sizeof(bootFile), kDefaultKernelPathForYos "%s", bootInfo->bootFile); // Yosemite: '/System/Library/Kernels/'
770}
771else
772{
773snprintf(bootFile, sizeof(bootFile), kDefaultKernelPathPreYos "%s", bootInfo->bootFile); // append a leading '/'
774}
775}
776else
777{
778strlcpy(bootFile, bootInfo->bootFile, sizeof(bootFile));
779}
780
781// Try to load kernel image from alternate locations on boot helper partitions.
782ret = -1;
783if ((gBootVolume->flags & kBVFlagBooter) && !bootFileWithDevice)
784{
785snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.P%s", bootFile);
786ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
787if (ret == -1)
788{
789snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.R%s", bootFile);
790ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
791if (ret == -1)
792{
793snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.S%s", bootFile);
794ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
795}
796}
797}
798if (ret == -1)
799{
800// No alternate location found, using the original kernel image path.
801strlcpy(bootFilePath, bootFile, sizeof(bootFilePath));
802}
803
804verbose("Loading kernel from: '%s' (%s)\n", gBootVolume->label, gBootVolume->type_name);
805ret = LoadThinFatFile(bootFilePath, &binary);
806if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
807{
808archCpuType = CPU_TYPE_I386;
809ret = LoadThinFatFile(bootFilePath, &binary);
810}
811} while (0);
812
813clearActivityIndicator();
814
815#if DEBUG
816printf("Pausing...");
817sleep(8);
818#endif
819
820if (ret <= 0)
821{
822error("Can't find boot file: '%s'\n", bootFile);
823sleep(1);
824
825if (gBootFileType == kNetworkDeviceType)
826{
827// Return control back to PXE. Don't unload PXE base code.
828gUnloadPXEOnExit = false;
829break;
830}
831#if DEBUG
832pause("\n[DEBUG] ");
833#endif
834
835}
836else
837{
838/* Won't return if successful. */
839ret = ExecKernel(binary);
840}
841}
842
843// chainboot
844if (status == 1)
845{
846// if we are already in graphics-mode,
847if (getVideoMode() == GRAPHICS_MODE)
848{
849setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode.
850}
851}
852
853if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit)
854{
855nbpUnloadBaseCode();
856}
857}
858
859/*!
860Selects a new BIOS device, taking care to update the global state appropriately.
861 */
862/*
863static void selectBiosDevice(void)
864{
865struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
866CacheReset();
867diskFreeMap(oldMap);
868oldMap = NULL;
869
870int dev = selectAlternateBootDevice(gBIOSDev);
871
872BVRef bvchain = scanBootVolumes(dev, 0);
873BVRef bootVol = selectBootVolume(bvchain);
874gBootVolume = bootVol;
875setRootVolume(bootVol);
876gBIOSDev = dev;
877}
878*/
879
880bool checkOSVersion(const char * version)
881{
882if ( (sizeof(version) > 4) && ('.' != version[4]) && ('\0' != version[4]) )
883{
884return ((gMacOSVersion[0] == version[0]) && (gMacOSVersion[1] == version[1])
885&& (gMacOSVersion[2] == version[2]) && (gMacOSVersion[3] == version[3])
886&& (gMacOSVersion[4] == version[4]));
887}
888else
889{
890return ((gMacOSVersion[0] == version[0]) && (gMacOSVersion[1] == version[1])
891&& (gMacOSVersion[2] == version[2]) && (gMacOSVersion[3] == version[3]));
892}
893}
894
895// Bungo
896uint32_t getMacOSVerCurrent()
897{
898MacOSVerCurrent = MacOSVer2Int(gBootVolume->OSVersion);
899return MacOSVerCurrent;
900}
901
902#define BASE 65521L /* largest prime smaller than 65536 */
903#define NMAX 5000
904// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
905
906#define DO1(buf, i){s1 += buf[i]; s2 += s1;}
907#define DO2(buf, i)DO1(buf, i); DO1(buf, i + 1);
908#define DO4(buf, i)DO2(buf, i); DO2(buf, i + 2);
909#define DO8(buf, i)DO4(buf, i); DO4(buf, i + 4);
910#define DO16(buf)DO8(buf, 0); DO8(buf, 8);
911
912unsigned long Adler32(unsigned char *buf, long len)
913{
914unsigned long s1 = 1; // adler & 0xffff;
915unsigned long s2 = 0; // (adler >> 16) & 0xffff;
916unsigned long result;
917int k;
918
919while (len > 0) {
920k = len < NMAX ? len : NMAX;
921len -= k;
922while (k >= 16) {
923DO16(buf);
924buf += 16;
925k -= 16;
926}
927if (k != 0) do {
928s1 += *buf++;
929s2 += s1;
930} while (--k);
931s1 %= BASE;
932s2 %= BASE;
933}
934result = (s2 << 16) | s1;
935return OSSwapHostToBigInt32(result);
936}
937

Archive Download this file

Revision: 2841