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

Archive Download this file

Revision: 1103