Chameleon

Chameleon Svn Source Tree

Root/branches/slice/trunkM/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 "ramdisk.h"
59#include "gui.h"
60#include "platform.h"
61#include "modules.h"
62#include "graphics.h"
63
64long gBootMode; /* defaults to 0 == kBootModeNormal */
65bool gOverrideKernel;
66static char gBootKernelCacheFile[512];
67static char gCacheNameAdler[64 + 256];
68char *gPlatformName = gCacheNameAdler;
69char gRootDevice[512];
70char gMKextName[512];
71char gMacOSVersion[8];
72void *gRootPCIDev;
73void *gPlatform;
74void *gBootOrder;
75void *gSMBIOS;
76int gDualLink;
77
78bool gEnableCDROMRescan;
79bool gScanSingleDrive;
80
81int bvCount = 0;
82//intmenucount = 0;
83int gDeviceCount = 0;
84
85BVRef bvr;
86BVRef menuBVR;
87BVRef bvChain;
88bool useGUI;
89
90//static void selectBiosDevice(void);
91static unsigned long Adler32(unsigned char *buffer, long length);
92static bool checkOSVersion(const char * version);
93static bool getOSVersion();
94
95static bool gUnloadPXEOnExit = false;
96
97/*
98 * How long to wait (in seconds) to load the
99 * kernel after displaying the "boot:" prompt.
100 */
101#define kBootErrorTimeout 5
102
103
104//==========================================================================
105// Zero the BSS.
106
107static void zeroBSS(void)
108{
109extern char _DATA__bss__begin, _DATA__bss__end;
110extern char _DATA__common__begin, _DATA__common__end;
111
112bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
113bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
114}
115
116//==========================================================================
117// Malloc error function
118
119static void malloc_error(char *addr, size_t size, const char *file, int line)
120{
121stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
122}
123
124//==========================================================================
125//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
126//
127void initialize_runtime(void)
128{
129zeroBSS();
130malloc_init(0, 0, 0, malloc_error);
131}
132
133//==========================================================================
134// execKernel - Load the kernel image (mach-o) and jump to its entry point.
135
136static int ExecKernel(void *binary)
137{
138entry_t kernelEntry;
139int ret;
140
141bootArgs->kaddr = bootArgs->ksize = 0;
142execute_hook("ExecKernel", (void*)binary, NULL, NULL, NULL);
143
144ret = DecodeKernel(binary,
145 &kernelEntry,
146 (char **) &bootArgs->kaddr,
147 (int *)&bootArgs->ksize );
148
149if ( ret != 0 )
150return ret;
151
152// Reserve space for boot args
153reserveKernBootStruct();
154
155// Notify modules that the kernel has been decoded
156execute_hook("DecodedKernel", (void*)binary, NULL, NULL, NULL);
157
158 setupFakeEfi();
159
160// Load boot drivers from the specifed root path.
161 //if (!gHaveKernelCache)
162 LoadDrivers("/");
163
164 execute_hook("DriversLoaded", (void*)binary, NULL, NULL, NULL);
165
166clearActivityIndicator();
167/*
168if (gErrors) {
169printf("Errors encountered while starting up the computer.\n");
170printf("Pausing %d seconds...\n", kBootErrorTimeout);
171sleep(kBootErrorTimeout);
172}
173*/
174md0Ramdisk();
175
176verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
177
178// Cleanup the PXE base code.
179
180if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
181if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
182{
183printf("nbpUnloadBaseCode error %d\n", (int) ret);
184sleep(2);
185}
186}
187
188bool dummyVal;
189if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->chameleonConfig) && dummyVal) {
190printf("(Wait) ");
191pause();
192}
193
194usb_loop();
195
196 if (checkOSVersion("10.7"))
197 {
198 execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL);// Notify modules that the kernel is about to be started
199 }
200 else
201 {
202 execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgsPreLion, NULL, NULL);// Notify modules that the kernel is about to be started
203 }
204
205// If we were in text mode, switch to graphics mode.
206// This will draw the boot graphics unless we are in
207// verbose mode.
208
209if(gVerboseMode)
210 setVideoMode( GRAPHICS_MODE, 0 );
211else
212 drawBootGraphics();
213
214setupBooterLog();
215
216finalizeBootStruct();
217
218 if (checkOSVersion("10.7")) {
219
220// Masking out so that Lion doesn't doublefault
221outb(0x21, 0xff);/* Maskout all interrupts Pic1 */
222outb(0xa1, 0xff);/* Maskout all interrupts Pic2 */
223
224// Jump to kernel's entry point. There's no going back now.
225
226startprog( kernelEntry, bootArgs );
227}
228else {
229// Jump to kernel's entry point. There's no going back now.
230
231startprog( kernelEntry, bootArgsPreLion );
232}
233
234// Not reached
235return 0;
236}
237
238//==========================================================================
239// This is the entrypoint from real-mode which functions exactly as it did
240// before. Multiboot does its own runtime initialization, does some of its
241// own things, and then calls common_boot.
242void boot(int biosdev)
243{
244initialize_runtime();
245// Enable A20 gate before accessing memory above 1Mb.
246enableA20();
247common_boot(biosdev);
248}
249
250//==========================================================================
251// The 'main' function for the booter. Called by boot0 when booting
252// from a block device, or by the network booter.
253//
254// arguments:
255// biosdev - Value passed from boot1/NBP to specify the device
256// that the booter was loaded from.
257//
258// If biosdev is kBIOSDevNetwork, then this function will return if
259// booting was unsuccessful. This allows the PXE firmware to try the
260// next boot device on its list.
261void common_boot(int biosdev)
262{
263 int status;
264 char *bootFile;
265 unsigned long adler32;
266 bool quiet;
267 bool firstRun = true;
268 bool instantMenu;
269 bool rescanPrompt;
270 unsigned int allowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot;
271 unsigned int denyBVFlags = kBVFlagEFISystem;
272
273 // Set reminder to unload the PXE base code. Neglect to unload
274 // the base code will result in a hang or kernel panic.
275 gUnloadPXEOnExit = true;
276
277 // Record the device that the booter was loaded from.
278 gBIOSDev = biosdev & kBIOSDevMask;
279
280 // Initialize boot info structure.
281 initKernBootStruct();
282
283initBooterLog();
284
285 // Setup VGA text mode.
286 // Not sure if it is safe to call setVideoMode() before the
287 // config table has been loaded. Call video_mode() instead.
288#if DEBUG
289 printf("before video_mode\n");
290#endif
291 video_mode( 2 ); // 80x25 mono text mode.
292#if DEBUG
293 printf("after video_mode\n");
294#endif
295
296 // Scan and record the system's hardware information.
297 scan_platform();
298
299 // First get info for boot volume.
300 scanBootVolumes(gBIOSDev, 0);
301 bvChain = getBVChainForBIOSDev(gBIOSDev);
302 setBootGlobals(bvChain);
303
304 // Load boot.plist config file
305 status = loadChameleonConfig(&bootInfo->chameleonConfig);
306
307 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) {
308 gBootMode |= kBootModeQuiet;
309 }
310
311 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
312 if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) {
313 firstRun = false;
314 }
315
316 // Loading preboot ramdisk if exists.
317 loadPrebootRAMDisk();
318
319 // Disable rescan option by default
320 gEnableCDROMRescan = false;
321
322 // Enable it with Rescan=y in system config
323 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig) && gEnableCDROMRescan) {
324 gEnableCDROMRescan = true;
325 }
326
327 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
328 rescanPrompt = false;
329 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
330 gEnableCDROMRescan = promptForRescanOption();
331 }
332
333 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
334 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig) && gScanSingleDrive) {
335 gScanSingleDrive = true;
336 }
337
338 // Create a list of partitions on device(s).
339 if (gScanSingleDrive) {
340 scanBootVolumes(gBIOSDev, &bvCount);
341 } else {
342 scanDisks(gBIOSDev, &bvCount);
343 }
344
345 // Create a separated bvr chain using the specified filters.
346 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
347
348 gBootVolume = selectBootVolume(bvChain);
349
350// Intialize module system
351init_module_system();
352
353#if DEBUG
354 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
355 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
356 getchar();
357#endif
358
359useGUI = true;
360// Override useGUI default
361getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig);
362if (useGUI && initGUI())
363{
364// initGUI() returned with an error, disabling GUI.
365useGUI = false;
366}
367
368 setBootGlobals(bvChain);
369
370 // Parse args, load and start kernel.
371 while (1) {
372 const char *val;
373 int len;
374 int trycache;
375 long flags, cachetime, kerneltime, exttime, sleeptime, time;
376 int ret = -1;
377 void *binary = (void *)kLoadAddr;
378 bool tryresume;
379 bool tryresumedefault;
380 bool forceresume;
381bool usecache = false;//true;
382
383 // additional variable for testing alternate kernel image locations on boot helper partitions.
384 char bootFileSpec[512];
385
386 // Initialize globals.
387
388 sysConfigValid = false;
389 gErrors = false;
390
391 status = getBootOptions(firstRun);
392 firstRun = false;
393 if (status == -1) continue;
394
395 status = processBootOptions();
396 // Status==1 means to chainboot
397 if ( status == 1 ) break;
398 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
399 if ( status == -1 )
400 {
401 // gBootVolume == NULL usually means the user hit escape.
402 if(gBootVolume == NULL)
403 {
404 freeFilteredBVChain(bvChain);
405
406 if (gEnableCDROMRescan)
407 rescanBIOSDevice(gBIOSDev);
408
409 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
410 setBootGlobals(bvChain);
411 setupDeviceList(&bootInfo->themeConfig);
412 }
413 continue;
414 }
415
416 // Other status (e.g. 0) means that we should proceed with boot.
417
418// Turn off any GUI elements
419if( bootArgs->Video.v_display == GRAPHICS_MODE )
420{
421gui.devicelist.draw = false;
422gui.bootprompt.draw = false;
423gui.menu.draw = false;
424gui.infobox.draw = false;
425gui.logo.draw = false;
426drawBackground();
427updateVRAM();
428}
429
430// Find out which version mac os we're booting.
431getOSVersion();
432
433if (platformCPUFeature(CPU_FEATURE_EM64T)) {
434archCpuType = CPU_TYPE_X86_64;
435} else {
436archCpuType = CPU_TYPE_I386;
437}
438if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) {
439if (strncmp(val, "i386", 4) == 0) {
440archCpuType = CPU_TYPE_I386;
441}
442}
443
444 if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) {
445if (strncmp(val, "i386", 4) == 0) {
446archCpuType = CPU_TYPE_I386;
447}
448}
449
450 //archCpuType = CPU_TYPE_I386;
451
452// Notify modules that we are attempting to boot
453execute_hook("PreBoot", NULL, NULL, NULL, NULL);
454
455if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) {
456tryresume = true;
457tryresumedefault = true;
458} else {
459tryresumedefault = false;
460}
461
462if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) {
463forceresume = false;
464}
465
466if (forceresume) {
467tryresume = true;
468tryresumedefault = false;
469}
470
471while (tryresume) {
472const char *tmp;
473BVRef bvr;
474if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig))
475val="/private/var/vm/sleepimage";
476
477// Do this first to be sure that root volume is mounted
478ret = GetFileInfo(0, val, &flags, &sleeptime);
479
480if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
481break;
482
483// Can't check if it was hibernation Wake=y is required
484if (bvr->modTime == 0 && tryresumedefault)
485break;
486
487if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
488break;
489
490if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
491#if DEBUG
492printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
493#endif
494break;
495}
496
497HibernateBoot((char *)val);
498break;
499}
500
501getBoolForKey(kUseKernelCache, &usecache, &bootInfo->chameleonConfig);
502if(usecache) {
503if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
504 if(val[0] == '\\')
505 {
506 len--;
507 val++;
508 }
509 strlcpy(gBootKernelCacheFile, val, len+1);
510}
511else {
512//Lion
513if (checkOSVersion("10.7")) {
514sprintf(gBootKernelCacheFile, "%skernelcache", kDefaultCachePathSnow);
515}
516// Snow Leopard
517else if (checkOSVersion("10.6")) {
518sprintf(gBootKernelCacheFile, "kernelcache_%s", (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64");
519int lnam = sizeof(gBootKernelCacheFile) + 9; //with adler32
520//Slice - TODO ???
521// e.g. kernelcache_i386.E102928C.qSs0 = "unsaved" cache file.
522//
523// See kext_tools-180.2.1/kextcache_main.c:
524// "Source directory has changed since starting; "
525 // "not saving cache file %s."
526// or
527// "Source kernel has changed since starting; "
528 // "not saving cache file %s."
529
530char* name;
531long prev_time = 0;
532
533struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow);
534
535while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0)
536{
537if(((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time && strstr(name, gBootKernelCacheFile) && (name[lnam] != '.'))
538{
539sprintf(gBootKernelCacheFile, "%s%s", kDefaultCachePathSnow, name);
540prev_time = time;
541}
542}
543}
544else {
545// Reset cache name.
546bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
547
548sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->chameleonConfig);
549
550adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
551
552sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePathLeo, adler32);
553}
554}
555}
556
557 // Check for cache file.
558 trycache = (usecache &&
559((gBootMode & kBootModeSafe) == 0) &&
560 !gOverrideKernel &&
561 (gBootFileType == kBlockDeviceType) &&
562 (gMKextName[0] == '\0') &&
563 (gBootKernelCacheFile[0] != '\0'));
564
565verbose("Loading Darwin %s\n", gMacOSVersion);
566
567 if (trycache) do {
568 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
569 if(ret != 0) kerneltime = 0;
570 else if ((flags & kFileTypeMask) != kFileTypeFlat) {
571 trycache = 0;
572 break;
573 }
574
575 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
576 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
577 || (cachetime < kerneltime)) {
578 trycache = 0;
579 break;
580 }
581 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
582 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
583 && (cachetime < exttime)) {
584 trycache = 0;
585 break;
586 }
587 if (ret == 0 && kerneltime > exttime) {
588 exttime = kerneltime;
589 }
590 if (ret == 0 && cachetime != (exttime + 1)) {
591 trycache = 0;
592 break;
593 }
594 } while (0);
595
596 do {
597 if (trycache) {
598 bootFile = gBootKernelCacheFile;
599
600verbose("Loading kernel cache %s\n", bootFile);
601
602 if (checkOSVersion("10.7")) {
603 ret = LoadThinFatFile(bootFile, &binary);
604}
605else {
606 ret = LoadFile(bootFile);
607binary = (void *)kLoadAddr;
608}
609
610 if (ret >= 0)
611 break;
612
613verbose("Kernel cache did not load %s\n ", bootFile);
614 }
615
616 bootFile = bootInfo->bootFile;
617
618 // Try to load kernel image from alternate locations on boot helper partitions.
619 sprintf(bootFileSpec, "com.apple.boot.P%s", bootFile);
620 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
621 if (ret == -1)
622 {
623 sprintf(bootFileSpec, "com.apple.boot.R%s", bootFile);
624 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
625 if (ret == -1)
626 {
627 sprintf(bootFileSpec, "com.apple.boot.S%s", bootFile);
628 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
629 if (ret == -1)
630 {
631 // No alternate location found, using the original kernel image path.
632 strcpy(bootFileSpec, bootFile);
633 }
634 }
635 }
636
637 if (checkOSVersion("10.7"))
638 {
639 //Lion, dont load kernel if haz cache
640 if (!trycache) {
641 verbose("Loading kernel %s\n", bootFileSpec);
642 ret = LoadThinFatFile(bootFileSpec, &binary);
643 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) {
644 archCpuType = CPU_TYPE_I386;
645 ret = LoadThinFatFile(bootFileSpec, &binary);
646 }
647 }
648else ret = 1;
649 }
650else {
651 //Snow Leopard or older
652 verbose("Loading kernel %s\n", bootFileSpec);
653 ret = LoadThinFatFile(bootFileSpec, &binary);
654 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) {
655 archCpuType = CPU_TYPE_I386;
656 ret = LoadThinFatFile(bootFileSpec, &binary);
657 }
658 }
659 } while (0);
660
661 clearActivityIndicator();
662#if DEBUG
663 printf("Pausing...");
664 sleep(8);
665#endif
666
667 if (ret <= 0) {
668printf("Can't find %s\n", bootFile);
669
670sleep(1);
671
672 if (gBootFileType == kNetworkDeviceType) {
673 // Return control back to PXE. Don't unload PXE base code.
674 gUnloadPXEOnExit = false;
675 break;
676 }
677 } else {
678 /* Won't return if successful. */
679 ret = ExecKernel(binary);
680 }
681 }
682
683 // chainboot
684 if (status==1) {
685if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
686setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
687}
688 }
689
690 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
691nbpUnloadBaseCode();
692 }
693}
694
695/*!
696 Selects a new BIOS device, taking care to update the global state appropriately.
697 */
698/*
699static void selectBiosDevice(void)
700{
701 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
702 CacheReset();
703 diskFreeMap(oldMap);
704 oldMap = NULL;
705
706 int dev = selectAlternateBootDevice(gBIOSDev);
707
708 BVRef bvchain = scanBootVolumes(dev, 0);
709 BVRef bootVol = selectBootVolume(bvchain);
710 gBootVolume = bootVol;
711 setRootVolume(bootVol);
712 gBIOSDev = dev;
713}
714*/
715
716bool checkOSVersion(const char * version)
717{
718return ((gMacOSVersion[0] == version[0]) && (gMacOSVersion[1] == version[1]) && (gMacOSVersion[2] == version[2]) && (gMacOSVersion[3] == version[3]));
719}
720
721bool getOSVersion()
722{
723bool valid = false;
724config_file_t systemVersion;
725const char *val;
726int len;
727
728if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
729{
730valid = true;
731}
732else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
733{
734valid = true;
735}
736
737if (valid)
738{
739if (getValueForKey(kProductVersion, &val, &len, &systemVersion))
740{
741// getValueForKey uses const char for val
742// so copy it and trim
743*gMacOSVersion = '\0';
744strncat(gMacOSVersion, val, MIN(len, 4));
745}
746else
747valid = false;
748}
749
750return valid;
751}
752
753#define BASE 65521L /* largest prime smaller than 65536 */
754#define NMAX 5000
755// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
756
757#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
758#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
759#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
760#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
761#define DO16(buf) DO8(buf,0); DO8(buf,8);
762
763unsigned long Adler32(unsigned char *buf, long len)
764{
765 unsigned long s1 = 1; // adler & 0xffff;
766 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
767 unsigned long result;
768 int k;
769
770 while (len > 0) {
771 k = len < NMAX ? len : NMAX;
772 len -= k;
773 while (k >= 16) {
774 DO16(buf);
775 buf += 16;
776 k -= 16;
777 }
778 if (k != 0) do {
779 s1 += *buf++;
780 s2 += s1;
781 } while (--k);
782 s1 %= BASE;
783 s2 %= BASE;
784 }
785 result = (s2 << 16) | s1;
786 return OSSwapHostToBigInt32(result);
787}
788

Archive Download this file

Revision: 1279