Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 1184