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

Archive Download this file

Revision: 1396