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 // Scan and record the system's hardware information.
452 scan_platform();
453
454 set_env(envgBIOSDev, (BIOSDev = biosdev & kBIOSDevMask));
455 set_env(envShouldboot, false);
456 set_env(envkCache, (uint32_t)gBootKernelCacheFile);
457 set_env(envMKextName, (uint32_t)gMKextName);
458
459 InitBootPrompt();
460
461
462 // First get info for boot volume.
463 scanBootVolumes(BIOSDev, 0);
464
465 bvChain = getBVChainForBIOSDev(BIOSDev);
466
467 setBootGlobals(bvChain);
468
469 // Load Booter boot.plist config file
470 /*status =*/ loadBooterConfig();
471
472 {
473 bool isServer = false;
474 getBoolForKey(kIsServer, &isServer, DEFAULT_BOOT_CONFIG); // set this as soon as possible
475 set_env(envIsServer , isServer);
476 }
477
478
479{
480bool quiet = false;
481if (getBoolForKey(kQuietBootKey, &quiet, DEFAULT_BOOT_CONFIG) && quiet)
482{
483gBootMode |= kBootModeQuiet;
484}
485}
486
487 set_env(envgBootMode, gBootMode);
488
489{
490bool instantMenu = false;
491// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
492if (getBoolForKey(kInsantMenuKey, &instantMenu, DEFAULT_BOOT_CONFIG) && instantMenu)
493{
494firstRun = false;
495}
496}
497
498 {
499#ifndef OPTION_ROM
500 bool ScanSingleDrive = false;
501 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
502 if (getBoolForKey(kScanSingleDriveKey, &ScanSingleDrive, DEFAULT_BOOT_CONFIG) && ScanSingleDrive)
503 {
504 ScanSingleDrive = true;
505 }
506 safe_set_env(envgScanSingleDrive, ScanSingleDrive);
507 // Create a list of partitions on device(s).
508 if (ScanSingleDrive)
509 {
510 scanBootVolumes(BIOSDev, &bvCount);
511 }
512 else
513#endif
514 {
515#if UNUSED
516 scanDisks(BIOSDev, &bvCount);
517#else
518 scanDisks();
519#endif
520 }
521
522}
523
524 // Create a separated bvr chain using the specified filters.
525 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &devcnt);
526 safe_set_env(envgDeviceCount,devcnt);
527
528
529gBootVolume = selectBootVolume(bvChain);
530
531{
532// Intialize module system
533EFI_STATUS sysinit = init_module_system();
534if((sysinit == EFI_SUCCESS) || (sysinit == EFI_ALREADY_STARTED) /*should never happen*/ )
535{
536load_all_modules();
537}
538}
539
540 load_all_internal_modules();
541
542 // Loading preboot ramdisk if exists.
543execute_hook("loadPrebootRAMDisk", NULL, NULL, NULL, NULL, NULL, NULL);
544
545#ifndef OPTION_ROM
546
547
548
549 {
550 // Disable rescan option by default
551 bool CDROMRescan = false;
552
553 // Enable it with Rescan=y in system config
554 if (getBoolForKey(kRescanKey, &CDROMRescan, DEFAULT_BOOT_CONFIG) && CDROMRescan)
555 {
556 CDROMRescan = true;
557
558 }
559 safe_set_env(envgEnableCDROMRescan, CDROMRescan);
560
561 }
562
563
564{
565bool rescanPrompt = false;
566// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
567if (getBoolForKey(kRescanPromptKey, &rescanPrompt , DEFAULT_BOOT_CONFIG) && rescanPrompt && biosDevIsCDROM((int)get_env(envgBIOSDev)))
568{
569 safe_set_env(envgEnableCDROMRescan, promptForRescanOption());
570}
571}
572
573#endif
574
575#if DEBUG
576 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
577 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
578 getc();
579#endif
580
581 setBootGlobals(bvChain);
582
583// Display the GUI
584execute_hook("GUI_Display", NULL, NULL, NULL, NULL, NULL, NULL);
585
586 // Parse args, load and start kernel.
587 while (1) {
588 const char *val;
589 int len;
590char *bootFile;
591bool trycache = true; // Always try to catch the kernelcache first
592
593 long flags;
594#ifdef BOOT_HELPER_SUPPORT
595long time;
596#endif
597 int ret = -1;
598 void *binary = (void *)kLoadAddr;
599
600 // additional variable for testing alternate kernel image locations on boot helper partitions.
601 char bootFileSpec[512];
602
603 // Initialize globals.
604 safe_set_env(envSysConfigValid, false);
605 gErrors = false;
606
607 status = getBootOptions(firstRun);
608 firstRun = false;
609 if (status == -1) continue;
610
611 status = processBootOptions();
612 // Status==1 means to chainboot
613 if ( status == 1 ) break;
614 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
615 if ( status == -1 )
616 {
617// gBootVolume == NULL usually means the user hit escape.
618if(gBootVolume == NULL)
619{
620freeFilteredBVChain(bvChain);
621#ifndef OPTION_ROM
622if (get_env(envgEnableCDROMRescan))
623rescanBIOSDevice((int)get_env(envgBIOSDev));
624#endif
625
626bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &devcnt);
627 safe_set_env(envgDeviceCount,devcnt);
628
629setBootGlobals(bvChain);
630}
631continue;
632 }
633
634 // Other status (e.g. 0) means that we should proceed with boot.
635execute_hook("GUI_PreBoot", NULL, NULL, NULL, NULL, NULL, NULL);
636
637if (getValueForKey(karch, &val, &len, DEFAULT_BOOT_CONFIG) && val)
638{
639if (strncmp(val, "x86_64", 4) == 0)
640{
641archCpuType = CPU_TYPE_X86_64;
642}
643else if (strncmp(val, "i386", 4) == 0)
644{
645archCpuType = CPU_TYPE_I386;
646}
647else
648{
649DBG("Incorrect parameter for option 'arch =' , please use x86_64 or i386\n");
650determineCpuArch();
651}
652
653}
654else determineCpuArch();
655
656
657getRootDevice();
658
659// Notify to all modules that we are attempting to boot
660execute_hook("PreBoot", NULL, NULL, NULL, NULL, NULL, NULL);
661
662if (execute_hook("getProductNamePatched", NULL, NULL, NULL, NULL, NULL, NULL) != EFI_SUCCESS)
663readSMBIOS(thePlatformName); // read smbios Platform Name
664
665
666if (((get_env(envgBootMode) & kBootModeSafe) == 0) &&
667!get_env(envgOverrideKernel) &&
668(gBootFileType == kBlockDeviceType) &&
669(gMKextName[0] == '\0') &&
670!getValueForBootKey(bootArgs->CommandLine, kIgnorePrelinkKern, &val, &len))
671{
672getBoolForKey(kUseKernelCache, &trycache, DEFAULT_BOOT_CONFIG);
673if (trycache == true)
674{
675// try to find the cache and fill the gBootKernelCacheFile string
676getKernelCachePath();
677
678// Check for cache file
679trycache = (gBootKernelCacheFile[0] != '\0') ? true : false; // if gBootKernelCacheFile is filled et bla bla bla.... :-)
680}
681
682}
683else
684{
685trycache = false;
686}
687
688verbose("Loading Darwin %s\n", gBootVolume->OSVersion);
689{
690long cachetime, kerneltime = 0, exttime;
691if (trycache && !forcecache) do {
692
693 if (strcmp(bootInfo->bootFile, kDefaultKernel) != 0) {
694 // if we haven't found the kernel yet, don't use the cache
695 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
696 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
697 {
698 trycache = 0;
699 safe_set_env(envAdler32, 0);
700 DBG("No kernel found, kernelcache disabled !!!\n");
701 break;
702 }
703 }
704 else if (gBootVolume->kernelfound != true) // Should never happen.
705 {
706 bootFile = kDefaultKernel;
707 goto out;
708 }
709
710ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
711if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
712|| (cachetime < kerneltime))
713{
714trycache = 0;
715safe_set_env(envAdler32, 0);
716DBG("Warning: No kernelcache found or kernelcache too old (timestamp of the kernel > timestamp of the cache), kernelcache disabled !!!\n");
717
718break;
719}
720ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
721if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
722&& (cachetime < exttime))
723{
724trycache = 0;
725safe_set_env(envAdler32, 0);
726DBG("Warning: kernelcache too old, timestamp of S/L/E > timestamp of the cache, kernelcache disabled !!! \n");
727
728break;
729}
730if (kerneltime > exttime)
731{
732exttime = kerneltime;
733}
734if (cachetime != (exttime + 1))
735{
736trycache = 0;
737safe_set_env(envAdler32, 0);
738DBG("Warning: invalid timestamp, kernelcache disabled !!!\n");
739
740break;
741}
742} while (0);
743}
744
745 do {
746 if (trycache)
747{
748 bootFile = gBootKernelCacheFile;
749 verbose("Loading kernel cache %s\n", bootFile);
750if (gBootVolume->OSVersion[3] > '6')
751{
752ret = LoadThinFatFile(bootFile, &binary);
753if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
754{
755archCpuType = CPU_TYPE_I386;
756ret = LoadThinFatFile(bootFile, &binary);
757}
758}
759else
760{
761ret = LoadFile(bootFile);
762binary = (void *)kLoadAddr;
763}
764
765 if (ret >= 0)
766{
767 break;
768 }
769
770 }
771safe_set_env(envAdler32, 0);
772 bootFile = bootInfo->bootFile;
773#ifdef BOOT_HELPER_SUPPORT
774
775 // Try to load kernel image from alternate locations on boot helper partitions.
776 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
777 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
778 if (ret == -1)
779 {
780sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
781ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
782if (ret == -1)
783{
784sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
785ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
786if (ret == -1)
787{
788// Not found any alternate locations, using the original kernel image path.
789strlcpy(bootFileSpec, bootFile,sizeof(bootFileSpec));
790}
791}
792 }
793#else
794strlcpy(bootFileSpec, bootFile,sizeof(bootFileSpec));
795#endif
796
797 verbose("Loading kernel %s\n", bootFileSpec);
798 ret = LoadThinFatFile(bootFileSpec, &binary);
799 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
800 {
801archCpuType = CPU_TYPE_I386;
802ret = LoadThinFatFile(bootFileSpec, &binary);
803 }
804
805 } while (0);
806
807#if DEBUG
808 printf("Pausing...");
809 sleep(8);
810#endif
811
812 if (ret <= 0)
813{
814 out:
815printf("Can't find %s\n", bootFile);
816
817sleep(1);
818#ifdef NBP_SUPPORT
819 if (gBootFileType == kNetworkDeviceType)
820{
821 // Return control back to PXE. Don't unload PXE base code.
822 gUnloadPXEOnExit = false;
823 break;
824 }
825#endif
826 }
827else
828{
829 /* Won't return if successful. */
830 if ( ExecKernel(binary))
831 {
832 firstRun = true;
833 continue;
834 }
835 }
836 }
837
838 // chainboot
839 if (status==1)
840{
841if (getVideoMode() == GRAPHICS_MODE)
842{// if we are already in graphics-mode,
843#if UNUSED
844__setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
845#else
846__setVideoMode(VGA_TEXT_MODE);// switch back to text mode
847#endif
848}
849 }
850#ifdef NBP_SUPPORT
851 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit)
852{
853nbpUnloadBaseCode();
854 }
855#endif
856}
857
858static void determineCpuArch(void)
859{
860if (cpu_mode_is64bit())
861{
862archCpuType = CPU_TYPE_X86_64;
863}
864else
865{
866archCpuType = CPU_TYPE_I386;
867}
868}
869
870void getKernelCachePath(void)
871{
872{
873// If there is an extra kext/mkext, we return immediatly and we skip the kernelCache
874// since kexts/mkexts are not loaded properly when the kernelCache is used.
875// Another method would be to re-build the kernelCache one the fly
876if (found_extra_kext() == true) return;
877}
878
879{
880const char *val;
881int len;
882unsigned long Adler32 = 0;
883
884if (getValueForKey(kKernelCacheKey, &val, &len, DEFAULT_BOOT_CONFIG))
885{
886 char * buffer = newString(val);
887
888if (val[0] == '\\')
889{
890// Flip the back slash's to slash's .
891 len = 0;
892 while (buffer[len] != '\0') {
893 if (buffer[len] == '\\')
894 {
895 buffer[len] = '/';
896 }
897 len++;
898 }
899}
900strlcpy(gBootKernelCacheFile, buffer, sizeof(gBootKernelCacheFile));
901 forcecache = true;
902}
903else
904{
905if(gBootVolume->OSVersion[3] > '6')
906{
907sprintf(gBootKernelCacheFile, "%s", kDefaultCachePath);
908}
909else if(gBootVolume->OSVersion[3] <= '6')
910{
911
912PlatformInfo *platformInfo = malloc(sizeof(PlatformInfo));
913if (platformInfo)
914{
915
916bzero(platformInfo, sizeof(PlatformInfo));
917
918if (GetgPlatformName())
919strlcpy(platformInfo->platformName,GetgPlatformName(), sizeof(platformInfo->platformName)+1);
920
921if (GetgRootDevice())
922{
923char *rootPath_p = platformInfo->rootPath;
924len = strlen(GetgRootDevice()) + 1;
925if ((unsigned)len > sizeof(platformInfo->rootPath))
926{
927len = sizeof(platformInfo->rootPath);
928}
929memcpy(rootPath_p, GetgRootDevice(),len);
930
931rootPath_p += len;
932
933len = strlen(bootInfo->bootFile);
934
935if ((unsigned)(rootPath_p - platformInfo->rootPath + len) >=
936sizeof(platformInfo->rootPath))
937{
938
939len = sizeof(platformInfo->rootPath) -
940(rootPath_p - platformInfo->rootPath);
941}
942memcpy(rootPath_p, bootInfo->bootFile, len);
943
944}
945
946if (!platformInfo->platformName[0] || !platformInfo->rootPath[0])
947{
948platformInfo->platformName[0] = platformInfo->rootPath[0] = 0;
949}
950#ifdef rootpath
951 SetgRootPath(platformInfo->rootPath);
952#endif
953
954Adler32 = OSSwapHostToBigInt32(adler32((unsigned char *)platformInfo, sizeof(*platformInfo)));
955safe_set_env(envAdler32, Adler32);
956
957free(platformInfo);
958}
959
960DBG("Adler32: %08lX\n",bootInfo->adler32);
961
962if (gBootVolume->OSVersion[3] < '6')
963{
964long flags, cachetime;
965int ret = -1;
966
967if (Adler32) {
968sprintf(gBootKernelCacheFile, "%s.%08lX", "/System/Library/Caches/com.apple.kernelcaches/kernelcache",Adler32);
969ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
970}
971
972if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
973{
974safe_set_env(envAdler32, 0);
975sprintf(gBootKernelCacheFile, "%s", "/System/Library/Caches/com.apple.kernelcaches/kernelcache");
976}
977
978} else if (Adler32)
979sprintf(gBootKernelCacheFile, "%s_%s.%08lX", kDefaultCachePath, (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64", Adler32); //Snow Leopard
980
981}
982}
983}
984}
985
986static void getRootDevice()
987{
988// Maximum config table value size
989#define VALUE_SIZE 2048
990bool uuidSet = false;
991const char *val = 0;
992 int cnt = 0;
993
994if (getValueForKey(kBootUUIDKey, &val, &cnt, DEFAULT_BOOT_CONFIG))
995{
996uuidSet = true;
997}
998else
999{
1000if (getValueForBootKey(bootArgs->CommandLine, kRootDeviceKey, &val, &cnt))
1001{
1002if (*val == '*' && *(val + 1) != '/' && *(val + 1) != 'u')
1003{
1004val += 1; //skip the *
1005uuidSet = true;
1006
1007}
1008else if (*val == '*' && *(val + 1) == 'u')
1009{
1010
1011if ( getValueForKey( kBootDeviceKey, &val, &cnt, DEFAULT_BOOT_CONFIG))
1012uuidSet = true;
1013
1014}
1015}
1016else
1017{
1018#ifdef BOOT_HELPER_SUPPORT
1019//
1020// Try an alternate method for getting the root UUID on boot helper partitions.
1021//
1022if (gBootVolume->flags & kBVFlagBooter)
1023{
1024if((loadHelperConfig() == 0)
1025 && getValueForKey(kHelperRootUUIDKey, &val, &cnt, &bootInfo->helperConfig) )
1026{
1027getValueForKey(kHelperRootUUIDKey, &val, &cnt, &bootInfo->helperConfig);
1028uuidSet = true;
1029goto out;
1030}
1031}
1032#endif
1033if ( getValueForKey( kBootDeviceKey, &val, &cnt, DEFAULT_BOOT_CONFIG))
1034{
1035int ArgCntRemaining = (int)get_env(envArgCntRemaining);
1036uuidSet = false;
1037char * valueBuffer;
1038valueBuffer = malloc(VALUE_SIZE);
1039char * argP = bootArgs->CommandLine;
1040valueBuffer[0] = '*';
1041if (cnt > VALUE_SIZE)
1042{
1043cnt = VALUE_SIZE;
1044}
1045strlcpy(valueBuffer + 1, val, cnt+1);
1046if (!copyArgument( kRootDeviceKey, valueBuffer, cnt, &argP, &ArgCntRemaining))
1047{
1048free(valueBuffer);
1049printf("Error: boot arguments too long, unable to set root device !!");
1050getc();
1051return;
1052}
1053 safe_set_env(envArgCntRemaining,ArgCntRemaining);
1054free(valueBuffer);
1055goto out;
1056}
1057
1058if (gBootVolume->fs_getuuid && gBootVolume->fs_getuuid (gBootVolume, bootInfo->uuidStr) == 0)
1059{
1060verbose("Setting boot-uuid to: %s\n", bootInfo->uuidStr);
1061//uuidSet = true;
1062SetgRootDevice(bootInfo->uuidStr);
1063return;
1064}
1065
1066}
1067}
1068
1069out:
1070verbose("Setting %s to: %s\n", uuidSet ? kBootUUIDKey : "root device", (char* )val);
1071 SetgRootDevice(val);
1072}
1073
1074static bool find_file_with_ext(const char* dir, const char *ext, const char * name_compare, size_t ext_size)
1075{
1076char* name;
1077long flags;
1078long time;
1079struct dirstuff* moduleDir = opendir(dir);
1080while(readdir(moduleDir, (const char**)&name, &flags, &time) >= 0)
1081{
1082int len = strlen(name);
1083
1084if (len >= ext_size)
1085{
1086if(strcmp(&name[len - ext_size], ext) == 0)
1087{
1088if (name_compare)
1089{
1090if (strcmp(name, name_compare) == 0)
1091{
1092DBG("found : %s\n", name);
1093closedir(moduleDir);
1094return true;
1095}
1096}
1097else
1098{
1099DBG("found : %s\n", name);
1100closedir(moduleDir);
1101return true;
1102}
1103}
1104#if DEBUG_BOOT
1105else
1106{
1107DBG("Ignoring %s\n", name);
1108}
1109#endif
1110}
1111#if DEBUG_BOOT
1112else
1113{
1114DBG("Ignoring %s\n", name);
1115}
1116#endif
1117}
1118
1119if (moduleDir) {
1120closedir(moduleDir);
1121
1122}
1123return false;
1124}
1125
1126// If a kext is found in /Extra/Extentions return true
1127// If a mkext is found in /Extra return true
1128// Otherwise return false
1129// Tips (if you still want to use extra kext(s)/mkext(s) ):
1130// 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),
1131// so it's recommended to create a system mkext by yourself to decrease boot time (see the kextcache commandline)
1132static bool found_extra_kext(void)
1133{
1134#define EXTENSIONS "Extensions"
1135#define MKEXT_EXT ".mkext"
1136#define MKEXT_EXT_SIZE sizeof("mkext")
1137#define KEXT_EXT ".kext"
1138#define KEXT_EXT_SIZE sizeof("kext")
1139
1140long flags;
1141long exttime;
1142int ret = -1;
1143
1144ret = GetFileInfo("rd(0,0)/Extra/", EXTENSIONS, &flags, &exttime);
1145if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeFlat))
1146{
1147if (((flags & kFileTypeMask) == kFileTypeFlat))
1148{
1149if (find_file_with_ext("rd(0,0)/Extra/", MKEXT_EXT, EXTENSIONS, MKEXT_EXT_SIZE))
1150{
1151return true;
1152}
1153}
1154else if (((flags & kFileTypeMask) == kFileTypeDirectory))
1155{
1156if (find_file_with_ext("rd(0,0)/Extra/Extensions/", KEXT_EXT, NULL, KEXT_EXT_SIZE))
1157{
1158return true;
1159}
1160}
1161}
1162ret = GetFileInfo("/Extra/", EXTENSIONS, &flags, &exttime);
1163if (ret == 0)
1164{
1165if (((flags & kFileTypeMask) == kFileTypeFlat))
1166{
1167if (find_file_with_ext("/Extra/", MKEXT_EXT, EXTENSIONS, MKEXT_EXT_SIZE))
1168{
1169return true;
1170}
1171}
1172else if (((flags & kFileTypeMask) == kFileTypeDirectory))
1173{
1174if (find_file_with_ext("/Extra/Extensions/", KEXT_EXT, NULL, KEXT_EXT_SIZE))
1175{
1176return true;
1177}
1178}
1179}
1180ret = GetFileInfo("bt(0,0)/Extra/", EXTENSIONS, &flags, &exttime);
1181if (ret == 0)
1182{
1183if (((flags & kFileTypeMask) == kFileTypeFlat))
1184{
1185if (find_file_with_ext("bt(0,0)/Extra/", MKEXT_EXT, EXTENSIONS, MKEXT_EXT_SIZE))
1186{
1187return true;
1188}
1189}
1190else if (((flags & kFileTypeMask) == kFileTypeDirectory))
1191{
1192if (find_file_with_ext("bt(0,0)/Extra/Extensions/", KEXT_EXT, NULL, KEXT_EXT_SIZE))
1193{
1194return true;
1195}
1196}
1197}
1198DBG("NO Extra Mkext/Kext found\n");
1199
1200// nothing found
1201return false;
1202}
1203
1204#if 0
1205static char *FIXED_BOOTFILE_PATH(char * str)
1206{
1207char bootfile[128];
1208
1209bool bootFileWithDevice = false;
1210// Check if bootFile start with a device ex: bt(0,0)/Extra/mach_kernel
1211if (strncmp(str,"bt(",3) == 0 ||
1212strncmp(str,"hd(",3) == 0 ||
1213strncmp(str,"rd(",3) == 0)
1214{
1215bootFileWithDevice = true;
1216}
1217
1218// bootFile must start with a / if it not start with a device name
1219if (!bootFileWithDevice && (str)[0] != '/')
1220sprintf(bootFile, "/%s", str); // append a leading /
1221else
1222strlcpy(bootFile, bootInfo->bootFile, sizeof(bootInfo->bootFile));
1223
1224return bootfile;
1225}
1226#endif
1227

Archive Download this file

Revision: 1913