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

Archive Download this file

Revision: 1919