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

Archive Download this file

Revision: 2121