Chameleon

Chameleon Svn Source Tree

Root/branches/mozodojo/i386/boot2/boot.c

  • Property svn:eol-style set to native
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
62long gBootMode; /* defaults to 0 == kBootModeNormal */
63bool gOverrideKernel;
64static char gBootKernelCacheFile[512];
65static char gCacheNameAdler[64 + 256];
66char *gPlatformName = gCacheNameAdler;
67char gRootDevice[512];
68char gMKextName[512];
69char gMacOSVersion[8];
70bool gEnableCDROMRescan;
71bool gScanSingleDrive;
72
73int bvCount = 0;
74//intmenucount = 0;
75int gDeviceCount = 0;
76
77BVRef bvr;
78BVRef menuBVR;
79BVRef bvChain;
80bool useGUI;
81
82//static void selectBiosDevice(void);
83static unsigned long Adler32(unsigned char *buffer, long length);
84static bool getOSVersion(char *str);
85
86static bool gUnloadPXEOnExit = false;
87
88/*
89 * How long to wait (in seconds) to load the
90 * kernel after displaying the "boot:" prompt.
91 */
92#define kBootErrorTimeout 5
93
94/*
95 * Default path to kernel cache file
96 */
97//Slice - first one for Leopard
98#define kDefaultCachePath "/System/Library/Caches/com.apple.kernelcaches/"
99#define kDefaultCachePathSnow "/System/Library/Caches/com.apple.kext.caches/Startup/"
100
101//==========================================================================
102// Zero the BSS.
103
104static void zeroBSS(void)
105{
106extern char _DATA__bss__begin, _DATA__bss__end;
107extern char _DATA__common__begin, _DATA__common__end;
108
109bzero(&_DATA__bss__begin, (&_DATA__bss__end - &_DATA__bss__begin));
110bzero(&_DATA__common__begin, (&_DATA__common__end - &_DATA__common__begin));
111}
112
113//==========================================================================
114// Malloc error function
115
116static void malloc_error(char *addr, size_t size, const char *file, int line)
117{
118stop("\nMemory allocation error! Addr=0x%x, Size=0x%x, File=%s, Line=%d\n", (unsigned)addr, (unsigned)size, file, line);
119}
120
121//==========================================================================
122//Initializes the runtime. Right now this means zeroing the BSS and initializing malloc.
123//
124void initialize_runtime(void)
125{
126zeroBSS();
127malloc_init(0, 0, 0, malloc_error);
128}
129
130//==========================================================================
131// execKernel - Load the kernel image (mach-o) and jump to its entry point.
132
133static int ExecKernel(void *binary)
134{
135 entry_t kernelEntry;
136 int ret;
137
138 bootArgs->kaddr = bootArgs->ksize = 0;
139 bootArgsSnow->kaddr = bootArgs->ksize = 0;
140
141 if ((gMacOSVersion[0] == '1') && (gMacOSVersion[1] == '0') && (gMacOSVersion[2] == '.') && (gMacOSVersion[3] >= '7'))
142 ret = DecodeKernel(binary,
143 &kernelEntry,
144 (char **) &bootArgs->kaddr,
145 (int *)&bootArgs->ksize );
146 else
147 ret = DecodeKernel(binary,
148 &kernelEntry,
149 (char **) &bootArgsSnow->kaddr,
150 (int *)&bootArgsSnow->ksize );
151
152 if ( ret != 0 )
153 return ret;
154
155 // Reserve space for boot args
156 reserveKernBootStruct();
157
158 // Load boot drivers from the specifed root path.
159
160 if (!gHaveKernelCache) {
161LoadDrivers("/");
162 }
163
164 clearActivityIndicator();
165
166 if (gErrors) {
167 printf("Errors encountered while starting up the computer.\n");
168 printf("Pausing %d seconds...\n", kBootErrorTimeout);
169 sleep(kBootErrorTimeout);
170 }
171
172 setupFakeEfi();
173
174 md0Ramdisk();
175
176 verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64");
177
178 // Cleanup the PXE base code.
179
180 if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) {
181if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess )
182 {
183 printf("nbpUnloadBaseCode error %d\n", (int) ret);
184 sleep(2);
185 }
186 }
187
188 bool dummyVal;
189if (getBoolForKey(kWaitForKeypressKey, &dummyVal, &bootInfo->bootConfig) && dummyVal) {
190printf("Press any key to continue...");
191getc();
192}
193
194usb_loop();
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.
199
200 if(gVerboseMode)
201setVideoMode( GRAPHICS_MODE, 0 );
202 else
203drawBootGraphics();
204
205setupBooterLog();
206
207 finalizeBootStruct();
208
209 // Masking out so that Lion doesn't doublefault
210 outb(0x21, 0xff); /* Maskout all interrupts Pic1 */
211outb(0xa1, 0xff); /* Maskout all interrupts Pic2 */
212
213 // Jump to kernel's entry point. There's no going back now.
214
215 if ((gMacOSVersion[0] == '1') && (gMacOSVersion[1] == '0') && (gMacOSVersion[2] == '.') && (gMacOSVersion[3] >= '7'))
216 startprog( kernelEntry, bootArgs );
217 else
218 startprog( kernelEntry, bootArgsSnow );
219
220 // Not reached
221
222 return 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{
250 int status;
251 char *bootFile;
252 unsigned long adler32;
253 bool quiet;
254 bool firstRun = true;
255 bool instantMenu;
256 bool rescanPrompt;
257 unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
258 unsigned int denyBVFlags = kBVFlagEFISystem;
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.
262 gUnloadPXEOnExit = true;
263
264 // Record the device that the booter was loaded from.
265 gBIOSDev = biosdev & kBIOSDevMask;
266
267 // Initialize boot info structure.
268 initKernBootStruct();
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
276 printf("before video_mode\n");
277#endif
278 video_mode( 2 ); // 80x25 mono text mode.
279#if DEBUG
280 printf("after video_mode\n");
281#endif
282
283 // Scan and record the system's hardware information.
284 scan_platform();
285
286 // First get info for boot volume.
287 scanBootVolumes(gBIOSDev, 0);
288 bvChain = getBVChainForBIOSDev(gBIOSDev);
289 setBootGlobals(bvChain);
290
291 // Load boot.plist config file
292 status = loadSystemConfig(&bootInfo->bootConfig);
293
294 if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) {
295 gBootMode |= kBootModeQuiet;
296 }
297
298 // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
299 if (getBoolForKey(kInsantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) {
300 firstRun = false;
301 }
302
303 // Loading preboot ramdisk if exists.
304 loadPrebootRAMDisk();
305
306 // Disable rescan option by default
307 gEnableCDROMRescan = false;
308
309 // Enable it with Rescan=y in system config
310 if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan) {
311 gEnableCDROMRescan = true;
312 }
313
314 // Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
315 rescanPrompt = false;
316 if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->bootConfig) && rescanPrompt && biosDevIsCDROM(gBIOSDev)) {
317 gEnableCDROMRescan = promptForRescanOption();
318 }
319
320 // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
321 if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive) {
322 gScanSingleDrive = true;
323 }
324
325 // Create a list of partitions on device(s).
326 if (gScanSingleDrive) {
327scanBootVolumes(gBIOSDev, &bvCount);
328 } else {
329scanDisks(gBIOSDev, &bvCount);
330 }
331
332 // Create a separated bvr chain using the specified filters.
333 bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
334
335 gBootVolume = selectBootVolume(bvChain);
336
337#if DEBUG
338 printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
339 printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
340 getc();
341#endif
342
343useGUI = true;
344// Override useGUI default
345getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);
346if (useGUI && initGUI())
347{
348// initGUI() returned with an error, disabling GUI.
349useGUI = false;
350}
351
352 setBootGlobals(bvChain);
353
354 // Parse args, load and start kernel.
355 while (1) {
356 const char *val;
357 int len;
358 int trycache;
359 long flags, cachetime, kerneltime, exttime, sleeptime, time;
360 int ret = -1;
361 void *binary = (void *)kLoadAddr;
362 bool tryresume;
363 bool tryresumedefault;
364 bool forceresume;
365
366 // additional variable for testing alternate kernel image locations on boot helper partitions.
367 char bootFileSpec[512];
368
369 // Initialize globals.
370
371 sysConfigValid = false;
372 gErrors = false;
373
374 status = getBootOptions(firstRun);
375 firstRun = false;
376 if (status == -1) continue;
377
378 status = processBootOptions();
379 // Status==1 means to chainboot
380 if ( status == 1 ) break;
381 // Status==-1 means that the config file couldn't be loaded or that gBootVolume is NULL
382 if ( status == -1 )
383 {
384// gBootVolume == NULL usually means the user hit escape.
385if(gBootVolume == NULL)
386{
387freeFilteredBVChain(bvChain);
388
389if (gEnableCDROMRescan)
390rescanBIOSDevice(gBIOSDev);
391
392bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
393setBootGlobals(bvChain);
394setupDeviceList(&bootInfo->themeConfig);
395}
396continue;
397 }
398
399 // Other status (e.g. 0) means that we should proceed with boot.
400
401// Turn off any GUI elements
402if( (bootArgs->Video.v_display == GRAPHICS_MODE) || (bootArgsSnow->Video.v_display == GRAPHICS_MODE) )
403{
404gui.devicelist.draw = false;
405gui.bootprompt.draw = false;
406gui.menu.draw = false;
407gui.infobox.draw = false;
408gui.logo.draw = false;
409drawBackground();
410updateVRAM();
411}
412
413// Find out which version mac os we're booting.
414getOSVersion(gMacOSVersion);
415
416if (platformCPUFeature(CPU_FEATURE_EM64T)) {
417archCpuType = CPU_TYPE_X86_64;
418} else {
419archCpuType = CPU_TYPE_I386;
420}
421if (getValueForKey(karch, &val, &len, &bootInfo->bootConfig)) {
422if (strncmp(val, "i386", 4) == 0) {
423archCpuType = CPU_TYPE_I386;
424}
425}
426
427if (!getBoolForKey (kWake, &tryresume, &bootInfo->bootConfig)) {
428tryresume = true;
429tryresumedefault = true;
430} else {
431tryresumedefault = false;
432}
433
434if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->bootConfig)) {
435forceresume = false;
436}
437
438if (forceresume) {
439tryresume = true;
440tryresumedefault = false;
441}
442
443while (tryresume) {
444const char *tmp;
445BVRef bvr;
446if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->bootConfig))
447val="/private/var/vm/sleepimage";
448
449// Do this first to be sure that root volume is mounted
450ret = GetFileInfo(0, val, &flags, &sleeptime);
451
452if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
453break;
454
455// Can't check if it was hibernation Wake=y is required
456if (bvr->modTime == 0 && tryresumedefault)
457break;
458
459if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
460break;
461
462if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
463printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",bvr->modTime-sleeptime);
464break;
465}
466
467HibernateBoot((char *)val);
468break;
469}
470
471 // Reset cache name.
472 bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
473
474 sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile);
475
476 adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
477
478 if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
479 strlcpy(gBootKernelCacheFile, val, len+1);
480 }
481else {
482//Lion
483if ((gMacOSVersion[0] == '1') && (gMacOSVersion[1] == '0') && (gMacOSVersion[2] == '.') && (gMacOSVersion[3] >= '7')) {
484sprintf(gBootKernelCacheFile, "%skernelcache", kDefaultCachePathSnow);
485}
486// Snow Leopard
487else if ((gMacOSVersion[0] == '1') && (gMacOSVersion[1] == '0') && (gMacOSVersion[2] == '.') && (gMacOSVersion[3] == '6')) {
488sprintf(gBootKernelCacheFile, "kernelcache_%s", /*kDefaultCachePathSnow,*/ (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64"); //, adler32);
489verbose("search for kernelcache %s\n", gBootKernelCacheFile);
490int lnam = sizeof(gBootKernelCacheFile) + 9; //with adler32
491//Slice - TODO
492/*
493 - but the name is longer .adler32 and more...
494 kernelcache_i386.E102928C.qSs0
495 so will opendir and scan for some files
496 */
497char* name;
498long flagsC;
499long timeC;
500struct dirstuff* cacheDir = opendir(kDefaultCachePathSnow);
501
502while(readdir(cacheDir, (const char**)&name, &flagsC, &timeC) >= 0)
503{
504if(strstr(name, gBootKernelCacheFile)) //?
505{
506if(name[lnam] == '.') continue;
507//char* tmp = malloc(strlen(name) + 1);
508sprintf(gBootKernelCacheFile, "%s%s", kDefaultCachePathSnow, name);
509verbose("Kernel cache found %s\n", gBootKernelCacheFile);
510break;
511}
512}
513//close(cacheDir);
514}
515else {
516sprintf(gBootKernelCacheFile, "%skernelcache", kDefaultCachePath);
517}
518
519
520/*if (archCpuType == CPU_TYPE_X86_64)
521sprintf(gBootKernelCacheFile, "%s_X86_64.%08lX", kDefaultCachePath, adler32);
522else
523sprintf(gBootKernelCacheFile, "%s_i386.%08lX", kDefaultCachePath, adler32);*/
524}
525
526 // Check for cache file.
527 trycache = (((gBootMode & kBootModeSafe) == 0) &&
528 !gOverrideKernel &&
529 (gBootFileType == kBlockDeviceType) &&
530 (gMKextName[0] == '\0') &&
531 (gBootKernelCacheFile[0] != '\0'));
532
533verbose("Loading Darwin %s\n", gMacOSVersion);
534
535 if (trycache) do {
536
537 // if we haven't found the kernel yet, don't use the cache
538 ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
539 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)) {
540 trycache = 0;
541 break;
542 }
543 ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
544 if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
545 || (cachetime < kerneltime)) {
546 trycache = 0;
547 break;
548 }
549 ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
550 if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
551 && (cachetime < exttime)) {
552 trycache = 0;
553 break;
554 }
555 if (kerneltime > exttime) {
556 exttime = kerneltime;
557 }
558 if (cachetime != (exttime + 1)) {
559 trycache = 0;
560 break;
561 }
562 } while (0);
563
564 //trycache=0;
565
566 if (getValueForKey("-usecache", &val, &len, &bootInfo->bootConfig))
567trycache=1;
568
569 do {
570 if (trycache) {
571 bootFile = gBootKernelCacheFile;
572 verbose("Loading kernel cache %s\n", bootFile);
573 if ((gMacOSVersion[0] == '1') && (gMacOSVersion[1] == '0') && (gMacOSVersion[2] == '.') && (gMacOSVersion[3] >= '7'))
574 ret = LoadThinFatFile(bootFile, &binary);
575else {
576 ret = LoadFile(bootFile);
577 binary = (void *)kLoadAddr;
578}
579
580 if (ret >= 0)
581 break;
582
583verbose("Kernel cache did not loaded %s\n ", bootFile);
584 }
585
586 bootFile = bootInfo->bootFile;
587
588 // Try to load kernel image from alternate locations on boot helper partitions.
589 sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
590 ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
591 if (ret == -1)
592 {
593sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
594ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
595if (ret == -1)
596{
597sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
598ret = GetFileInfo(NULL, bootFileSpec, &flags, &time);
599if (ret == -1)
600{
601// Not found any alternate locations, using the original kernel image path.
602strcpy(bootFileSpec, bootFile);
603}
604}
605 }
606 if ((gMacOSVersion[0] == '1') && (gMacOSVersion[1] == '0') && (gMacOSVersion[2] == '.') && (gMacOSVersion[3] >= '7'))
607 {
608 //Lion, dont load kernel if haz cache
609 if (!trycache) {
610 verbose("Loading kernel %s\n", bootFileSpec);
611 ret = LoadThinFatFile(bootFileSpec, &binary);
612 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
613 {
614 archCpuType = CPU_TYPE_I386;
615 ret = LoadThinFatFile(bootFileSpec, &binary);
616 }
617 } else ret = 1;
618 } else {
619 //Snow leopard or older
620 verbose("Loading kernel %s\n", bootFileSpec);
621 ret = LoadThinFatFile(bootFileSpec, &binary);
622 if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
623 {
624 archCpuType = CPU_TYPE_I386;
625 ret = LoadThinFatFile(bootFileSpec, &binary);
626 }
627 }
628
629 } while (0);
630
631 clearActivityIndicator();
632#if DEBUG
633 printf("Pausing...");
634 sleep(8);
635#endif
636
637 if (ret <= 0) {
638printf("Can't find %s\n", bootFile);
639
640sleep(1);
641
642 if (gBootFileType == kNetworkDeviceType) {
643 // Return control back to PXE. Don't unload PXE base code.
644 gUnloadPXEOnExit = false;
645 break;
646 }
647 } else {
648 /* Won't return if successful. */
649 ret = ExecKernel(binary);
650 }
651 }
652
653 // chainboot
654 if (status==1) {
655if (getVideoMode() == GRAPHICS_MODE) {// if we are already in graphics-mode,
656setVideoMode(VGA_TEXT_MODE, 0);// switch back to text mode
657}
658 }
659
660 if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
661nbpUnloadBaseCode();
662 }
663}
664
665/*!
666 Selects a new BIOS device, taking care to update the global state appropriately.
667 */
668/*
669 static void selectBiosDevice(void)
670 {
671 struct DiskBVMap *oldMap = diskResetBootVolumes(gBIOSDev);
672 CacheReset();
673 diskFreeMap(oldMap);
674 oldMap = NULL;
675
676 int dev = selectAlternateBootDevice(gBIOSDev);
677
678 BVRef bvchain = scanBootVolumes(dev, 0);
679 BVRef bootVol = selectBootVolume(bvchain);
680 gBootVolume = bootVol;
681 setRootVolume(bootVol);
682 gBIOSDev = dev;
683 }
684 */
685
686static bool getOSVersion(char *str)
687{
688bool valid = false;
689config_file_t systemVersion;
690const char *val;
691int len;
692
693if (!loadConfigFile("System/Library/CoreServices/SystemVersion.plist", &systemVersion))
694{
695valid = true;
696}
697else if (!loadConfigFile("System/Library/CoreServices/ServerVersion.plist", &systemVersion))
698{
699valid = true;
700}
701
702if (valid)
703{
704if (getValueForKey(kProductVersion, &val, &len, &systemVersion))
705{
706// getValueForKey uses const char for val
707// so copy it and trim
708*str = '\0';
709strncat(str, val, MIN(len, 4));
710}
711else
712valid = false;
713}
714
715return valid;
716}
717
718#define BASE 65521L /* largest prime smaller than 65536 */
719#define NMAX 5000
720// NMAX (was 5521) the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
721
722#define DO1(buf,i) {s1 += buf[i]; s2 += s1;}
723#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
724#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
725#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
726#define DO16(buf) DO8(buf,0); DO8(buf,8);
727
728unsigned long Adler32(unsigned char *buf, long len)
729{
730 unsigned long s1 = 1; // adler & 0xffff;
731 unsigned long s2 = 0; // (adler >> 16) & 0xffff;
732 unsigned long result;
733 int k;
734
735 while (len > 0) {
736 k = len < NMAX ? len : NMAX;
737 len -= k;
738 while (k >= 16) {
739 DO16(buf);
740 buf += 16;
741 k -= 16;
742 }
743 if (k != 0) do {
744 s1 += *buf++;
745 s2 += s1;
746 } while (--k);
747 s1 %= BASE;
748 s2 %= BASE;
749 }
750 result = (s2 << 16) | s1;
751 return OSSwapHostToBigInt32(result);
752}
753

Archive Download this file

Revision: 755