Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 2733