Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 2869