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;
365boolusecache = false;//true;
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
488getBoolForKey(kUseKernelCache, &usecache, &bootInfo->chameleonConfig);
489if (usecache) {
490if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
491if (val[0] == '\\')
492{
493len--;
494val++;
495}
496strlcpy(gBootKernelCacheFile, val, len + 1);
497}
498else {
499//Lion
500if (checkOSVersion("10.7")) {
501sprintf(gBootKernelCacheFile, "%skernelcache", kDefaultCachePathSnow);
502}
503// Snow Leopard
504else if (checkOSVersion("10.6")) {
505sprintf(gBootKernelCacheFile, "kernelcache_%s", (archCpuType == CPU_TYPE_I386)
506? "i386" : "x86_64");
507int lnam = sizeof(gBootKernelCacheFile) + 9; //with adler32
508
509char* name;
510long prev_time = 0;
511
512struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow);
513
514while(readdir(cacheDir, (const char**)&name, &flags, &time) >= 0)
515{
516if (((flags & kFileTypeMask) != kFileTypeDirectory) && time > prev_time
517&& strstr(name, gBootKernelCacheFile) && (name[lnam] != '.'))
518{
519sprintf(gBootKernelCacheFile, "%s%s", kDefaultCachePathSnow, name);
520prev_time = time;
521}
522}
523}
524else {
525// Reset cache name.
526bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
527
528sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
529
530adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
531
532sprintf(gBootKernelCacheFile, "%s.%08lX", kDefaultCachePathLeo, adler32);
533}
534}
535}
536
537// Check for cache file.
538trycache = (usecache &&
539((gBootMode & kBootModeSafe) == 0) &&
540!gOverrideKernel &&
541(gBootFileType == kBlockDeviceType) &&
542(gMKextName[0] == '\0') &&
543(gBootKernelCacheFile[0] != '\0'));
544
545verbose("Loading Darwin %s\n", gMacOSVersion);
546
547if (trycache) do {
548ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
549if (ret != 0) kerneltime = 0;
550else if ((flags & kFileTypeMask) != kFileTypeFlat) {
551trycache = 0;
552break;
553}
554
555ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
556if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
557|| (cachetime < kerneltime)) {
558trycache = 0;
559break;
560}
561
562ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
563if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
564&& (cachetime < exttime)) {
565trycache = 0;
566break;
567}
568
569if (ret == 0 && kerneltime > exttime) {
570exttime = kerneltime;
571}
572
573if (ret == 0 && cachetime != (exttime + 1)) {
574trycache = 0;
575break;
576}
577} while (0);
578
579do {
580if (trycache) {
581bootFile = gBootKernelCacheFile;
582
583verbose("Loading kernel cache %s\n", bootFile);
584
585if (checkOSVersion("10.7")) {
586ret = LoadThinFatFile(bootFile, &binary);
587}
588else {
589ret = LoadFile(bootFile);
590binary = (void *)kLoadAddr;
591}
592
593if (ret >= 0)
594break;
595
596verbose("Kernel cache did not load %s\n ", bootFile);
597}
598
599if (checkOSVersion("10.7")) {
600bootFile = gBootKernelCacheFile;
601}
602else {
603sprintf(bootFile, "/%s", bootInfo->bootFile);
604}
605
606// Try to load kernel image from alternate locations on boot helper partitions.
607sprintf(bootFileSpec, "com.apple.boot.P%s", bootFile);
608ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
609if (ret == -1)
610{
611sprintf(bootFileSpec, "com.apple.boot.R%s", bootFile);
612ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
613if (ret == -1)
614{
615sprintf(bootFileSpec, "com.apple.boot.S%s", bootFile);
616ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
617if (ret == -1)
618{
619// No alternate location found, using the original kernel image path.
620strcpy(bootFileSpec, bootInfo->bootFile);
621}
622}
623}
624
625if (checkOSVersion("10.7"))
626{
627//Lion, dont load kernel if haz cache
628if (!trycache)
629{
630verbose("Loading kernel %s\n", bootFileSpec);
631ret = LoadThinFatFile(bootFileSpec, &binary);
632if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
633{
634archCpuType = CPU_TYPE_I386;
635ret = LoadThinFatFile(bootFileSpec, &binary);
636}
637}
638else ret = 1;
639}
640else
641{
642//Snow Leopard or older
643verbose("Loading kernel %s\n", bootFileSpec);
644ret = LoadThinFatFile(bootFileSpec, &binary);
645if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
646{
647archCpuType = CPU_TYPE_I386;
648ret = LoadThinFatFile(bootFileSpec, &binary);
649}
650}
651} while (0);
652
653clearActivityIndicator();
654
655#if DEBUG
656printf("Pausing...");
657sleep(8);
658#endif
659
660if (ret <= 0) {
661printf("Can't find %s\n", bootFile);
662
663sleep(1);
664
665if (gBootFileType == kNetworkDeviceType) {
666// Return control back to PXE. Don't unload PXE base code.
667gUnloadPXEOnExit = false;
668break;
669}
670} else {
671/* Won't return if successful. */
672ret = ExecKernel(binary);
673}
674}
675
676// chainboot
677if (status == 1) {
678// if we are already in graphics-mode,
679if (getVideoMode() == GRAPHICS_MODE) {
680setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode.
681}
682}
683
684if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
685nbpUnloadBaseCode();
686}
687}
688
689/*!
690Selects a new BIOS device, taking care to update the global state appropriately.
691 */
692/*
693static void selectBiosDevice(void)
694{
695struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
696CacheReset();
697diskFreeMap(oldMap);
698oldMap = NULL;
699
700int dev = selectAlternateBootDevice(gBIOSDev);
701
702BVRef bvchain = scanBootVolumes(dev, 0);
703BVRef bootVol = selectBootVolume(bvchain);
704gBootVolume = bootVol;
705setRootVolume(bootVol);
706gBIOSDev = dev;
707}
708*/
709
710bool checkOSVersion(const char * version)
711{
712return ((gMacOSVersion[0] == version[0]) && (gMacOSVersion[1] == version[1])
713&& (gMacOSVersion[2] == version[2]) && (gMacOSVersion[3] == version[3]));
714}
715
716bool getOSVersion()
717{
718boolvalid = false;
719const char*val;
720intlen;
721config_file_tsystemVersion;
722
723if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
724{
725valid = true;
726}
727else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
728{
729valid = true;
730}
731
732if (valid)
733{
734if(getValueForKey(kProductVersion, &val, &len, &systemVersion))
735{
736// getValueForKey uses const char for val
737// so copy it and trim
738*gMacOSVersion = '\0';
739strncat(gMacOSVersion, val, MIN(len, 4));
740}
741else
742valid = false;
743}
744
745return valid;
746}
747
748#define BASE 65521L /* largest prime smaller than 65536 */
749#define NMAX 5000
750// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
751
752#define DO1(buf, i){s1 += buf[i]; s2 += s1;}
753#define DO2(buf, i)DO1(buf, i); DO1(buf, i + 1);
754#define DO4(buf, i)DO2(buf, i); DO2(buf, i + 2);
755#define DO8(buf, i)DO4(buf, i); DO4(buf, i + 4);
756#define DO16(buf)DO8(buf, 0); DO8(buf, 8);
757
758unsigned long Adler32(unsigned char *buf, long len)
759{
760unsigned long s1 = 1; // adler & 0xffff;
761unsigned long s2 = 0; // (adler >> 16) & 0xffff;
762unsigned long result;
763int k;
764
765while (len > 0) {
766k = len < NMAX ? len : NMAX;
767len -= k;
768while (k >= 16) {
769DO16(buf);
770buf += 16;
771k -= 16;
772}
773if (k != 0) do {
774s1 += *buf++;
775s2 += s1;
776} while (--k);
777s1 %= BASE;
778s2 %= BASE;
779}
780result = (s2 << 16) | s1;
781return OSSwapHostToBigInt32(result);
782}
783

Archive Download this file

Revision: 1433