Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 2592