Chameleon Applications

Chameleon Applications Svn Source Tree

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

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

Archive Download this file

Revision: 298