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

Archive Download this file

Revision: 2811