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

Archive Download this file

Revision: 2602