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

Archive Download this file

Revision: 2847