Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 1442