Chameleon Applications

Chameleon Applications Svn Source Tree

Root/branches/iFabio/Chameleon/i386/boot2/boot.c

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

Archive Download this file

Revision: 296