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

Archive Download this file

Revision: 1171