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

Archive Download this file

Revision: 1439