Chameleon

Chameleon Svn Source Tree

Root/branches/cparm/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 * Mach Operating System
26 * Copyright (c) 1990 Carnegie-Mellon University
27 * Copyright (c) 1989 Carnegie-Mellon University
28 * All rights reserved. The CMU software License Agreement specifies
29 * the terms and conditions for use and redistribution.
30 */
31
32/*
33 * INTEL CORPORATION PROPRIETARY INFORMATION
34 *
35 * This software is supplied under the terms of a license agreement or
36 * nondisclosure agreement with Intel Corporation and may not be copied
37 * nor disclosed except in accordance with the terms of that agreement.
38 *
39 * Copyright 1988, 1989 by Intel Corporation
40 */
41
42/*
43 * Copyright 1993 NeXT Computer, Inc.
44 * All rights reserved.
45 */
46
47/*
48 * Completely reworked by Sam Streeper (sam_s@NeXT.com)
49 * Reworked again by Curtis Galloway (galloway@NeXT.com)
50 */
51
52
53#include "boot.h"
54#include "bootstruct.h"
55#include "fake_efi.h"
56#include "sl.h"
57#include "libsa.h"
58#include "platform.h"
59#include "graphics.h"
60#ifndef OPTION_ROM
61#include "appleboot.h"
62#endif
63#include "modules.h"
64#include "xml.h"
65#include "options.h"
66
67#ifndef DEBUG_BOOT
68#define DEBUG_BOOT 0
69#endif
70
71#if DEBUG_BOOT
72#define DBG(x...)printf(x)
73#else
74#define DBG(x...)
75#endif
76
77
78typedef struct platform_info {
79char platformName[PLATFORM_NAME_LEN];
80char rootPath[ROOT_PATH_LEN];
81} PlatformInfo;
82
83static char gBootKernelCacheFile[Cache_len_name];
84static char gMKextName[Cache_len_name];
85
86static BVRef bvChain;
87static bool forcecache = false;
88
89static void zeroBSS(void);
90#ifdef SAFE_MALLOC
91static inline void malloc_error(char *addr, size_t size, const char *file, int line);
92#else
93static inline void malloc_error(char *addr, size_t size);
94#endif
95static int ExecKernel(void *binary);
96static void getRootDevice();
97#ifdef NBP_SUPPORT
98static bool gUnloadPXEOnExit = false;
99#endif
100static bool find_file_with_ext(const char* dir, const char *ext, const char * name_compare, size_t ext_size);
101static bool found_extra_kext(void);
102static void determineCpuArch(void);
103static void init_pic(void);
104void getKernelCachePath(void);
105
106
107/*
108 * How long to wait (in seconds) to load the
109 * kernel after displaying the "boot:" prompt.
110 */
111#define kBootErrorTimeout 5
112
113/*
114 * Default path to kernel cache file
115 */
116#define kDefaultCachePath "/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache"
117
118//==========================================================================
119// Zero the BSS.
120
121static void zeroBSS(void)
122{
123extern char _DATA__bss__begin, _DATA__bss__end;
124extern char _DATA__common__begin, _DATA__common__end;
125
126bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
127bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
128}
129
130//==========================================================================
131// Malloc error function
132
133#ifdef SAFE_MALLOC
134static inline void malloc_error(char *addr, size_t size, const char *file, int line)
135{
136 stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
137}
138#else
139static inline void malloc_error(char *addr, size_t size)
140{
141 printf("\nMemory allocation error (0x%x, 0x%x)\n", (unsigned)addr, (unsigned)size);
142 asm volatile ("hlt");
143}
144#endif
145
146#if 0
147static inline void exception_error(char *msg, int nb)
148{
149 printf("\r\nException number = %d\r\nmessage = %s\r\n\r\n", nb, msg);
150 asm volatile ("hlt");
151}
152#endif
153
154BVRef getBvChain(void)
155{
156return bvChain;
157}
158
159
160//==========================================================================
161//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
162//
163void initialize_runtime(void)
164{
165zeroBSS();
166malloc_init(0, 0, 0, malloc_error);
167#if 0
168exception_init(exception_error);
169#endif
170}
171
172static void init_pic(void)
173{
174 /* Remap IRQ's */
175 outb(0x20, 0x11);
176 outb(0xA0, 0x11);
177 outb(0x21, 0x20);
178 outb(0xA1, 0x28);
179 outb(0x21, 0x04);
180 outb(0xA1, 0x02);
181 outb(0x21, 0x01);
182 outb(0xA1, 0x01);
183
184outb(0x70, inb(0x70)|0x80); /* Disable NMI */
185
186outb(0x21, 0xff); /* Maskout all interrupts Pic1 */
187outb(0xa1, 0xff); /* Maskout all interrupts Pic2 */
188}
189
190//==========================================================================
191// execKernel - Load the kernel image (mach-o) and jump to its entry point.
192
193static int ExecKernel(void *binary)
194{
195 entry_t kernelEntry;
196 int ret;
197
198 bootArgs->kaddr = bootArgs->ksize = 0;
199
200if(gBootVolume->OSVersion[3] <= '6')
201{
202bootArgs->Header.Version = kBootArgsVersion1;
203bootArgs->Header.Revision = gBootVolume->OSVersion[3];
204}
205else
206{
207#if kBootArgsVersion > 1
208
209bootArgs->Header.Version = kBootArgsVersion;
210bootArgs->Header.Revision = kBootArgsRevision;
211#else
212if(gBootVolume->OSVersion[3] >= '7')
213{
214bootArgs->Header.Version = 2;
215bootArgs->Header.Revision = 0;
216}
217#endif
218}
219
220execute_hook("ExecKernel", (void*)binary, NULL, NULL, NULL, NULL, NULL);
221
222 ret = DecodeKernel(binary,
223 &kernelEntry,
224 (char **) &bootArgs->kaddr,
225 (int *)&bootArgs->ksize );
226
227 if ( ret != 0 )
228 return ret;
229
230 // Load boot drivers from the specifed root path.
231
232 if (!gHaveKernelCache)
233{
234LoadDrivers("/");
235 }
236
237 if (gErrors)
238{
239 printf("Errors encountered while starting up the computer.\n");
240#if DEBUG_BOOT
241 printf("Pausing %d seconds...\n", kBootErrorTimeout);
242 sleep(kBootErrorTimeout);
243#endif
244 }
245
246execute_hook("md0Ramdisk", NULL, NULL, NULL, NULL, NULL, NULL);
247
248 setupFakeEfi();
249
250 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
251#ifdef NBP_SUPPORT
252 // Cleanup the PXE base code.
253
254 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit )
255{
256if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
257 {
258 printf("nbpUnloadBaseCode error %d\n", (int) ret);
259 sleep(2);
260 }
261 }
262#endif
263{
264bool wait = false;
265const char *strval = 0;
266int dummysize /*= 0*/;
267
268getBoolForKey(kWaitForKeypressKey, &wait, DEFAULT_BOOT_CONFIG);
269
270if (getValueForBootKey(bootArgs->CommandLine, "-wait", &strval, &dummysize))
271{
272wait = true;
273
274if (strval && ((strcmp(strval, "no") == 0) || (strcmp(strval, "No") == 0)))
275{
276wait = false;
277}
278}
279
280if (wait == true)
281{
282pause();
283}
284}
285
286 //debug_platform_env();
287
288if ((execute_hook("GUI_ExecKernel", NULL, NULL, NULL, NULL, NULL, NULL) != EFI_SUCCESS)) // (bootArgs->Video.v_display == VGA_TEXT_MODE)
289{
290#if UNUSED
291__setVideoMode( GRAPHICS_MODE, 0 );
292#else
293__setVideoMode( GRAPHICS_MODE );
294#endif
295
296#ifndef OPTION_ROM
297
298if(!gVerboseMode)
299{
300__drawColorRectangle(0, 0, DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, 0x01);
301
302uint8_t *appleBootPict;
303uint16_t bootImageWidth = kAppleBootWidth;
304uint16_t bootImageHeight = kAppleBootHeight;
305uint8_t *bootImageData = NULL;
306uint16_t x, y;
307
308unsigned long screen_params[4] = {DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, 32, 0};// here we store the used screen resolution
309// Prepare the data for the default Apple boot image.
310appleBootPict = (uint8_t *) __decodeRLE(gAppleBootPictRLE, kAppleBootRLEBlocks, bootImageWidth * bootImageHeight);
311if (appleBootPict)
312{
313__convertImage(bootImageWidth, bootImageHeight, appleBootPict, &bootImageData);
314if (bootImageData)
315{
316x = (screen_params[0] - MIN(kAppleBootWidth, screen_params[0])) / 2;
317y = (screen_params[1] - MIN(kAppleBootHeight, screen_params[1])) / 2;
318__drawDataRectangle(x, y, kAppleBootWidth, kAppleBootHeight, bootImageData);
319free(bootImageData);
320}
321free(appleBootPict);
322}
323
324}
325#endif
326}
327
328 finalizeEFIConfigTable();
329
330setupBooterLog();
331
332 finalizeBootStruct();
333
334execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL, NULL, NULL);// Notify modules that the kernel is about to be started
335
336 switch (gBootVolume->OSVersion[3]) {
337case '4':
338case '5':
339case '6':
340reserveKernLegacyBootStruct();
341break;
342case '7':
343reserveKern107BootStruct();
344break;
345case '8':
346reserveKern108BootStruct();
347break;
348default:
349break;
350}
351
352#if UNUSED
353turnOffFloppy();
354#endif
355#if BETA
356#include "smp-imps.h"
357#include "apic.h"
358IMPS_LAPIC_WRITE(LAPIC_LVT1, LAPIC_ICR_DM_NMI);
359#endif
360
361switch (gBootVolume->OSVersion[3]) {
362case '4':
363case '5':
364case '6':
365// Jump to kernel's entry point. There's no going back now. XXX LEGACY OS XXX
366startprog( kernelEntry, bootArgsLegacy );
367break;
368case '7':
369init_pic();
370// Jump to kernel's entry point. There's no going back now. XXX LION XXX
371startprog( kernelEntry, bootArgs107 );
372break;
373case '8':
374init_pic();
375// Jump to kernel's entry point. There's no going back now. XXX MOUNTAIN LION XXX
376startprog( kernelEntry, bootArgs108 );
377break;
378default:
379printf("Error: Unsupported Darwin version\n");
380getc();
381break;
382}
383
384 // Should not be reached
385
386 return 0;
387}
388
389//==========================================================================
390// This is the entrypoint from real-mode which functions exactly as it did
391// before. Multiboot does its own runtime initialization, does some of its
392// own things, and then calls common_boot.
393void boot(int biosdev)
394{
395initialize_runtime();
396// Enable A20 gate before accessing memory above 1Mb.
397enableA20();
398common_boot(biosdev);
399}
400
401//==========================================================================
402// The 'main' function for the booter. Called by boot0 when booting
403// from a block device, or by the network booter.
404//
405// arguments:
406// biosdev - Value passed from boot1/NBP to specify the device
407// that the booter was loaded from.
408//
409// If biosdev is kBIOSDevNetwork, then this function will return if
410// booting was unsuccessful. This allows the PXE firmware to try the
411// next boot device on its list.
412void common_boot(int biosdev)
413{
414 int status;
415 bool firstRun = true;
416 int devcnt = 0;
417 int bvCount = 0;
418int BIOSDev = 0;
419 long gBootMode = kBootModeNormal; /* defaults to 0 == kBootModeNormal */
420
421 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
422 unsigned int denyBVFlags = kBVFlagEFISystem;
423
424#ifdef NBP_SUPPORT
425 // Set reminder to unload the PXE base code. Neglect to unload
426 // the base code will result in a hang or kernel panic.
427 gUnloadPXEOnExit = true;
428#endif
429
430 // Setup VGA text mode.
431 // It's unsafe to call setVideoMode() before the
432 // bootargs is initialized, we call video_mode() instead.
433#if DEBUG
434 printf("before video_mode\n");
435#endif
436 video_mode( 2 ); // 80x25 mono text mode.
437#if DEBUG
438 printf("after video_mode\n");
439#endif
440printf("Starting Chameleon ...\n");
441
442init_ut_fnc();
443
444 arc4_init();
445
446initBooterLog();
447
448// Initialize boot info structure.
449 initKernBootStruct();
450
451
452 // Scan and record the system's hardware information.
453 scan_platform();
454
455 set_env(envgBIOSDev, (BIOSDev = biosdev & kBIOSDevMask));
456 set_env(envShouldboot, false);
457 set_env(envkCache, (uint32_t)gBootKernelCacheFile);
458 set_env(envMKextName, (uint32_t)gMKextName);
459
460 InitBootPrompt();
461
462 // First get info for boot volume.
463 scanBootVolumes(BIOSDev, 0);
464 bvChain = getBVChainForBIOSDev(BIOSDev);
465 setBootGlobals(bvChain);
466
467 // Load Booter boot.plist config file
468 status = loadBooterConfig();
469
470 {
471 bool isServer = false;
472 getBoolForKey(kIsServer, &isServer, DEFAULT_BOOT_CONFIG); // set this as soon as possible
473 set_env(envIsServer , isServer);
474 }
475
476
477{
478bool quiet = false;
479if (getBoolForKey(kQuietBootKey, &quiet, DEFAULT_BOOT_CONFIG) && quiet)
480{
481 long gBootMode = kBootModeNormal;
482gBootMode |= kBootModeQuiet;
483}
484}
485
486 set_env(envgBootMode, gBootMode);
487
488{
489bool instantMenu = false;
490// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
491if (getBoolForKey(kInsantMenuKey, &instantMenu, DEFAULT_BOOT_CONFIG) && instantMenu)
492{
493firstRun = false;
494}
495}
496
497 {
498#ifndef OPTION_ROM
499 bool ScanSingleDrive = false;
500 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
501 if (getBoolForKey(kScanSingleDriveKey, &ScanSingleDrive, DEFAULT_BOOT_CONFIG) && ScanSingleDrive)
502 {
503 ScanSingleDrive = true;
504 }
505 safe_set_env(envgScanSingleDrive, ScanSingleDrive);
506 // Create a list of partitions on device(s).
507 if (ScanSingleDrive)
508 {
509 scanBootVolumes(BIOSDev, &bvCount);
510 }
511 else
512#endif
513 {
514#if UNUSED
515 scanDisks(BIOSDev, &bvCount);
516#else
517 scanDisks();
518#endif
519 }
520
521}
522
523 // Create a separated bvr chain using the specified filters.
524 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &devcnt);
525 safe_set_env(envgDeviceCount,devcnt);
526
527
528gBootVolume = selectBootVolume(bvChain);
529
530{
531// Intialize module system
532EFI_STATUS sysinit = init_module_system();
533if((sysinit == EFI_SUCCESS) || (sysinit == EFI_ALREADY_STARTED) /*should never happen*/ )
534{
535load_all_modules();
536}
537}
538
539 load_all_internal_modules();
540
541 // Loading preboot ramdisk if exists.
542execute_hook("loadPrebootRAMDisk", NULL, NULL, NULL, NULL, NULL, NULL);
543
544#ifndef OPTION_ROM
545
546
547
548 {
549 // Disable rescan option by default
550 bool CDROMRescan = false;
551
552 // Enable it with Rescan=y in system config
553 if (getBoolForKey(kRescanKey, &CDROMRescan, DEFAULT_BOOT_CONFIG) && CDROMRescan)
554 {
555 CDROMRescan = true;
556
557 }
558 safe_set_env(envgEnableCDROMRescan, CDROMRescan);
559
560 }
561
562
563{
564bool rescanPrompt = false;
565// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
566if (getBoolForKey(kRescanPromptKey, &rescanPrompt , DEFAULT_BOOT_CONFIG) && rescanPrompt && biosDevIsCDROM((int)get_env(envgBIOSDev)))
567{
568 safe_set_env(envgEnableCDROMRescan, promptForRescanOption());
569}
570}
571
572#endif
573
574#if DEBUG
575 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
576 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
577 getc();
578#endif
579
580 setBootGlobals(bvChain);
581
582// Display the GUI
583execute_hook("GUI_Display", NULL, NULL, NULL, NULL, NULL, NULL);
584
585 // Parse args, load and start kernel.
586 while (1) {
587 const char *val;
588 int len;
589char *bootFile;
590bool trycache = true; // Always try to catch the kernelcache first
591
592 long flags;
593#ifdef BOOT_HELPER_SUPPORT
594long time;
595#endif
596 int ret = -1;
597 void *binary = (void *)kLoadAddr;
598
599 // additional variable for testing alternate kernel image locations on boot helper partitions.
600 char bootFileSpec[512];
601
602 // Initialize globals.
603 safe_set_env(envSysConfigValid, false);
604 gErrors = false;
605
606 status = getBootOptions(firstRun);
607 firstRun = false;
608 if (status == -1) continue;
609
610 status = processBootOptions();
611 // Status==1 means to chainboot
612 if ( status == 1 ) break;
613 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
614 if ( status == -1 )
615 {
616// gBootVolume == NULL usually means the user hit escape.
617if(gBootVolume == NULL)
618{
619freeFilteredBVChain(bvChain);
620#ifndef OPTION_ROM
621if (get_env(envgEnableCDROMRescan))
622rescanBIOSDevice((int)get_env(envgBIOSDev));
623#endif
624
625bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &devcnt);
626 safe_set_env(envgDeviceCount,devcnt);
627
628setBootGlobals(bvChain);
629}
630continue;
631 }
632
633 // Other status (e.g. 0) means that we should proceed with boot.
634execute_hook("GUI_PreBoot", NULL, NULL, NULL, NULL, NULL, NULL);
635
636if (getValueForKey(karch, &val, &len, DEFAULT_BOOT_CONFIG) && val)
637{
638if (strncmp(val, "x86_64", 4) == 0)
639{
640archCpuType = CPU_TYPE_X86_64;
641}
642else if (strncmp(val, "i386", 4) == 0)
643{
644archCpuType = CPU_TYPE_I386;
645}
646else
647{
648DBG("Incorrect parameter for option 'arch =' , please use x86_64 or i386\n");
649determineCpuArch();
650}
651
652}
653else determineCpuArch();
654
655
656getRootDevice();
657
658// Notify to all modules that we are attempting to boot
659execute_hook("PreBoot", NULL, NULL, NULL, NULL, NULL, NULL);
660
661if (execute_hook("getProductNamePatched", NULL, NULL, NULL, NULL, NULL, NULL) != EFI_SUCCESS)
662readSMBIOS(thePlatformName); // read smbios Platform Name
663
664
665if (((get_env(envgBootMode) & kBootModeSafe) == 0) &&
666!get_env(envgOverrideKernel) &&
667(gBootFileType == kBlockDeviceType) &&
668(gMKextName[0] == '\0') &&
669!getValueForBootKey(bootArgs->CommandLine, kIgnorePrelinkKern, &val, &len))
670{
671getBoolForKey(kUseKernelCache, &trycache, DEFAULT_BOOT_CONFIG);
672if (trycache == true)
673{
674// try to find the cache and fill the gBootKernelCacheFile string
675getKernelCachePath();
676
677// Check for cache file
678trycache = (gBootKernelCacheFile[0] != '\0') ? true : false; // if gBootKernelCacheFile is filled et bla bla bla.... :-)
679}
680
681}
682else
683{
684trycache = false;
685}
686
687verbose("Loading Darwin %s\n", gBootVolume->OSVersion);
688{
689long cachetime, kerneltime, exttime;
690if (trycache && !forcecache) do {
691
692 if (strcmp(bootInfo->bootFile, kDefaultKernel) != 0) {
693 // if we haven't found the kernel yet, don't use the cache
694 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
695 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
696 {
697 trycache = 0;
698 bootInfo->adler32 = 0;
699 DBG("No kernel found, kernelcache disabled !!!\n");
700 break;
701 }
702 }
703 else if (gBootVolume->kernelfound != true) // Should never happen.
704 {
705 bootFile = kDefaultKernel;
706 goto out;
707 }
708
709ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
710if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
711|| (cachetime < kerneltime))
712{
713trycache = 0;
714bootInfo->adler32 = 0;
715DBG("Warning: No kernelcache found or kernelcache too old (timestamp of the kernel > timestamp of the cache), kernelcache disabled !!!\n");
716
717break;
718}
719ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
720if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
721&& (cachetime < exttime))
722{
723trycache = 0;
724bootInfo->adler32 = 0;
725DBG("Warning: kernelcache too old, timestamp of S/L/E > timestamp of the cache, kernelcache disabled !!! \n");
726
727break;
728}
729if (kerneltime > exttime)
730{
731exttime = kerneltime;
732}
733if (cachetime != (exttime + 1))
734{
735trycache = 0;
736bootInfo->adler32 = 0;
737DBG("Warning: invalid timestamp, kernelcache disabled !!!\n");
738
739break;
740}
741} while (0);
742}
743
744 do {
745 if (trycache)
746{
747 bootFile = gBootKernelCacheFile;
748 verbose("Loading kernel cache %s\n", bootFile);
749if (gBootVolume->OSVersion[3] > '6')
750{
751ret = LoadThinFatFile(bootFile, &binary);
752if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
753{
754archCpuType = CPU_TYPE_I386;
755ret = LoadThinFatFile(bootFile, &binary);
756}
757}
758else
759{
760ret = LoadFile(bootFile);
761binary = (void *)kLoadAddr;
762}
763
764 if (ret >= 0)
765{
766 break;
767 }
768
769 }
770bootInfo->adler32 = 0;
771 bootFile = bootInfo->bootFile;
772#ifdef BOOT_HELPER_SUPPORT
773
774 // Try to load kernel image from alternate locations on boot helper partitions.
775 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
776 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
777 if (ret == -1)
778 {
779sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
780ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
781if (ret == -1)
782{
783sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
784ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
785if (ret == -1)
786{
787// Not found any alternate locations, using the original kernel image path.
788strlcpy(bootFileSpec, bootFile,sizeof(bootFileSpec));
789}
790}
791 }
792#else
793strlcpy(bootFileSpec, bootFile,sizeof(bootFileSpec));
794#endif
795
796 verbose("Loading kernel %s\n", bootFileSpec);
797 ret = LoadThinFatFile(bootFileSpec, &binary);
798 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
799 {
800archCpuType = CPU_TYPE_I386;
801ret = LoadThinFatFile(bootFileSpec, &binary);
802 }
803
804 } while (0);
805
806#if DEBUG
807 printf("Pausing...");
808 sleep(8);
809#endif
810
811 if (ret <= 0)
812{
813out:
814printf("Can't find %s\n", bootFile);
815
816sleep(1);
817#ifdef NBP_SUPPORT
818 if (gBootFileType == kNetworkDeviceType)
819{
820 // Return control back to PXE. Don't unload PXE base code.
821 gUnloadPXEOnExit = false;
822 break;
823 }
824#endif
825 }
826else
827{
828 /* Won't return if successful. */
829 if ( ExecKernel(binary))
830 {
831 firstRun = true;
832 continue;
833 }
834 }
835 }
836
837 // chainboot
838 if (status==1)
839{
840if (__getVideoMode() == GRAPHICS_MODE)
841{// if we are already in graphics-mode,
842#if UNUSED
843__setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
844#else
845__setVideoMode(VGA_TEXT_MODE);// switch back to text mode
846#endif
847}
848 }
849#ifdef NBP_SUPPORT
850 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit)
851{
852nbpUnloadBaseCode();
853 }
854#endif
855}
856
857static void determineCpuArch(void)
858{
859if (cpu_mode_is64bit())
860{
861archCpuType = CPU_TYPE_X86_64;
862}
863else
864{
865archCpuType = CPU_TYPE_I386;
866}
867}
868
869void getKernelCachePath(void)
870{
871{
872// If there is an extra kext/mkext, we return immediatly and we skip the kernelCache
873// since kexts/mkexts are not loaded properly when the kernelCache is used.
874// Another method would be to re-build the kernelCache one the fly
875if (found_extra_kext() == true) return;
876}
877
878{
879const char *val;
880int len;
881
882if (getValueForKey(kKernelCacheKey, &val, &len, DEFAULT_BOOT_CONFIG))
883{
884 char * buffer = newString(val);
885
886if (val[0] == '\\')
887{
888// Flip the back slash's to slash's .
889 len = 0;
890 while (buffer[len] != '\0') {
891 if (buffer[len] == '\\')
892 {
893 buffer[len] = '/';
894 }
895 len++;
896 }
897}
898strlcpy(gBootKernelCacheFile, buffer, sizeof(gBootKernelCacheFile));
899 forcecache = true;
900}
901else
902{
903if(gBootVolume->OSVersion[3] > '6')
904{
905sprintf(gBootKernelCacheFile, "%s", kDefaultCachePath);
906}
907else if(gBootVolume->OSVersion[3] <= '6')
908{
909
910PlatformInfo *platformInfo = malloc(sizeof(PlatformInfo));
911if (platformInfo)
912{
913
914bzero(platformInfo, sizeof(PlatformInfo));
915
916if (GetgPlatformName())
917strlcpy(platformInfo->platformName,GetgPlatformName(), sizeof(platformInfo->platformName)+1);
918
919if (GetgRootDevice())
920{
921char *rootPath_p = platformInfo->rootPath;
922len = strlen(GetgRootDevice()) + 1;
923if ((unsigned)len > sizeof(platformInfo->rootPath))
924{
925len = sizeof(platformInfo->rootPath);
926}
927memcpy(rootPath_p, GetgRootDevice(),len);
928
929rootPath_p += len;
930
931len = strlen(bootInfo->bootFile);
932
933if ((unsigned)(rootPath_p - platformInfo->rootPath + len) >=
934sizeof(platformInfo->rootPath))
935{
936
937len = sizeof(platformInfo->rootPath) -
938(rootPath_p - platformInfo->rootPath);
939}
940memcpy(rootPath_p, bootInfo->bootFile, len);
941
942}
943
944if (!platformInfo->platformName[0] || !platformInfo->rootPath[0])
945{
946platformInfo->platformName[0] = platformInfo->rootPath[0] = 0;
947}
948#ifdef rootpath
949 SetgRootPath(platformInfo->rootPath);
950#endif
951
952bootInfo->adler32 = OSSwapHostToBigInt32(adler32((unsigned char *)platformInfo, sizeof(*platformInfo)));
953
954free(platformInfo);
955}
956
957DBG("Adler32: %08lX\n",bootInfo->adler32);
958
959if (gBootVolume->OSVersion[3] < '6')
960{
961long flags, cachetime;
962int ret = -1;
963sprintf(gBootKernelCacheFile, "%s.%08lX", "/System/Library/Caches/com.apple.kernelcaches/kernelcache",bootInfo->adler32);
964ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
965if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
966{
967bootInfo->adler32 = 0;
968sprintf(gBootKernelCacheFile, "%s", "/System/Library/Caches/com.apple.kernelcaches/kernelcache");
969}
970
971} else
972sprintf(gBootKernelCacheFile, "%s_%s.%08lX", kDefaultCachePath, (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64", bootInfo->adler32); //Snow Leopard
973
974}
975}
976}
977}
978
979static void getRootDevice()
980{
981// Maximum config table value size
982#define VALUE_SIZE 2048
983bool uuidSet = false;
984const char *val = 0;
985 int cnt = 0;
986
987if (getValueForKey(kBootUUIDKey, &val, &cnt, DEFAULT_BOOT_CONFIG))
988{
989uuidSet = true;
990}
991else
992{
993if (getValueForBootKey(bootArgs->CommandLine, kRootDeviceKey, &val, &cnt))
994{
995if (*val == '*' && *(val + 1) != '/' && *(val + 1) != 'u')
996{
997val += 1; //skip the *
998uuidSet = true;
999
1000}
1001else if (*val == '*' && *(val + 1) == 'u')
1002{
1003
1004if ( getValueForKey( kBootDeviceKey, &val, &cnt, DEFAULT_BOOT_CONFIG))
1005uuidSet = true;
1006
1007}
1008}
1009else
1010{
1011#ifdef BOOT_HELPER_SUPPORT
1012//
1013// Try an alternate method for getting the root UUID on boot helper partitions.
1014//
1015if (gBootVolume->flags & kBVFlagBooter)
1016{
1017if((loadHelperConfig() == 0)
1018 && getValueForKey(kHelperRootUUIDKey, &val, &cnt, &bootInfo->helperConfig) )
1019{
1020getValueForKey(kHelperRootUUIDKey, &val, &cnt, &bootInfo->helperConfig);
1021uuidSet = true;
1022goto out;
1023}
1024}
1025#endif
1026if ( getValueForKey( kBootDeviceKey, &val, &cnt, DEFAULT_BOOT_CONFIG))
1027{
1028int ArgCntRemaining = (int)get_env(envArgCntRemaining);
1029uuidSet = false;
1030char * valueBuffer;
1031valueBuffer = malloc(VALUE_SIZE);
1032char * argP = bootArgs->CommandLine;
1033valueBuffer[0] = '*';
1034if (cnt > VALUE_SIZE)
1035{
1036cnt = VALUE_SIZE;
1037}
1038strlcpy(valueBuffer + 1, val, cnt+1);
1039if (!copyArgument( kRootDeviceKey, valueBuffer, cnt, &argP, &ArgCntRemaining))
1040{
1041free(valueBuffer);
1042printf("Error: boot arguments too long, unable to set root device !!");
1043getc();
1044return;
1045}
1046 safe_set_env(envArgCntRemaining,ArgCntRemaining);
1047free(valueBuffer);
1048goto out;
1049}
1050
1051if (gBootVolume->fs_getuuid && gBootVolume->fs_getuuid (gBootVolume, bootInfo->uuidStr) == 0)
1052{
1053verbose("Setting boot-uuid to: %s\n", bootInfo->uuidStr);
1054uuidSet = true;
1055SetgRootDevice(bootInfo->uuidStr);
1056return;
1057}
1058
1059}
1060}
1061
1062out:
1063verbose("Setting %s to: %s\n", uuidSet ? kBootUUIDKey : "root device", (char* )val);
1064 SetgRootDevice(val);
1065}
1066
1067static bool find_file_with_ext(const char* dir, const char *ext, const char * name_compare, size_t ext_size)
1068{
1069char* name;
1070long flags;
1071long time;
1072struct dirstuff* moduleDir = opendir(dir);
1073while(readdir(moduleDir, (const char**)&name, &flags, &time) >= 0)
1074{
1075int len = strlen(name);
1076
1077if (len >= ext_size)
1078{
1079if(strcmp(&name[len - ext_size], ext) == 0)
1080{
1081if (name_compare)
1082{
1083if (strcmp(name, name_compare) == 0)
1084{
1085DBG("found : %s\n", name);
1086closedir(moduleDir);
1087return true;
1088}
1089}
1090else
1091{
1092DBG("found : %s\n", name);
1093closedir(moduleDir);
1094return true;
1095}
1096}
1097#if DEBUG_BOOT
1098else
1099{
1100DBG("Ignoring %s\n", name);
1101}
1102#endif
1103}
1104#if DEBUG_BOOT
1105else
1106{
1107DBG("Ignoring %s\n", name);
1108}
1109#endif
1110}
1111
1112if (moduleDir) {
1113closedir(moduleDir);
1114
1115}
1116return false;
1117}
1118
1119// If a kext is found in /Extra/Extentions return true
1120// If a mkext is found in /Extra return true
1121// Otherwise return false
1122// Tips (if you still want to use extra kext(s)/mkext(s) ):
1123// With Lion and earlier, the default boot cache is a kernelcache, no mkext is created anymore by kextd automaticaly (kextd still update the existing mkexts),
1124// so it's recommended to create a system mkext by yourself to decrease boot time (see the kextcache commandline)
1125static bool found_extra_kext(void)
1126{
1127#define EXTENSIONS "Extensions"
1128#define MKEXT_EXT ".mkext"
1129#define MKEXT_EXT_SIZE sizeof("mkext")
1130#define KEXT_EXT ".kext"
1131#define KEXT_EXT_SIZE sizeof("kext")
1132
1133long flags;
1134long exttime;
1135int ret = -1;
1136
1137ret = GetFileInfo("rd(0,0)/Extra/", EXTENSIONS, &flags, &exttime);
1138if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeFlat))
1139{
1140if (((flags & kFileTypeMask) == kFileTypeFlat))
1141{
1142if (find_file_with_ext("rd(0,0)/Extra/", MKEXT_EXT, EXTENSIONS, MKEXT_EXT_SIZE))
1143{
1144return true;
1145}
1146}
1147else if (((flags & kFileTypeMask) == kFileTypeDirectory))
1148{
1149if (find_file_with_ext("rd(0,0)/Extra/Extensions/", KEXT_EXT, NULL, KEXT_EXT_SIZE))
1150{
1151return true;
1152}
1153}
1154}
1155ret = GetFileInfo("/Extra/", EXTENSIONS, &flags, &exttime);
1156if (ret == 0)
1157{
1158if (((flags & kFileTypeMask) == kFileTypeFlat))
1159{
1160if (find_file_with_ext("/Extra/", MKEXT_EXT, EXTENSIONS, MKEXT_EXT_SIZE))
1161{
1162return true;
1163}
1164}
1165else if (((flags & kFileTypeMask) == kFileTypeDirectory))
1166{
1167if (find_file_with_ext("/Extra/Extensions/", KEXT_EXT, NULL, KEXT_EXT_SIZE))
1168{
1169return true;
1170}
1171}
1172}
1173ret = GetFileInfo("bt(0,0)/Extra/", EXTENSIONS, &flags, &exttime);
1174if (ret == 0)
1175{
1176if (((flags & kFileTypeMask) == kFileTypeFlat))
1177{
1178if (find_file_with_ext("bt(0,0)/Extra/", MKEXT_EXT, EXTENSIONS, MKEXT_EXT_SIZE))
1179{
1180return true;
1181}
1182}
1183else if (((flags & kFileTypeMask) == kFileTypeDirectory))
1184{
1185if (find_file_with_ext("bt(0,0)/Extra/Extensions/", KEXT_EXT, NULL, KEXT_EXT_SIZE))
1186{
1187return true;
1188}
1189}
1190}
1191DBG("NO Extra Mkext/Kext found\n");
1192
1193// nothing found
1194return false;
1195}
1196
1197#if 0
1198static char *FIXED_BOOTFILE_PATH(char * str)
1199{
1200char bootfile[128];
1201
1202bool bootFileWithDevice = false;
1203// Check if bootFile start with a device ex: bt(0,0)/Extra/mach_kernel
1204if (strncmp(str,"bt(",3) == 0 ||
1205strncmp(str,"hd(",3) == 0 ||
1206strncmp(str,"rd(",3) == 0)
1207{
1208bootFileWithDevice = true;
1209}
1210
1211// bootFile must start with a / if it not start with a device name
1212if (!bootFileWithDevice && (str)[0] != '/')
1213sprintf(bootFile, "/%s", str); // append a leading /
1214else
1215strlcpy(bootFile, bootInfo->bootFile, sizeof(bootInfo->bootFile));
1216
1217return bootfile;
1218}
1219#endif
1220

Archive Download this file

Revision: 1887