Chameleon

Chameleon Svn Source Tree

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

Archive Download this file

Revision: 1310