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

Archive Download this file

Revision: 2834