Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 1021