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

Archive Download this file

Revision: 1402