Index: branches/cparm/TODO =================================================================== --- branches/cparm/TODO (revision 1971) +++ branches/cparm/TODO (revision 1972) @@ -1,23 +1,23 @@ TODO List for Chameleon Boot Loader ==================================== -- update cpu_intel_amd - split nvidia, gma and ati code into separate modules +- move device_inject, winfs, bsdfs, ext2fs, befs, and the command lspci, memory, more and video into modules +- Implement a pool allocator, so each module will run and allocate memory in there own pool, de-alloc all allocated memory by the module, + will be done simply by destroying the pool +- Implement snprintf to avoid buffer overflow in some case + - implement cpu topology - Backport cconfig from the trunk -- move winfs, bsdfs, ext2fs, befs and lspci into modules +- update cpu_intel_amd - Implement a Host like in bits to avoid some return issues - update project with corehash -- Implement a pool allocator, so each module will run and allocate memory in there own pool, de-alloc all allocated memory by the module, - will be done simply by destroying the pool - Try to sync our prf() with the apple/mach __doprnt() (in Xnu/osfmk/kern/printf.c) to normalize the formating in our printf, sprintf, etc ..., and facilitate bug fixes -- Implement snprintf to avoid buffer overflow in some case - -- It seems that nvram variables must be set thru efiRuntimeServices->SetVariable(...), +NOTE: It seems that nvram variables must be set thru efiRuntimeServices->SetVariable(...), then, the /options node is filled by kernel depending on the Runtime Services. If true, this requires a more complete EFI implementation (perhaps in a module, or a kext). Index: branches/cparm/Chameleon.xcodeproj/project.pbxproj =================================================================== --- branches/cparm/Chameleon.xcodeproj/project.pbxproj (revision 1971) +++ branches/cparm/Chameleon.xcodeproj/project.pbxproj (revision 1972) @@ -213,7 +213,6 @@ AB43B2E514C37E520018D529 /* prf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = prf.c; sourceTree = ""; }; AB43B2E614C37E520018D529 /* printf.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = printf.c; sourceTree = ""; }; AB43B2E714C37E520018D529 /* qsort.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = qsort.c; sourceTree = ""; }; - AB43B2E814C37E520018D529 /* rand.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rand.c; sourceTree = ""; }; AB43B2E914C37E520018D529 /* setjmp.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = setjmp.s; sourceTree = ""; }; AB43B2EA14C37E520018D529 /* string.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = string.c; sourceTree = ""; }; AB43B2EB14C37E520018D529 /* strtol.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = strtol.c; sourceTree = ""; }; @@ -261,7 +260,6 @@ AB43B31714C37E520018D529 /* hfs_CaseTables.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hfs_CaseTables.h; sourceTree = ""; }; AB43B31814C37E520018D529 /* hfs_compare.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hfs_compare.c; sourceTree = ""; }; AB43B31914C37E520018D529 /* intel_acpi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = intel_acpi.h; sourceTree = ""; }; - AB43B31A14C37E520018D529 /* internal_modules.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = internal_modules.h; sourceTree = ""; }; AB43B31B14C37E520018D529 /* io_inline.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = io_inline.h; sourceTree = ""; }; AB43B31C14C37E520018D529 /* libsaio.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libsaio.h; sourceTree = ""; }; AB43B31D14C37E520018D529 /* load.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = load.c; sourceTree = ""; }; @@ -388,12 +386,10 @@ AB43B3A214C37E520018D529 /* Makefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = ""; }; AB43B3A414C37E520018D529 /* dram_controllers.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = dram_controllers.c; sourceTree = ""; }; AB43B3A514C37E520018D529 /* dram_controllers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = dram_controllers.h; sourceTree = ""; }; - AB43B3A614C37E520018D529 /* GPL_V2_LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = GPL_V2_LICENSE; sourceTree = ""; }; AB43B3A714C37E520018D529 /* Makefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.make; path = Makefile; sourceTree = ""; }; AB43B3A814C37E520018D529 /* mem.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = mem.c; sourceTree = ""; }; AB43B3A914C37E520018D529 /* mem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = mem.h; sourceTree = ""; }; AB43B3AA14C37E520018D529 /* Memory.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Memory.c; sourceTree = ""; }; - AB43B3AB14C37E520018D529 /* MEMTEST86_LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = MEMTEST86_LICENSE; sourceTree = ""; }; AB43B3AC14C37E520018D529 /* memvendors.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = memvendors.h; sourceTree = ""; }; AB43B3AD14C37E520018D529 /* README */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README; sourceTree = ""; }; AB43B3AE14C37E520018D529 /* spd.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = spd.c; sourceTree = ""; }; @@ -452,15 +448,18 @@ AB43B3F214C383120018D529 /* udivdi3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = udivdi3.c; sourceTree = ""; }; AB43B3F314C383120018D529 /* umoddi3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = umoddi3.c; sourceTree = ""; }; AB43B3F814C384040018D529 /* stack_protector.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = stack_protector.c; sourceTree = ""; }; - AB43B42A14C3A8080018D529 /* arc4random.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = arc4random.c; sourceTree = ""; }; AB79217514F38CF200F5EB39 /* bootXnu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = bootXnu.h; sourceTree = ""; }; AB79219214F3919E00F5EB39 /* ModuleHelp.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ModuleHelp.txt; sourceTree = ""; }; + ABA0C7BF1568190C003440AF /* arc4random-fbsd.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = "arc4random-fbsd.c"; sourceTree = ""; }; + ABA0C7C01568190C003440AF /* lib.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lib.c; sourceTree = ""; }; + ABA0C7C11568190C003440AF /* rtc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rtc.c; sourceTree = ""; }; + ABA0C7C21568190C003440AF /* time.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = time.c; sourceTree = ""; }; + ABAC08601568835800C89CC3 /* GPL_V2_LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = GPL_V2_LICENSE; sourceTree = ""; }; + ABAC08611568836C00C89CC3 /* MEMTEST86_LICENSE */ = {isa = PBXFileReference; lastKnownFileType = text; path = MEMTEST86_LICENSE; sourceTree = ""; }; ABB4CE7D151E39740053B64E /* lzss.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = lzss.c; sourceTree = ""; }; ABD521F114F9197900B62550 /* utarray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utarray.h; sourceTree = ""; }; ABD521F214F9197900B62550 /* uthash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = uthash.h; sourceTree = ""; }; ABD521F314F9197900B62550 /* uterror.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = uterror.c; sourceTree = ""; }; - ABD521F414F9197900B62550 /* utlist.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utlist.h; sourceTree = ""; }; - ABD521F514F9197900B62550 /* utstring.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = utstring.h; sourceTree = ""; }; ABD9A1FC150F706A008DA465 /* CoreHash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CoreHash.h; sourceTree = ""; }; ABD9A1FF150F80C4008DA465 /* CoreHash.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CoreHash.c; sourceTree = ""; }; ABE5FF4E14F9495500447F78 /* modules.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; lineEnding = 0; path = modules.c; sourceTree = ""; xcLanguageSpecificationIdentifier = xcode.lang.c; }; @@ -954,7 +953,6 @@ AB43B2E514C37E520018D529 /* prf.c */, AB43B2E614C37E520018D529 /* printf.c */, AB43B2E714C37E520018D529 /* qsort.c */, - AB43B2E814C37E520018D529 /* rand.c */, AB43B2E914C37E520018D529 /* setjmp.s */, AB43B2EA14C37E520018D529 /* string.c */, AB43B2EB14C37E520018D529 /* strtol.c */, @@ -966,13 +964,16 @@ AB43B2ED14C37E520018D529 /* libsaio */ = { isa = PBXGroup; children = ( + ABA0C7BF1568190C003440AF /* arc4random-fbsd.c */, + ABA0C7C01568190C003440AF /* lib.c */, + ABA0C7C11568190C003440AF /* rtc.c */, + ABA0C7C21568190C003440AF /* time.c */, ABB4CE7D151E39740053B64E /* lzss.c */, AB43B2EE14C37E520018D529 /* acpi.h */, AB43B2EF14C37E520018D529 /* acpi_tools.c */, AB43B2F014C37E520018D529 /* acpi_tools.h */, AB43B2F114C37E520018D529 /* allocate.c */, AB43B2F214C37E520018D529 /* apic.h */, - AB43B42A14C3A8080018D529 /* arc4random.c */, AB43B2F314C37E520018D529 /* asm.s */, AB43B2F414C37E520018D529 /* befs.c */, AB43B2F514C37E520018D529 /* befs.h */, @@ -1015,7 +1016,6 @@ AB43B31714C37E520018D529 /* hfs_CaseTables.h */, AB43B31814C37E520018D529 /* hfs_compare.c */, AB43B31914C37E520018D529 /* intel_acpi.h */, - AB43B31A14C37E520018D529 /* internal_modules.h */, AB43B31B14C37E520018D529 /* io_inline.h */, AB43B31C14C37E520018D529 /* libsaio.h */, AB43B31D14C37E520018D529 /* load.c */, @@ -1061,8 +1061,6 @@ ABD521F114F9197900B62550 /* utarray.h */, ABD521F214F9197900B62550 /* uthash.h */, ABD521F314F9197900B62550 /* uterror.c */, - ABD521F414F9197900B62550 /* utlist.h */, - ABD521F514F9197900B62550 /* utstring.h */, AB43B34114C37E520018D529 /* vbe.c */, AB43B34214C37E520018D529 /* vbe.h */, AB43B34314C37E520018D529 /* xml.c */, @@ -1259,12 +1257,12 @@ children = ( AB43B3A414C37E520018D529 /* dram_controllers.c */, AB43B3A514C37E520018D529 /* dram_controllers.h */, - AB43B3A614C37E520018D529 /* GPL_V2_LICENSE */, + ABAC08601568835800C89CC3 /* GPL_V2_LICENSE */, AB43B3A714C37E520018D529 /* Makefile */, AB43B3A814C37E520018D529 /* mem.c */, AB43B3A914C37E520018D529 /* mem.h */, AB43B3AA14C37E520018D529 /* Memory.c */, - AB43B3AB14C37E520018D529 /* MEMTEST86_LICENSE */, + ABAC08611568836C00C89CC3 /* MEMTEST86_LICENSE */, AB43B3AC14C37E520018D529 /* memvendors.h */, AB43B3AD14C37E520018D529 /* README */, AB43B3AE14C37E520018D529 /* spd.c */, Index: branches/cparm/CHANGES =================================================================== --- branches/cparm/CHANGES (revision 1971) +++ branches/cparm/CHANGES (revision 1972) @@ -1,3 +1,13 @@ +- security and stability fixes +- Improved Xcode4.3+ and clang compatibility +- Fixed a bug in device_inject.c +- Updated uthash, utarrey, etc ... to v1.9.6 +- Replaced arc4random by the freebsd version (found in darwin's libc) +(also Removed others random generators since the pseudo-random generator now work perfectly ) +- Implemented gettimeofday taken from libpayload +- finaly back to safe_malloc +- Sync'd the cpu legacy method to the trunk + - Implemented the Runtime Bundles Modules - Updated nvidia and ati device id - Small security fixes Index: branches/cparm/i386/libsaio/arc4random.c =================================================================== --- branches/cparm/i386/libsaio/arc4random.c (revision 1971) +++ branches/cparm/i386/libsaio/arc4random.c (revision 1972) @@ -1,277 +0,0 @@ - -#include "libsaio.h" - -/* - * License for L15_Swap, L15_InitState, L_SCHEDULE, L15_KSA, L15_Discard, L15, L15_Byte - * - * Copyright (c) 2004, 2005, 2006 Robin J Carey. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions, and the following disclaimer, - * without modification, immediately at the beginning of the file. - * 2. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR - * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - * $DragonFly: src/sys/kern/kern_nrandom.c,v 1.7 2008/08/01 04:42:30 dillon Exp $ - */ - -/* - * IMPORTANT NOTE: LByteType must be exactly 8-bits in size or this software - * will not function correctly. - */ -typedef unsigned char LByteType; -#define L15_STATE_SIZE 256 -static LByteType L15_x, L15_y; -static LByteType L15_start_x; -static LByteType L15_state[L15_STATE_SIZE]; - -/* - * PRIVATE FUNCS: - */ -static void L15(const LByteType * const key, const size_t keyLen); -static void L15_Swap(const LByteType pos1, const LByteType pos2); -static void L15_InitState(void); -static void L15_KSA(const LByteType * const key, - const size_t keyLen); -static void L15_Discard(const LByteType numCalls); -/* - * PUBLIC INTERFACE: - */ -static LByteType L15_Byte(void); - -static __inline void -L15_Swap(const LByteType pos1, const LByteType pos2) -{ - const LByteType save1 = L15_state[pos1]; - - L15_state[pos1] = L15_state[pos2]; - L15_state[pos2] = save1; -} - -static void -L15_InitState (void) -{ - size_t i; - for (i = 0; i < L15_STATE_SIZE; ++i) - L15_state[i] = i; -} - -#define L_SCHEDULE(xx) \ - \ -for (i = 0; i < L15_STATE_SIZE; ++i) { \ - L15_Swap(i, (stateIndex += (L15_state[i] + (xx)))); \ -} - -static void -L15_KSA (const LByteType * const key, const size_t keyLen) -{ - size_t i, keyIndex; - LByteType stateIndex = 0; - - L_SCHEDULE(keyLen); - for (keyIndex = 0; keyIndex < keyLen; ++keyIndex) { - L_SCHEDULE(key[keyIndex]); - } -} - -static void -L15_Discard(const LByteType numCalls) -{ - LByteType i; - for (i = 0; i < numCalls; ++i) { - (void)L15_Byte(); - } -} - -/* - * PUBLIC INTERFACE: - */ -static void -L15(const LByteType * const key, const size_t keyLen) -{ - L15_x = L15_start_x = 0; - L15_y = L15_STATE_SIZE - 1; - L15_InitState(); - L15_KSA(key, keyLen); - L15_Discard(L15_Byte()); -} - -static LByteType -L15_Byte(void) -{ - LByteType z; - - L15_Swap(L15_state[L15_x], L15_y); - z = (L15_state [L15_x++] + L15_state[L15_y--]); - if (L15_x == L15_start_x) { - --L15_y; - } - return (L15_state[z]); -} - - - -/*- - * THE BEER-WARE LICENSE - * - * wrote this file. As long as you retain this notice you - * can do whatever you want with this stuff. If we meet some day, and you - * think this stuff is worth it, you can buy me a beer in return. - * - * Dan Moschuk - * - * $FreeBSD: src/sys/libkern/arc4random.c,v 1.3.2.2 2001/09/17 07:06:50 silby Exp $ - */ - - -#define ARC4_MAXRUNS 16384 -#define ARC4_RESEED_SECONDS 300 * 18 -#define ARC4_KEYBYTES 32 /* 256 bit key */ - -static u_int8_t arc4_i, arc4_j; -static int arc4_initialized = 0; -static int arc4_numruns = 0; -static u_int8_t arc4_sbox[256]; -static u_int32_t arc4_tv_nextreseed; - -static u_int8_t arc4_randbyte(void); - -static __inline void -arc4_swap(u_int8_t *a, u_int8_t *b) -{ - u_int8_t c; - - c = *a; - *a = *b; - *b = c; -} - -/* - * Stir our S-box. - */ -static void -arc4_randomstir (void) -{ - u_int8_t key[256]; - int r, n; - - /* - * XXX read_random() returns unsafe numbers if the entropy - * device is not loaded -- MarkM. - */ - - { - for (r = 0; r < ARC4_KEYBYTES; ++r) - ((u_char *)key)[r] = L15_Byte(); - } - - /* If r == 0 || -1, just use what was on the stack. */ - if (r > 0) - { - for (n = r; n < sizeof(key); n++) - key[n] = key[n % r]; - } - - for (n = 0; n < 256; n++) - { - arc4_j = (arc4_j + arc4_sbox[n] + key[n]) % 256; - arc4_swap(&arc4_sbox[n], &arc4_sbox[arc4_j]); - } - arc4_i = arc4_j = 0; - - /* Reset for next reseed cycle. */ - arc4_tv_nextreseed = time18(); - arc4_tv_nextreseed += ARC4_RESEED_SECONDS; - arc4_numruns = 0; -} - -/* - * Initialize our S-box to its beginning defaults. - */ -void -arc4_init(void) -{ - int n; - - u_int32_t now = time18(); - L15((const LByteType *)&now, sizeof(u_int32_t)); - - arc4_i = arc4_j = 0; - for (n = 0; n < 256; n++) - arc4_sbox[n] = (u_int8_t) n; - - arc4_randomstir(); - arc4_initialized = 1; - - /* - * Throw away the first N words of output, as suggested in the - * paper "Weaknesses in the Key Scheduling Algorithm of RC4" - * by Fluher, Mantin, and Shamir. (N = 256 in our case.) - */ - for (n = 0; n < 256*4; n++) - arc4_randbyte(); -} - -/* - * Generate a random byte. - */ -static u_int8_t -arc4_randbyte(void) -{ - u_int8_t arc4_t; - - arc4_i = (arc4_i + 1) % 256; - arc4_j = (arc4_j + arc4_sbox[arc4_i]) % 256; - - arc4_swap(&arc4_sbox[arc4_i], &arc4_sbox[arc4_j]); - - arc4_t = (arc4_sbox[arc4_i] + arc4_sbox[arc4_j]) % 256; - return arc4_sbox[arc4_t]; -} - -void -arc4rand(void *ptr, u_int len, int reseed) -{ - u_char *p; - u_int32_t tv_now; - - /* Initialize array if needed. */ - if (!arc4_initialized) - arc4_init(); - - tv_now = time18(); - - if (reseed || - (arc4_numruns > ARC4_MAXRUNS) || - (tv_now > arc4_tv_nextreseed)) - arc4_randomstir(); - - arc4_numruns += len; - p = ptr; - while (len--) - *p++ = arc4_randbyte(); -} - -uint32_t -arc4random(void) -{ - uint32_t ret; - - arc4rand(&ret, sizeof ret, 0); - return ret; -} Index: branches/cparm/i386/libsaio/internal_modules.h =================================================================== --- branches/cparm/i386/libsaio/internal_modules.h (revision 1971) +++ branches/cparm/i386/libsaio/internal_modules.h (revision 1972) @@ -1,31 +0,0 @@ - - -#ifndef __INTERNAL_MODULES_H -#define __INTERNAL_MODULES_H - - - -static inline void load_all_internal_modules() -{ - // HOW TO: the procedure is quite simple but not automatic yet, - - // to embed a module just drag/copy the content your module folder (*.c,*.h, etc...), but DO NOT COPY THE MAKEFILE. - // into libsaio folder, edit the libsaio makefile to build the files that you just added, - // and add here some code to start the module, - - // ex. : - - //extern void ACPICodec_start(); - //ACPICodec_start(); - - //extern void SMBiosGetters_start(); - //SMBiosGetters_start(); - - //extern void GUI_start(); - //GUI_start(); - - // Done !!! - -} - -#endif /* __INTERNAL_MODULES_H */ \ No newline at end of file Index: branches/cparm/i386/libsaio/utstring.h =================================================================== --- branches/cparm/i386/libsaio/utstring.h (revision 1971) +++ branches/cparm/i386/libsaio/utstring.h (revision 1972) @@ -1,155 +0,0 @@ -/* -Copyright (c) 2008-2011, Troy D. Hanson http://uthash.sourceforge.net -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -/* a dynamic string implementation using macros - * see http://uthash.sourceforge.net/utstring - */ -#ifndef UTSTRING_H -#define UTSTRING_H - -#define UTSTRING_VERSION 1.9.4 - -#ifdef __GNUC__ -#define _UNUSED_ __attribute__ ((__unused__)) -#else -#define _UNUSED_ -#endif - -#include "libsaio.h" -#define oom() longjmp(h_buf_error,-1) - -typedef struct { - char *d; - size_t n; /* allocd size */ - size_t i; /* index of first unused byte */ -} UT_string; - -#define utstring_reserve(s,amt) \ -do { \ - if (((s)->n - (s)->i) < (size_t)(amt)) { \ - (s)->d = (char*)realloc((s)->d, (s)->n + amt); \ - if ((s)->d == NULL) oom(); \ - (s)->n += amt; \ - } \ -} while(0) - -#define utstring_init(s) \ -do { \ - (s)->n = 0; (s)->i = 0; (s)->d = NULL; \ - utstring_reserve(s,100); \ - (s)->d[0] = '\0'; \ -} while(0) - -#define utstring_done(s) \ -do { \ - if ((s)->d != NULL) free((s)->d); \ - (s)->n = 0; \ -} while(0) - -#define utstring_free(s) \ -do { \ - utstring_done(s); \ - free(s); \ -} while(0) - -#if 0 -#define utstring_new(s) \ -do { \ - s = (UT_string*)calloc(sizeof(UT_string),1); \ - if (!s) oom(); \ - utstring_init(s); \ -} while(0) -#else -#define utstring_new(s) \ -do { \ -s = (UT_string*)malloc(sizeof(UT_string)); \ -if (!s) oom(); \ -utstring_init(s); \ -} while(0) -#endif - -#define utstring_renew(s) \ -do { \ - if (s) { \ - utstring_clear(s); \ - } else { \ - utstring_new(s); \ - } \ -} while(0) - -#define utstring_clear(s) \ -do { \ - (s)->i = 0; \ - (s)->d[0] = '\0'; \ -} while(0) - -#define utstring_bincpy(s,b,l) \ -do { \ - utstring_reserve((s),(l)+1); \ - if (l) memcpy(&(s)->d[(s)->i], b, l); \ - (s)->i += l; \ - (s)->d[(s)->i]='\0'; \ -} while(0) - -#define utstring_concat(dst,src) \ -do { \ - utstring_reserve(dst,(src->i)+1); \ - if (src->i) memcpy(&(dst)->d[(dst)->i], src->d, src->i); \ - dst->i += src->i; \ - dst->d[dst->i]='\0'; \ -} while(0) - -#define utstring_len(s) ((unsigned)((s)->i)) - -#define utstring_body(s) ((s)->d) - -_UNUSED_ static void utstring_printf_va(UT_string *s, const char *fmt, va_list ap) { - int n; - va_list cp; - while (1) { -#ifdef _WIN32 - cp = ap; -#else - va_copy(cp, ap); -#endif - n = vsnprintf (&s->d[s->i], s->n-s->i, fmt, cp); - va_end(cp); - - if ((n > -1) && (n < (int)(s->n-s->i))) { - s->i += n; - return; - } - - /* Else try again with more space. */ - if (n > -1) utstring_reserve(s,n+1); /* exact */ - else utstring_reserve(s,(s->n)*2); /* 2x */ - } -} -_UNUSED_ static void utstring_printf(UT_string *s, const char *fmt, ...) { - va_list ap; - va_start(ap,fmt); - utstring_printf_va(s,fmt,ap); - va_end(ap); -} - -#endif /* UTSTRING_H */ Index: branches/cparm/i386/libsaio/utlist.h =================================================================== --- branches/cparm/i386/libsaio/utlist.h (revision 1971) +++ branches/cparm/i386/libsaio/utlist.h (revision 1972) @@ -1,522 +0,0 @@ -/* -Copyright (c) 2007-2011, Troy D. Hanson http://uthash.sourceforge.net -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS -IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER -OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#ifndef UTLIST_H -#define UTLIST_H - -#define UTLIST_VERSION 1.9.4 - -#include - -/* - * This file contains macros to manipulate singly and doubly-linked lists. - * - * 1. LL_ macros: singly-linked lists. - * 2. DL_ macros: doubly-linked lists. - * 3. CDL_ macros: circular doubly-linked lists. - * - * To use singly-linked lists, your structure must have a "next" pointer. - * To use doubly-linked lists, your structure must "prev" and "next" pointers. - * Either way, the pointer to the head of the list must be initialized to NULL. - * - * ----------------.EXAMPLE ------------------------- - * struct item { - * int id; - * struct item *prev, *next; - * } - * - * struct item *list = NULL: - * - * int main() { - * struct item *item; - * ... allocate and populate item ... - * DL_APPEND(list, item); - * } - * -------------------------------------------------- - * - * For doubly-linked lists, the append and delete macros are O(1) - * For singly-linked lists, append and delete are O(n) but prepend is O(1) - * The sort macro is O(n log(n)) for all types of single/double/circular lists. - */ - -/* These macros use decltype or the earlier __typeof GNU extension. - As decltype is only available in newer compilers (VS2010 or gcc 4.3+ - when compiling c++ code), this code uses whatever method is needed - or, for VS2008 where neither is available, uses casting workarounds. */ -#ifdef _MSC_VER /* MS compiler */ -#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ -#define LDECLTYPE(x) decltype(x) -#else /* VS2008 or older (or VS2010 in C mode) */ -#define NO_DECLTYPE -#define LDECLTYPE(x) char* -#endif -#else /* GNU, Sun and other compilers */ -#define LDECLTYPE(x) __typeof(x) -#endif - -/* for VS2008 we use some workarounds to get around the lack of decltype, - * namely, we always reassign our tmp variable to the list head if we need - * to dereference its prev/next pointers, and save/restore the real head.*/ -#ifdef NO_DECLTYPE -#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } -#define _NEXT(elt,list) ((char*)((list)->next)) -#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } -#define _PREV(elt,list) ((char*)((list)->prev)) -#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } -#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } -#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } -#else -#define _SV(elt,list) -#define _NEXT(elt,list) ((elt)->next) -#define _NEXTASGN(elt,list,to) ((elt)->next)=(to) -#define _PREV(elt,list) ((elt)->prev) -#define _PREVASGN(elt,list,to) ((elt)->prev)=(to) -#define _RS(list) -#define _CASTASGN(a,b) (a)=(b) -#endif - -/****************************************************************************** - * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * - * Unwieldy variable names used here to avoid shadowing passed-in variables. * - *****************************************************************************/ -#define LL_SORT(list, cmp) \ -do { \ - LDECLTYPE(list) _ls_p; \ - LDECLTYPE(list) _ls_q; \ - LDECLTYPE(list) _ls_e; \ - LDECLTYPE(list) _ls_tail; \ - LDECLTYPE(list) _ls_oldhead; \ - LDECLTYPE(list) _tmp; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _CASTASGN(_ls_p,list); \ - _CASTASGN(_ls_oldhead,list); \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else if (cmp(_ls_p,_ls_q) <= 0) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } \ - if (_ls_tail) { \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ - } else { \ - _CASTASGN(list,_ls_e); \ - } \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } else _tmp=NULL; /* quiet gcc unused variable warning */ \ -} while (0) - -#define DL_SORT(list, cmp) \ -do { \ - LDECLTYPE(list) _ls_p; \ - LDECLTYPE(list) _ls_q; \ - LDECLTYPE(list) _ls_e; \ - LDECLTYPE(list) _ls_tail; \ - LDECLTYPE(list) _ls_oldhead; \ - LDECLTYPE(list) _tmp; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _CASTASGN(_ls_p,list); \ - _CASTASGN(_ls_oldhead,list); \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else if (cmp(_ls_p,_ls_q) <= 0) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - } else { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - } \ - if (_ls_tail) { \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ - } else { \ - _CASTASGN(list,_ls_e); \ - } \ - _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - _CASTASGN(list->prev, _ls_tail); \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } else _tmp=NULL; /* quiet gcc unused variable warning */ \ -} while (0) - -#define CDL_SORT(list, cmp) \ -do { \ - LDECLTYPE(list) _ls_p; \ - LDECLTYPE(list) _ls_q; \ - LDECLTYPE(list) _ls_e; \ - LDECLTYPE(list) _ls_tail; \ - LDECLTYPE(list) _ls_oldhead; \ - LDECLTYPE(list) _tmp; \ - LDECLTYPE(list) _tmp2; \ - int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ - if (list) { \ - _ls_insize = 1; \ - _ls_looping = 1; \ - while (_ls_looping) { \ - _CASTASGN(_ls_p,list); \ - _CASTASGN(_ls_oldhead,list); \ - list = NULL; \ - _ls_tail = NULL; \ - _ls_nmerges = 0; \ - while (_ls_p) { \ - _ls_nmerges++; \ - _ls_q = _ls_p; \ - _ls_psize = 0; \ - for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ - _ls_psize++; \ - _SV(_ls_q,list); \ - if (_NEXT(_ls_q,list) == _ls_oldhead) { \ - _ls_q = NULL; \ - } else { \ - _ls_q = _NEXT(_ls_q,list); \ - } \ - _RS(list); \ - if (!_ls_q) break; \ - } \ - _ls_qsize = _ls_insize; \ - while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ - if (_ls_psize == 0) { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ - } else if (_ls_qsize == 0 || !_ls_q) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ - } else if (cmp(_ls_p,_ls_q) <= 0) { \ - _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ - if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ - } else { \ - _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ - if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ - } \ - if (_ls_tail) { \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ - } else { \ - _CASTASGN(list,_ls_e); \ - } \ - _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ - _ls_tail = _ls_e; \ - } \ - _ls_p = _ls_q; \ - } \ - _CASTASGN(list->prev,_ls_tail); \ - _CASTASGN(_tmp2,list); \ - _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list); \ - if (_ls_nmerges <= 1) { \ - _ls_looping=0; \ - } \ - _ls_insize *= 2; \ - } \ - } else _tmp=NULL; /* quiet gcc unused variable warning */ \ -} while (0) - -/****************************************************************************** - * singly linked list macros (non-circular) * - *****************************************************************************/ -#define LL_PREPEND(head,add) \ -do { \ - (add)->next = head; \ - head = add; \ -} while (0) - -#define LL_CONCAT(head1,head2) \ -do { \ - LDECLTYPE(head1) _tmp; \ - if (head1) { \ - _tmp = head1; \ - while (_tmp->next) { _tmp = _tmp->next; } \ - _tmp->next=(head2); \ - } else { \ - (head1)=(head2); \ - } \ -} while (0) - -#define LL_APPEND(head,add) \ -do { \ - LDECLTYPE(head) _tmp; \ - (add)->next=NULL; \ - if (head) { \ - _tmp = head; \ - while (_tmp->next) { _tmp = _tmp->next; } \ - _tmp->next=(add); \ - } else { \ - (head)=(add); \ - } \ -} while (0) - -#define LL_DELETE(head,del) \ -do { \ - LDECLTYPE(head) _tmp; \ - if ((head) == (del)) { \ - (head)=(head)->next; \ - } else { \ - _tmp = head; \ - while (_tmp->next && (_tmp->next != (del))) { \ - _tmp = _tmp->next; \ - } \ - if (_tmp->next) { \ - _tmp->next = ((del)->next); \ - } \ - } \ -} while (0) - -/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */ -#define LL_APPEND_VS2008(head,add) \ -do { \ - if (head) { \ - (add)->next = head; /* use add->next as a temp variable */ \ - while ((add)->next->next) { (add)->next = (add)->next->next; } \ - (add)->next->next=(add); \ - } else { \ - (head)=(add); \ - } \ - (add)->next=NULL; \ -} while (0) - -#define LL_DELETE_VS2008(head,del) \ -do { \ - if ((head) == (del)) { \ - (head)=(head)->next; \ - } else { \ - char *_tmp = (char*)(head); \ - while (head->next && (head->next != (del))) { \ - head = head->next; \ - } \ - if (head->next) { \ - head->next = ((del)->next); \ - } \ - { \ - char **_head_alias = (char**)&(head); \ - *_head_alias = _tmp; \ - } \ - } \ -} while (0) -#ifdef NO_DECLTYPE -#undef LL_APPEND -#define LL_APPEND LL_APPEND_VS2008 -#undef LL_DELETE -#define LL_DELETE LL_DELETE_VS2008 -#undef LL_CONCAT /* no LL_CONCAT_VS2008 */ -#undef DL_CONCAT /* no DL_CONCAT_VS2008 */ -#endif -/* end VS2008 replacements */ - -#define LL_FOREACH(head,el) \ - for(el=head;el;el=el->next) - -#define LL_FOREACH_SAFE(head,el,tmp) \ - for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) - -#define LL_SEARCH_SCALAR(head,out,field,val) \ -do { \ - LL_FOREACH(head,out) { \ - if ((out)->field == (val)) break; \ - } \ -} while(0) - -#define LL_SEARCH(head,out,elt,cmp) \ -do { \ - LL_FOREACH(head,out) { \ - if ((cmp(out,elt))==0) break; \ - } \ -} while(0) - -/****************************************************************************** - * doubly linked list macros (non-circular) * - *****************************************************************************/ -#define DL_PREPEND(head,add) \ -do { \ - (add)->next = head; \ - if (head) { \ - (add)->prev = (head)->prev; \ - (head)->prev = (add); \ - } else { \ - (add)->prev = (add); \ - } \ - (head) = (add); \ -} while (0) - -#define DL_APPEND(head,add) \ -do { \ - if (head) { \ - (add)->prev = (head)->prev; \ - (head)->prev->next = (add); \ - (head)->prev = (add); \ - (add)->next = NULL; \ - } else { \ - (head)=(add); \ - (head)->prev = (head); \ - (head)->next = NULL; \ - } \ -} while (0); - -#define DL_CONCAT(head1,head2) \ -do { \ - LDECLTYPE(head1) _tmp; \ - if (head2) { \ - if (head1) { \ - _tmp = (head2)->prev; \ - (head2)->prev = (head1)->prev; \ - (head1)->prev->next = (head2); \ - (head1)->prev = _tmp; \ - } else { \ - (head1)=(head2); \ - } \ - } \ -} while (0); - -#define DL_DELETE(head,del) \ -do { \ - assert((del)->prev != NULL); \ - if ((del)->prev == (del)) { \ - (head)=NULL; \ - } else if ((del)==(head)) { \ - (del)->next->prev = (del)->prev; \ - (head) = (del)->next; \ - } else { \ - (del)->prev->next = (del)->next; \ - if ((del)->next) { \ - (del)->next->prev = (del)->prev; \ - } else { \ - (head)->prev = (del)->prev; \ - } \ - } \ -} while (0); - - -#define DL_FOREACH(head,el) \ - for(el=head;el;el=el->next) - -/* this version is safe for deleting the elements during iteration */ -#define DL_FOREACH_SAFE(head,el,tmp) \ - for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) - -/* these are identical to their singly-linked list counterparts */ -#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR -#define DL_SEARCH LL_SEARCH - -/****************************************************************************** - * circular doubly linked list macros * - *****************************************************************************/ -#define CDL_PREPEND(head,add) \ -do { \ - if (head) { \ - (add)->prev = (head)->prev; \ - (add)->next = (head); \ - (head)->prev = (add); \ - (add)->prev->next = (add); \ - } else { \ - (add)->prev = (add); \ - (add)->next = (add); \ - } \ -(head)=(add); \ -} while (0) - -#define CDL_DELETE(head,del) \ -do { \ - if ( ((head)==(del)) && ((head)->next == (head))) { \ - (head) = 0L; \ - } else { \ - (del)->next->prev = (del)->prev; \ - (del)->prev->next = (del)->next; \ - if ((del) == (head)) (head)=(del)->next; \ - } \ -} while (0); - -#define CDL_FOREACH(head,el) \ - for(el=head;el;el=(el->next==head ? 0L : el->next)) - -#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ - for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL); \ - (el) && ((tmp2)=(el)->next, 1); \ - ((el) = (((el)==(tmp1)) ? 0L : (tmp2)))) - -#define CDL_SEARCH_SCALAR(head,out,field,val) \ -do { \ - CDL_FOREACH(head,out) { \ - if ((out)->field == (val)) break; \ - } \ -} while(0) - -#define CDL_SEARCH(head,out,elt,cmp) \ -do { \ - CDL_FOREACH(head,out) { \ - if ((cmp(out,elt))==0) break; \ - } \ -} while(0) - -#endif /* UTLIST_H */ - Index: branches/cparm/i386/libsaio/xml.c =================================================================== --- branches/cparm/i386/libsaio/xml.c (revision 1971) +++ branches/cparm/i386/libsaio/xml.c (revision 1972) @@ -39,7 +39,7 @@ else if (dict == DEFAULT_HELPER_CONFIG_DICT) \ dict = bootInfo->helperConfig.dictionary ; -string_ref *ref_strings = NULL; +static string_ref *ref_strings = NULL; /// TODO: remove below static char* buffer_start = NULL; Index: branches/cparm/i386/libsaio/uterror.c =================================================================== --- branches/cparm/i386/libsaio/uterror.c (revision 1971) +++ branches/cparm/i386/libsaio/uterror.c (revision 1972) @@ -9,7 +9,7 @@ #include "libsaio.h" -jmp_buf h_buf_error; +jmp_buf uterror; void init_ut_fnc(void) { Index: branches/cparm/i386/libsaio/console.c =================================================================== --- branches/cparm/i386/libsaio/console.c (revision 1971) +++ branches/cparm/i386/libsaio/console.c (revision 1972) @@ -48,17 +48,16 @@ #include "bootstruct.h" #include "platform.h" -//extern int vprf(const char * fmt, va_list ap); - -bool gVerboseMode; -bool gErrors; - /* Kabyl: BooterLog */ #define BOOTER_LOG_SIZE (128 * 1024) #define SAFE_LOG_SIZE 134 -char *msgbuf = 0; -char *cursor = 0; +struct LOG { + char *buf; + char *cursor; +}; +typedef struct LOG LOG; +static LOG booterlog; struct putc_info { char * str; @@ -78,62 +77,64 @@ void initBooterLog(void) { - msgbuf = malloc(BOOTER_LOG_SIZE); - if (!msgbuf) { + booterlog.buf = malloc(BOOTER_LOG_SIZE); + if (!booterlog.buf) { printf("Couldn't allocate buffer for booter log\n"); + booterlog.cursor = 0; + booterlog.buf = 0; return; } - bzero(msgbuf, BOOTER_LOG_SIZE); - cursor = msgbuf; - + bzero(booterlog.buf, BOOTER_LOG_SIZE); + booterlog.cursor = booterlog.buf; + } char *getConsoleMsg(void) { - return msgbuf; + return booterlog.buf; } char *getConsoleCursor(void) { - return cursor; + return booterlog.buf; } void setConsoleMsg(char *p) { - msgbuf = p; + booterlog.buf = p; } void setConsoleCursor(char *p) { - cursor = p; + booterlog.cursor = p; } - void msglog(const char * fmt, ...) { va_list ap; struct putc_info pi; - if (!msgbuf) + if (!booterlog.buf) return; - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((booterlog.cursor - booterlog.buf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) return; va_start(ap, fmt); - pi.str = cursor; + pi.str = booterlog.cursor; pi.last_str = 0; prf(fmt, ap, sputc, &pi); va_end(ap); - cursor += strlen((char *)cursor); + booterlog.cursor += strlen((char *)booterlog.cursor); } void setupBooterLog(void) { - if (!msgbuf) + if (!booterlog.buf) return; Node *node = DT__FindNode("/", false); if (node) - DT__AddProperty(node, "boot-log", strlen((char *)msgbuf) + 1, msgbuf); + DT__AddProperty(node, "boot-log", strlen((char *)booterlog.buf) + 1, booterlog.buf); } + /* Kabyl: !BooterLog */ @@ -191,15 +192,15 @@ /* Kabyl: BooterLog */ struct putc_info pi; - if (!msgbuf) + if (!booterlog.buf) return 0; - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((booterlog.cursor - booterlog.buf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) return 0; - pi.str = cursor; + pi.str = booterlog.cursor; pi.last_str = 0; prf(fmt, ap, sputc, &pi); - cursor += strlen((char *)cursor); + booterlog.cursor += strlen((char *)booterlog.cursor); } va_end(ap); @@ -212,7 +213,7 @@ va_list ap; va_start(ap, fmt); - if (gVerboseMode) + if (get_env(envgVerboseMode)) { prf(fmt, ap, putchar, 0); } @@ -221,15 +222,15 @@ /* Kabyl: BooterLog */ struct putc_info pi; - if (!msgbuf) + if (!booterlog.buf) return 0; - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((booterlog.cursor - booterlog.buf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) return 0; - pi.str = cursor; + pi.str = booterlog.cursor; pi.last_str = 0; prf(fmt, ap, sputc, &pi); - cursor += strlen((char *)cursor); + booterlog.cursor += strlen((char *)booterlog.cursor); } va_end(ap); @@ -240,12 +241,31 @@ int error(const char * fmt, ...) { va_list ap; - gErrors = true; + struct putc_info pi; + int len; + char *str = NULL; + va_start(ap, fmt); + len = prf(fmt, ap, 0, 0); + if (len > 0) + { + str = newEmptyStringWithLength(len); + if (str != NULL) + { + pi.last_str = 0; + + pi.str = str; + + prf(fmt, ap, sputc, &pi); + *pi.str = '\0'; + } + + } + va_end(ap); - prf(fmt, ap, putchar, 0); - - va_end(ap); + set_env_copy(envConsoleErr, str, len); + free(str); + return(0); } Index: branches/cparm/i386/libsaio/xml.h =================================================================== --- branches/cparm/i386/libsaio/xml.h (revision 1971) +++ branches/cparm/i386/libsaio/xml.h (revision 1972) @@ -47,8 +47,6 @@ }; typedef struct string_ref string_ref; -extern string_ref* ref_strings; - #define kXMLTagPList "plist " #define kXMLTagDict "dict" #define kXMLTagKey "key" @@ -83,6 +81,7 @@ #define kPropNSPrincipalClass ("NSPrincipalClass") #define kPropIOClass ("IOClass") #define kPropIOProviderClass ("IOProviderClass") +#define kPropOSBundleWorkspace ("OSBundleWorkspace") #define DEFAULT_BOOT_CONFIG_DICT (TagPtr)0 #define DEFAULT_SYSTEM_CONFIG_DICT (TagPtr)1 Index: branches/cparm/i386/libsaio/bootstruct.c =================================================================== --- branches/cparm/i386/libsaio/bootstruct.c (revision 1971) +++ branches/cparm/i386/libsaio/bootstruct.c (revision 1972) @@ -43,7 +43,7 @@ /* ... */ PrivateBootInfo_t *bootInfo = NULL; -Node *gMemoryMapNode = NULL; +//Node *gMemoryMapNode = NULL; static char platformName[64]; static MemoryRange memoryMap[kMemoryMapCountMax]; @@ -110,14 +110,15 @@ } } - gMemoryMapNode = DT__FindNode("/chosen/memory-map", true); + Node *gMemoryMapNode = DT__FindNode("/chosen/memory-map", true); set_env(envConvMem, convmem); set_env(envExtMem, extmem); set_env(envMemoryMap, (uint32_t)memoryMap); set_env(envMemoryMapCnt, memoryMapCount); + set_env(envMemoryMapNode, (uint32_t)gMemoryMapNode); + - init_done = 1; } Index: branches/cparm/i386/libsaio/vbe.c =================================================================== --- branches/cparm/i386/libsaio/vbe.c (revision 1971) +++ branches/cparm/i386/libsaio/vbe.c (revision 1972) @@ -76,9 +76,11 @@ } #endif +#if UNUSED + int getEDID( void * edidBlock, UInt8 block) { - bzero(&bb, sizeof(bb)); + bzero(&bb, sizeof(biosBuf_t)); bb.intno = 0x10; bb.eax.rr = funcGetEDID; bb.ebx.r.l= 0x01; @@ -93,7 +95,6 @@ -#if UNUSED /* * Default GTF parameter values. */ Index: branches/cparm/i386/libsaio/bootstruct.h =================================================================== --- branches/cparm/i386/libsaio/bootstruct.h (revision 1971) +++ branches/cparm/i386/libsaio/bootstruct.h (revision 1972) @@ -41,7 +41,7 @@ extern boot_args_107 *bootArgs107; extern boot_args_108 *bootArgs108; -extern Node *gMemoryMapNode; +//extern Node *gMemoryMapNode; #define VGA_TEXT_MODE 0 Index: branches/cparm/i386/libsaio/hfs.c =================================================================== --- branches/cparm/i386/libsaio/hfs.c (revision 1971) +++ branches/cparm/i386/libsaio/hfs.c (revision 1972) @@ -31,6 +31,7 @@ #include #include "hfs.h" +#include "platform.h" #define kBlockSize (0x200) @@ -76,9 +77,6 @@ #endif /* !__i386__ */ -unsigned long HFSLoadVerbose = 1; - - static long ReadFile(void *file, uint64_t *length, void *base, uint64_t offset); static long GetCatalogEntryInfo(void *entry, long *flags, long *time, FinderInfo *finderInfo, long *infoValid); @@ -261,7 +259,8 @@ long HFSLoadFile(CICell ih, char * filePath) { - return HFSReadFile(ih, filePath, (void *)gFSLoadAddress, 0, 0); + //return HFSReadFile(ih, filePath, (void *)gFSLoadAddress, 0, 0); + return HFSReadFile(ih, filePath, (void *)(uint32_t)get_env(envgFSLoadAddress), 0, 0); } long HFSReadFile(CICell ih, char * filePath, void *base, uint64_t offset, uint64_t length) @@ -304,11 +303,11 @@ getDeviceDescription(ih, devStr); - if (HFSLoadVerbose) { + if (get_env(envHFSLoadVerbose)) { verbose("Read HFS%s file: [%s/%s] %d bytes.\n", (gIsHFSPlus ? "+" : ""), devStr, filePath, (uint32_t)length); - } else if (HFSLoadVerbose == 0) { - HFSLoadVerbose = 1; + } else if (get_env(envHFSLoadVerbose) == 0) { + safe_set_env(envHFSLoadVerbose, 1); } return length; Index: branches/cparm/i386/libsaio/vbe.h =================================================================== --- branches/cparm/i386/libsaio/vbe.h (revision 1971) +++ branches/cparm/i386/libsaio/vbe.h (revision 1972) @@ -230,7 +230,7 @@ * CRTC information block passed to function 4F02 * to override default refresh rate. */ -#pragma pack(1) +//#pragma pack(1) typedef struct { unsigned short HTotal; @@ -243,9 +243,9 @@ unsigned long PixelClock; /* in Hz */ unsigned short RefreshRate; /* units of 0.01 Hz */ unsigned char Reserved[40]; -} VBECRTCInfoBlock; +} __attribute__((packed)) VBECRTCInfoBlock; -#pragma pack() +//#pragma pack() /* * Defined flags for 'Flags' field in VBECRTCInfoBlock. Index: branches/cparm/i386/libsaio/allocate.c =================================================================== --- branches/cparm/i386/libsaio/allocate.c (revision 1971) +++ branches/cparm/i386/libsaio/allocate.c (revision 1972) @@ -26,6 +26,7 @@ #include "saio_internal.h" #include "bootstruct.h" #include "device_tree.h" +#include "platform.h" static long gImageLastKernelAddr; @@ -48,7 +49,7 @@ buffer[0] = start; buffer[1] = length; - DT__AddProperty(gMemoryMapNode, nameBuf, 2 * sizeof(uint32_t), (char *)buffer); + DT__AddProperty((Node*)(uint32_t)get_env(envMemoryMapNode), nameBuf, 2 * sizeof(uint32_t), (char *)buffer); return 0; } Index: branches/cparm/i386/libsaio/libsaio.h =================================================================== --- branches/cparm/i386/libsaio/libsaio.h (revision 1971) +++ branches/cparm/i386/libsaio/libsaio.h (revision 1972) @@ -31,7 +31,6 @@ #include "io_inline.h" #include "saio_types.h" #include "saio_internal.h" -#include "internal_modules.h" #include "uthash.h" #endif /* !__LIBSAIO_LIBSAIO_H */ Index: branches/cparm/i386/libsaio/Makefile =================================================================== --- branches/cparm/i386/libsaio/Makefile (revision 1971) +++ branches/cparm/i386/libsaio/Makefile (revision 1972) @@ -14,7 +14,7 @@ CFLAGS = $(RC_CFLAGS) $(OPTIM) $(MORECPP) -arch i386 -g -Wmost -fno-stack-protector \ -D__ARCHITECTURE__=\"i386\" -DSAIO_INTERNAL_USER \ -DRCZ_COMPRESSED_FILE_SUPPORT $(DEBUG) \ - -fno-builtin -static $(OMIT_FRAME_POINTER_CFLAG) -march=pentium4 -msse2 -msoft-float -ffreestanding -mpreferred-stack-boundary=2 -fno-align-functions -mfpmath=sse + -fno-builtin -static $(OMIT_FRAME_POINTER_CFLAG) -march=pentium4 -msse2 -msoft-float -Qunused-arguments -ffreestanding -DBOOT_CORE -mpreferred-stack-boundary=2 -fno-align-functions -mfpmath=sse DEFINES= CONFIG = hd @@ -31,7 +31,7 @@ VPATH = $(OBJROOT):$(SYMROOT) -SAIO_OBJS = table.o asm.o bios.o biosfn.o arc4random.o \ +SAIO_OBJS = table.o asm.o bios.o biosfn.o arc4random-fbsd.o \ disk.o sys.o cache.o bootstruct.o \ stringTable.o load.o pci.o allocate.o misc.o \ vbe.o hfs.o hfs_compare.o \ @@ -39,23 +39,8 @@ cpu.o platform.o \ fake_efi.o \ device_inject.o pci_root.o \ - convert.o acpi_tools.o smbios.o uterror.o lzss.o + convert.o acpi_tools.o smbios.o uterror.o lzss.o lib.o rtc.o time.o -# example for AcpiCodec -#SAIO_OBJS += acpi_codec.o acpicode.o ACPICodec.o acpidecode.o - -# example for AcpiPatcher -#SAIO_OBJS += aml_generator.o acpi_patcher.o AcpiPatcher.o - -# example for GE -#SAIO_OBJS += nvidia.o ati.o gma.o GraphicsEnabler.o - -# example for SMBiosGetters -#SAIO_OBJS += mysmbios.o smbios_decode.o smbios_getters.o SMBiosGetters.o - -# example for GUI -#SAIO_OBJS += graphic_utils.o gui.o picopng.o GUI_module.o - # Options enabled by default: #CFLAGS += -DNO_WIN_SUPPORT # -7744 bytes SAIO_OBJS += ntfs.o msdos.o exfat.o Index: branches/cparm/i386/libsaio/ufs.c =================================================================== --- branches/cparm/i386/libsaio/ufs.c (revision 1971) +++ branches/cparm/i386/libsaio/ufs.c (revision 1972) @@ -194,7 +194,9 @@ long UFSLoadFile( CICell ih, char * filePath ) { - return UFSReadFile(ih, filePath, (void *)gFSLoadAddress, 0, 0); + //return UFSReadFile(ih, filePath, (void *)gFSLoadAddress, 0, 0); + return UFSReadFile(ih, filePath, (void *)(uint32_t)get_env(envgFSLoadAddress), 0, 0); + } long UFSReadFile( CICell ih, char * filePath, void * base, uint64_t offset, uint64_t length ) Index: branches/cparm/i386/libsaio/time.c =================================================================== --- branches/cparm/i386/libsaio/time.c (revision 0) +++ branches/cparm/i386/libsaio/time.c (revision 1972) @@ -0,0 +1,137 @@ +/* + * This file is part of the libpayload project. + * + * Copyright (C) 2008 Advanced Micro Devices, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/** + * @file libc/time.c + * General time functions + */ +#include "libsaio.h" +#include "cpu.h" +#include "platform.h" + + +static uint32_t cpu_khz; + +static struct { + uint64_t ticks; + time_t secs; + suseconds_t usecs; +} private_clock; + +#define TICKS_PER_SEC (cpu_khz * 1000) +#define TICKS_PER_USEC (cpu_khz / 1000) + +static void update_clock(void) +{ + uint64_t delta = rdtsc64() - private_clock.ticks; + int secs; + + private_clock.ticks += delta; + + secs = (int) (delta / TICKS_PER_SEC); + private_clock.secs += secs; + delta -= (secs * TICKS_PER_SEC); + private_clock.usecs += (int) (delta / TICKS_PER_USEC); + + if (private_clock.usecs > 1000000) { + private_clock.usecs -= 1000000; + private_clock.secs++; + } +} + +static unsigned int day_of_year(int mon, int day, int year) +{ + static uint8_t mdays[12] = { 31, 28, 31, 30, 31, 30, + 31, 31, 30, 31, 30, 31 }; + + int i, ret = 0; + + for(i = 0; i < mon; i++) { + ret += mdays[i]; + + if (i == 1 && (year % 4)) + ret++; + } + + return (ret + day); +} + +static void gettimeofday_init(void) +{ + int days, delta; + struct tm tm; + + rtc_read_clock(&tm); + private_clock.ticks = rdtsc64(); + + /* Calculate the number of days in the year so far */ + days = day_of_year(tm.tm_mon, tm.tm_mday, tm.tm_year + 1900); + + delta = tm.tm_year - 70; + + days += (delta * 365); + + /* Figure leap years */ + + if (delta > 2) + days += (delta - 2) / 4; + + private_clock.secs = (days * 86400) + (tm.tm_hour * 3600) + + (tm.tm_min * 60) + tm.tm_sec; +} + +/** + * Return the current time broken into a timeval structure. + * + * @param tv A pointer to a timeval structure. + * @param tz Added for compatability - not used. + * @return 0 for success (this function cannot return non-zero currently). + * + * WARNING : In this implemetation gettimeofday() WILL NOT WORK until the cpu is initialized. + */ +int gettimeofday(struct timeval *tv, void *tz) +{ + cpu_khz = (uint32_t)(get_env(envCPUFreq) / 1000); + if (!(cpu_khz>0)) { + return 1; + } + /* + * Call the gtod init when we need it - this keeps the code from + * being included in the binary if we don't need it. + */ + if (!private_clock.ticks) + gettimeofday_init(); + + update_clock(); + + tv->tv_sec = private_clock.secs; + tv->tv_usec = private_clock.usecs; + + return 0; +} Index: branches/cparm/i386/libsaio/modules.c =================================================================== --- branches/cparm/i386/libsaio/modules.c (revision 1971) +++ branches/cparm/i386/libsaio/modules.c (revision 1972) @@ -179,68 +179,57 @@ if (is_system_loaded() != EFI_SUCCESS) return; - struct dirstuff* moduleDir = opendir("/Extra/modules/"); + long ret, length, flags, time, bundleType; + long long index; + long result = -1; + const char * name; void (*module_start)(void); - while(readdir(moduleDir, (const char**)&name, &flags, &time) >= 0) - { - if ((strcmp("Symbols.dylib",name)) == 0) continue; // if we found Symbols.dylib, just skip it + + DBG("FileLoadBundles in %s\n",dirSpec); + + index = 0; + while (1) { + ret = GetDirEntry("/Extra/modules/", &index, &name, &flags, &time); + if (ret == -1) break; + // Make sure this is not a directory. + if ((flags & kFileTypeMask) == kFileTypeDirectory) continue; + + if ((strcmp("Symbols.dylib",name)) == 0) continue; // if we found Symbols.dylib, just skip it + if (is_dylib_loaded(name) == EFI_SUCCESS) continue; + + + // Make sure this is a kext. + length = strlen(name); + if (strcmp(name + length - 6, ".dylib")) continue; - int len = strlen(name); - int ext_size = sizeof("dylib"); - - if (len >= ext_size) - { - if(strcmp(&name[len - ext_size], ".dylib") == 0) - { - char *tmp = newStringWithFormat("/Extra/modules/%s",name); - if (!tmp) { - continue; - } - char *dylib_name = newString(name); - if (!dylib_name) { - free(tmp); - continue; - } - msglog("* Attempting to load module: %s\n", tmp); - module_start = (void*)load_module(dylib_name,tmp); - - if(module_start && ( module_start != (void*)0xFFFFFFFF)) - { - add_dylib(name); - module_start(); - } - else - { - // failed to load or already loaded - free(tmp); - free(dylib_name); - - } - } -#if DEBUG_MODULES - else - { - DBG("Ignoring %s\n", name); - } -#endif - } -#if DEBUG_MODULES - else - { - DBG("Ignoring %s\n", name); - } -#endif - - } + char *tmp = newStringWithFormat( "/Extra/modules/%s",name); + if (!tmp) { + continue; + } + char *dylib_name = newString(name); + if (!dylib_name) { + free(tmp); + continue; + } + msglog("* Attempting to load module: %s\n", tmp); + module_start = (void*)load_module(dylib_name,tmp); + + if(module_start && ( module_start != (void*)0xFFFFFFFF)) + { + add_dylib(name); + module_start(); + } + else + { + // failed to load or already loaded + free(tmp); + free(dylib_name); + + } + } - if (moduleDir) - { - closedir(moduleDir); - - } - #if DEBUG_MODULES print_symbol_list(); #endif @@ -1356,7 +1345,7 @@ char* binary = (char*)addr; if(addr != 0xFFFFFFFF) { - UInt32* jumpPointer = malloc(sizeof(UInt32*)); + UInt32* jumpPointer = malloc(sizeof(UInt32)); if (!jumpPointer) { return EFI_OUT_OF_RESOURCES; } @@ -1436,6 +1425,7 @@ long willLoad; TagPtr dict; TagPtr personalities; + //pool_t workspace; char *plistAddr; long plistLength; char *executablePath; @@ -1669,7 +1659,7 @@ ret = ParseXML(buffer, &module); if (ret != 0 ) { printf("Unable to read plist of %s",name); break; } - if (!module) break; // Should never happen but it will make the compiler happy + if (!module) {ret = -1;break;} // Should never happen but it will make the compiler happy // Allocate memory for the driver path and the plist. Index: branches/cparm/i386/libsaio/modules.h =================================================================== --- branches/cparm/i386/libsaio/modules.h (revision 1971) +++ branches/cparm/i386/libsaio/modules.h (revision 1972) @@ -59,9 +59,6 @@ #define SYS_CLASS "SYMS" #define SYSLIB_CLASS "SYS_LIB" -#define BundleHighPriority "high" -#define BundleNormalPriority "normal" -#define BundleLowPriority "low" /* * Modules Interface * execute_hook Index: branches/cparm/i386/libsaio/device_inject.c =================================================================== --- branches/cparm/i386/libsaio/device_inject.c (revision 1971) +++ branches/cparm/i386/libsaio/device_inject.c (revision 1972) @@ -129,7 +129,7 @@ numpaths = 0; break; } - device->pci_dev_path[numpaths].device = ascii_hex_to_int(buff); + device->pci_dev_path[numpaths].device = (uint8_t)strtoul(buff, NULL, 16); x += 3; // 0x curr = x; @@ -148,7 +148,7 @@ numpaths = 0; break; } - device->pci_dev_path[numpaths].function = ascii_hex_to_int(buff); // TODO: find dev from char *path + device->pci_dev_path[numpaths].function = (uint8_t)strtoul(buff, NULL, 16); // TODO: find dev from char *path numpaths++; } @@ -189,20 +189,17 @@ if(!string->entries) { - if((string->entries = (struct DevPropDevice**)malloc(sizeof(device)))== NULL) + if((string->entries = (struct DevPropDevice*)malloc(sizeof(struct DevPropDevice) * MAX_STRING_NUM_ENTRIES))== NULL) { free(device); return NULL; } } + struct DevPropDevice **string_entries_arrey = (struct DevPropDevice **) string->entries; - if((string->entries[string->numentries++] = (struct DevPropDevice*)malloc(sizeof(device)))== NULL) - { - free(device); - free(string->entries); - return NULL; - } - string->entries[string->numentries-1] = device; + string->numentries++; + + string_entries_arrey[string->numentries-1] = device; return device; } @@ -297,36 +294,38 @@ buffer += 24; int i = 0, x = 0; + struct DevPropDevice **string_entries_arrey = (struct DevPropDevice **) string->entries; + while(i < string->numentries) { - sprintf(buffer, "%08x%04x%04x", dp_swap32(string->entries[i]->length), - dp_swap16(string->entries[i]->numentries), string->entries[i]->WHAT2); + sprintf(buffer, "%08x%04x%04x", dp_swap32(string_entries_arrey[i]->length), + dp_swap16(string_entries_arrey[i]->numentries), string_entries_arrey[i]->WHAT2); buffer += 16; - sprintf(buffer, "%02x%02x%04x%08x%08x", string->entries[i]->acpi_dev_path.type, - string->entries[i]->acpi_dev_path.subtype, - dp_swap16(string->entries[i]->acpi_dev_path.length), - string->entries[i]->acpi_dev_path._HID, - dp_swap32(string->entries[i]->acpi_dev_path._UID)); + sprintf(buffer, "%02x%02x%04x%08x%08x", string_entries_arrey[i]->acpi_dev_path.type, + string_entries_arrey[i]->acpi_dev_path.subtype, + dp_swap16(string_entries_arrey[i]->acpi_dev_path.length), + string_entries_arrey[i]->acpi_dev_path._HID, + dp_swap32(string_entries_arrey[i]->acpi_dev_path._UID)); buffer += 24; - for(x=0;x < string->entries[i]->num_pci_devpaths; x++) + for(x=0;x < string_entries_arrey[i]->num_pci_devpaths; x++) { - sprintf(buffer, "%02x%02x%04x%02x%02x", string->entries[i]->pci_dev_path[x].type, - string->entries[i]->pci_dev_path[x].subtype, - dp_swap16(string->entries[i]->pci_dev_path[x].length), - string->entries[i]->pci_dev_path[x].function, - string->entries[i]->pci_dev_path[x].device); + sprintf(buffer, "%02x%02x%04x%02x%02x", string_entries_arrey[i]->pci_dev_path[x].type, + string_entries_arrey[i]->pci_dev_path[x].subtype, + dp_swap16(string_entries_arrey[i]->pci_dev_path[x].length), + string_entries_arrey[i]->pci_dev_path[x].function, + string_entries_arrey[i]->pci_dev_path[x].device); buffer += 12; } - sprintf(buffer, "%02x%02x%04x", string->entries[i]->path_end.type, - string->entries[i]->path_end.subtype, - dp_swap16(string->entries[i]->path_end.length)); + sprintf(buffer, "%02x%02x%04x", string_entries_arrey[i]->path_end.type, + string_entries_arrey[i]->path_end.subtype, + dp_swap16(string_entries_arrey[i]->path_end.length)); buffer += 8; - uint8_t *dataptr = string->entries[i]->data; - for(x = 0; (uint32_t)x < (string->entries[i]->length) - (24 + (6 * string->entries[i]->num_pci_devpaths)) ; x++) + uint8_t *dataptr = string_entries_arrey[i]->data; + for(x = 0; (uint32_t)x < (string_entries_arrey[i]->length) - (24 + (6 * string_entries_arrey[i]->num_pci_devpaths)) ; x++) { sprintf(buffer, "%02x", *dataptr++); buffer += 2; @@ -344,17 +343,20 @@ } int i; + + struct DevPropDevice **string_entries_arrey = (struct DevPropDevice **) string->entries; + for(i = 0; i < string->numentries; i++) { - if(string->entries[i]) + if(string_entries_arrey[i]) { - if(string->entries[i]->data) + if(string_entries_arrey[i]->data) { - free(string->entries[i]->data); - string->entries[i]->data = NULL; + free(string_entries_arrey[i]->data); + string_entries_arrey[i]->data = NULL; } - free(string->entries[i]); - string->entries[i] = NULL; + free(string_entries_arrey[i]); + string_entries_arrey[i] = NULL; } } Index: branches/cparm/i386/libsaio/device_inject.h =================================================================== --- branches/cparm/i386/libsaio/device_inject.h (revision 1971) +++ branches/cparm/i386/libsaio/device_inject.h (revision 1972) @@ -11,6 +11,7 @@ #define DP_ADD_TEMP_VAL(dev, val) devprop_add_value(dev, (char*)val[0], (uint8_t*)val[1], strlen(val[1]) + 1) #define DP_ADD_TEMP_VAL_DATA(dev, val) devprop_add_value(dev, (char*)val.name, (uint8_t*)val.data, val.size) #define MAX_PCI_DEV_PATHS 4 +#define MAX_STRING_NUM_ENTRIES 100 extern struct DevPropString *string; extern uint8_t *stringdata; @@ -68,7 +69,7 @@ uint32_t WHAT2; // 0x01000000 ? uint16_t numentries; uint16_t WHAT3; // 0x0000 ? - struct DevPropDevice **entries; + struct DevPropDevice *entries; }; char *efi_inject_get_devprop_string(uint32_t *len); Index: branches/cparm/i386/libsaio/sys.c =================================================================== --- branches/cparm/i386/libsaio/sys.c (revision 1971) +++ branches/cparm/i386/libsaio/sys.c (revision 1972) @@ -110,15 +110,8 @@ static struct iob iob[NFILES]; -void * gFSLoadAddress = 0; - -// Turbo - save what we think is our original BIOS boot volume if we have one 0xab -BVRef gBIOSBootVolume = NULL; -BVRef gBootVolume; - static BVRef newBootVolumeRef( int biosdev, int partno ); static int GetFreeFd(void); -static struct iob * iob_from_fdesc(int fdesc); static int open_bvr(BVRef bvr, const char *filePath); @@ -135,8 +128,8 @@ // Read file into load buffer. The data in the load buffer will be // overwritten by the next LoadFile() call. - gFSLoadAddress = (void *) LOAD_ADDR; - + safe_set_env(envgFSLoadAddress, (uint32_t)(void *)LOAD_ADDR); + fileSize = bvr->fs_loadfile(bvr, (char *)filePath); // Return the size of the file, or -1 if load failed. @@ -162,6 +155,7 @@ return LoadVolumeFile(bvr, filePath); } +#if UNUSED long ReadFileAtOffset(const char * fileSpec, void *buffer, uint64_t offset, uint64_t length) { const char *filePath; @@ -175,6 +169,7 @@ return bvr->fs_readfile(bvr, (char *)filePath, buffer, offset, length); } +#endif long LoadThinFatFile(const char *fileSpec, void **binary) { @@ -194,7 +189,7 @@ // Read file into load buffer. The data in the load buffer will be // overwritten by the next LoadFile() call. - gFSLoadAddress = (void *) LOAD_ADDR; + safe_set_env(envgFSLoadAddress, (uint32_t)(void *)LOAD_ADDR); readFile = bvr->fs_readfile; @@ -318,6 +313,8 @@ if (gMakeDirSpec == 0) gMakeDirSpec = (char *)malloc(1024); + if (!gMakeDirSpec) return -1; + if (!dirSpec) { long idx, len; @@ -367,7 +364,7 @@ // Return a pointer to an allocated 'iob' based on the file descriptor // provided. Returns NULL if the file descriptor given is invalid. -static struct iob * iob_from_fdesc(int fdesc) +struct iob * iob_from_fdesc(int fdesc) { register struct iob * io; @@ -408,7 +405,9 @@ } // Load entire file into memory. Unnecessary open() calls must be avoided. - gFSLoadAddress = io->i_buf; + //gFSLoadAddress = io->i_buf; + safe_set_env(envgFSLoadAddress, (uint32_t)(void *)io->i_buf); + io->i_filesize = bvr->fs_loadfile(bvr, (char *)filePath); if (io->i_filesize < 0) { close(fdesc); @@ -531,6 +530,7 @@ return io->i_filesize; } +#if UNUSED //========================================================================== struct dirstuff * opendir(const char * path) @@ -582,7 +582,6 @@ 0, 0); } -#if UNUSED long GetFSUUID(char *spec, char *uuidStr) { BVRef bvr; @@ -635,7 +634,6 @@ return fdesc; } -#endif //========================================================================== // lseek() - Reposition the byte offset of the file descriptor from the // beginning of the file. Returns the relocated offset. @@ -651,7 +649,7 @@ return offset; } -#if UNUSED + //========================================================================== // tell() - Returns the byte offset of the file descriptor. @@ -689,7 +687,6 @@ return count; } #if UNUSED - int writebyte(int fdesc, char value) { struct iob * io; @@ -760,7 +757,7 @@ const char * systemConfigDir() { - if (gBootFileType == kNetworkDeviceType) + if (get_env(envgBootFileType) == kNetworkDeviceType) return ""; return "/Library/Preferences/SystemConfiguration"; } @@ -769,8 +766,6 @@ //========================================================================== -int gBootFileType; - void scanBootVolumes( int biosdev, int * count ) { BVRef bvr = 0; @@ -782,13 +777,14 @@ bvr = nbpScanBootVolumes(biosdev, count); if (bvr != NULL) { - gBootFileType = kNetworkDeviceType; + safe_set_env(envgBootFileType, kNetworkDeviceType); } #endif } else { - gBootFileType = kBlockDeviceType; + safe_set_env(envgBootFileType, kBlockDeviceType); + } } @@ -880,7 +876,7 @@ // zhell -- Undo a regression that was introduced from r491 to 492. // if gBIOSBootVolume is set already, no change is required if ( (bvr->flags & (kBVFlagBootable|kBVFlagSystemVolume)) - && gBIOSBootVolume + && get_env(envgBIOSBootVolume) && (!filteredChain || (filteredChain && bvr->visible)) && (bvr->biosdev == gBIOSDev) ) { @@ -890,7 +886,7 @@ // zhell -- if gBIOSBootVolume is NOT set, we use the "if" statement // from r491, if ( bvr->flags & kBVFlagBootable - && ! gBIOSBootVolume + && !get_env(envgBIOSBootVolume)/*gBIOSBootVolume*/ && bvr->biosdev == gBIOSDev ) { bvr2 = bvr; @@ -943,11 +939,12 @@ void setBootGlobals(BVRef chain) { // Record default boot device. - gBootVolume = selectBootVolume(chain); + BVRef gBootVolume = selectBootVolume(chain); // turbo - Save the ORIGINAL boot volume too for loading our mkext - if (!gBIOSBootVolume) gBIOSBootVolume = gBootVolume; - + if (!get_env(envgBIOSBootVolume)) safe_set_env(envgBIOSBootVolume, (uint32_t)gBootVolume); + + safe_set_env(envgBootVolume, (uint32_t)gBootVolume); setRootVolume(gBootVolume); } @@ -1075,7 +1072,7 @@ if (biosdev == kPseudoBIOSDevBooter) { if (bvr1 == NULL ) - bvr1 = gBIOSBootVolume; + bvr1 = (BVRef)(uint32_t)get_env(envgBIOSBootVolume); } else { Index: branches/cparm/i386/libsaio/load.c =================================================================== --- branches/cparm/i386/libsaio/load.c (revision 1971) +++ branches/cparm/i386/libsaio/load.c (revision 1972) @@ -31,16 +31,13 @@ #include #include "sl.h" +#include "platform.h" static long DecodeSegment(long cmdBase, unsigned int*load_addr, unsigned int *load_size); static long DecodeUnixThread(long cmdBase, unsigned int *entry); static long DecodeSymbolTable(long cmdBase); +static unsigned long gBinaryAddress; - -unsigned long gBinaryAddress; -bool gHaveKernelCache; /* XXX aserebln: uninitialized? and only set to true, never to false */ -cpu_type_t archCpuType=CPU_TYPE_I386; - // Public Functions long ThinFatFile(void **binary, unsigned long *length) @@ -87,7 +84,7 @@ fapsize = fap->size; } - if (fapcputype == archCpuType) + if (fapcputype == get_env(envarchCpuType)) { *binary = (void *) ((unsigned long)*binary + fapoffset); size = fapsize; @@ -111,7 +108,7 @@ { struct mach_header *mH; mH = (struct mach_header *)(gBinaryAddress); - switch (archCpuType) + switch (get_env(envarchCpuType)) { case CPU_TYPE_I386: if (mH->magic != MH_MAGIC) @@ -276,7 +273,7 @@ } if (vmsize && (strcmp(segname, "__PRELINK") == 0 || strcmp(segname, "__PRELINK_INFO") == 0)) - gHaveKernelCache = true; + safe_set_env(envgHaveKernelCache, true); // Copy from file load area. if (vmsize>0 && filesize>0) @@ -294,7 +291,7 @@ static long DecodeUnixThread(long cmdBase, unsigned int *entry) { - switch (archCpuType) + switch (get_env(envarchCpuType)) { case CPU_TYPE_I386: { Index: branches/cparm/i386/libsaio/sl.h =================================================================== --- branches/cparm/i386/libsaio/sl.h (revision 1971) +++ branches/cparm/i386/libsaio/sl.h (revision 1972) @@ -60,9 +60,6 @@ #define Seek(c, p) diskSeek(c, p); #define Read(c, a, l) diskRead(c, a, l); -extern void * gFSLoadAddress; -extern cpu_type_t archCpuType; -extern unsigned long HFSLoadVerbose; -cpu_type_t detectCpuType (); +//extern void * gFSLoadAddress; #endif /* !__LIBSAIO_SL_H */ Index: branches/cparm/i386/libsaio/platform.c =================================================================== --- branches/cparm/i386/libsaio/platform.c (revision 1971) +++ branches/cparm/i386/libsaio/platform.c (revision 1972) @@ -20,6 +20,10 @@ #define DBG(x...) #endif +#ifndef DEBUG_PLATFORM_CPU +#define DEBUG_PLATFORM_CPU 0 +#endif + static char *gboardproduct = NULL; static char *gPlatformName = NULL; static char *gRootDevice = NULL; @@ -96,7 +100,7 @@ static struct env_struct *find_env(const char *name) { struct env_struct *var; - if (setjmp(h_buf_error) == -1) { + if (setjmp(uterror) == -1) { #if DEBUG_PLATFORM printf("find_env: Unable to find environement variable\n"); getc(); @@ -164,7 +168,7 @@ return; } - if (setjmp(h_buf_error) == -1) { + if (setjmp(uterror) == -1) { printf("_set_env: Unable to set environement variable"); // don't try to acces to the string 'name', //'cause we just returned from the longjump, stack as already changed state. #if DEBUG_PLATFORM @@ -320,7 +324,7 @@ static void delete_env(struct env_struct *var) { - if (setjmp(h_buf_error) == -1) { + if (setjmp(uterror) == -1) { printf("delete_env: Unable to delete environement variable\n"); #if DEBUG_PLATFORM getc(); @@ -345,7 +349,7 @@ void free_platform_env(void) { struct env_struct *current_var, *tmp; - if (setjmp(h_buf_error) == -1) { + if (setjmp(uterror) == -1) { printf("free_platform_env: Unable to delete all environement variables\n"); #if DEBUG_PLATFORM getc(); @@ -363,7 +367,7 @@ #if DEBUG_PLATFORM void debug_platform_env(void) { - struct env_struct *current_var = platform_env; + struct env_struct *current_var; for(current_var=platform_env;current_var;current_var=(struct env_struct*)(current_var->hh.next)) { #if DEBUG_PLATFORM >= 2 @@ -384,186 +388,53 @@ } #endif +void showError(void) +{ + struct env_struct *current_var; + for(current_var=platform_env;current_var;current_var=(struct env_struct*)(current_var->hh.next)) + { + if (strcmp(current_var->name, envConsoleErr) == 0) { + if (current_var->Type == kEnvPtr) { + printf("stderr: %s \n",(char*)(uint32_t)current_var->ptr); + } + } + } +} + /** Scan platform hardware information, called by the main entry point (common_boot() ) _before_ bootConfig xml parsing settings are loaded */ void scan_platform(void) { - //memset(&Platform, 0, sizeof(PlatformInfo_t)); build_pci_dt(); scan_cpu(); -#if DEBUG_PLATFORM - DBG("CPU: %s\n", (char*)get_env_ptr(envBrandString)); +#if DEBUG_PLATFORM_CPU + printf("CPU: %s\n", (char*)get_env_ptr(envBrandString)); if (get_env(envVendor) == CPUID_VENDOR_AMD) - DBG("CPU: Vendor/Model/ExtModel: 0x%x/0x%x/0x%x\n", (uint32_t)get_env(envVendor), (uint32_t)get_env(envModel), (uint32_t)get_env(envExtModel)); - DBG("CPU: Family/ExtFamily: 0x%x/0x%x\n", (uint32_t)get_env(envFamily), (uint32_t)get_env(envExtFamily)); + printf("CPU: Vendor/Model/ExtModel: 0x%x/0x%x/0x%x\n", (uint32_t)get_env(envVendor), (uint32_t)get_env(envModel), (uint32_t)get_env(envExtModel)); + printf("CPU: Family/ExtFamily: 0x%x/0x%x\n", (uint32_t)get_env(envFamily), (uint32_t)get_env(envExtFamily)); if (get_env(envVendor) == CPUID_VENDOR_AMD) { - DBG("CPU (AMD): TSCFreq: %dMHz\n", (uint32_t)(get_env(envTSCFreq) / 1000000)); - DBG("CPU (AMD): FSBFreq: %dMHz\n", (uint32_t)(get_env(envFSBFreq) / 1000000)); - DBG("CPU (AMD): CPUFreq: %dMHz\n", (uint32_t)(get_env(envCPUFreq) / 1000000)); - DBG("CPU (AMD): MaxCoef/CurrCoef: 0x%x/0x%x\n", (uint32_t)get_env(envMaxCoef), (uint32_t)get_env(envCurrCoef)); - DBG("CPU (AMD): MaxDiv/CurrDiv: 0x%x/0x%x\n", (uint32_t)get_env(envMaxDiv), (uint32_t)get_env(envCurrDiv)); + printf("CPU (AMD): TSCFreq: %dMHz\n", (uint32_t)(get_env(envTSCFreq) / 1000000)); + printf("CPU (AMD): FSBFreq: %dMHz\n", (uint32_t)(get_env(envFSBFreq) / 1000000)); + printf("CPU (AMD): CPUFreq: %dMHz\n", (uint32_t)(get_env(envCPUFreq) / 1000000)); + printf("CPU (AMD): MaxCoef/CurrCoef: 0x%x/0x%x\n", (uint32_t)get_env(envMaxCoef), (uint32_t)get_env(envCurrCoef)); + printf("CPU (AMD): MaxDiv/CurrDiv: 0x%x/0x%x\n", (uint32_t)get_env(envMaxDiv), (uint32_t)get_env(envCurrDiv)); } else if (get_env(envVendor) == CPUID_VENDOR_INTEL){ - DBG("CPU: TSCFreq: %dMHz\n", (uint32_t)(get_env(envTSCFreq) / 1000000)); - DBG("CPU: FSBFreq: %dMHz\n", (uint32_t)(get_env(envFSBFreq) / 1000000)); - DBG("CPU: CPUFreq: %dMHz\n", (uint32_t)(get_env(envCPUFreq) / 1000000)); - DBG("CPU: MaxCoef/CurrCoef: 0x%x/0x%x\n", (uint32_t)(get_env(envMaxCoef)), (uint32_t)(get_env(envCurrCoef))); - DBG("CPU: MaxDiv/CurrDiv: 0x%x/0x%x\n", (uint32_t)(get_env(envMaxDiv)), (uint32_t)(get_env(envCurrDiv))); + printf("CPU: TSCFreq: %dMHz\n", (uint32_t)(get_env(envTSCFreq) / 1000000)); + printf("CPU: FSBFreq: %dMHz\n", (uint32_t)(get_env(envFSBFreq) / 1000000)); + printf("CPU: CPUFreq: %dMHz\n", (uint32_t)(get_env(envCPUFreq) / 1000000)); + printf("CPU: MaxCoef/CurrCoef: 0x%x/0x%x\n", (uint32_t)(get_env(envMaxCoef)), (uint32_t)(get_env(envCurrCoef))); + printf("CPU: MaxDiv/CurrDiv: 0x%x/0x%x\n", (uint32_t)(get_env(envMaxDiv)), (uint32_t)(get_env(envCurrDiv))); } - DBG("CPU: NoCores/NoThreads: %d/%d\n", (uint32_t)(get_env(envNoCores)), (uint32_t)(get_env(envNoThreads))); - DBG("CPU: Features: 0x%08x\n", (uint32_t)(get_env(envFeatures))); - DBG("CPU: ExtFeatures: 0x%08x\n", (uint32_t)(get_env(envExtFeatures))); + printf("CPU: NoCores/NoThreads: %d/%d\n", (uint32_t)(get_env(envNoCores)), (uint32_t)(get_env(envNoThreads))); + printf("CPU: Features: 0x%08x\n", (uint32_t)(get_env(envFeatures))); + printf("CPU: ExtFeatures: 0x%08x\n", (uint32_t)(get_env(envExtFeatures))); #ifndef AMD_SUPPORT - DBG("CPU: MicrocodeVersion: %d\n", (uint32_t)(get_env(envMicrocodeVersion))); + printf("CPU: MicrocodeVersion: %d\n", (uint32_t)(get_env(envMicrocodeVersion))); #endif pause(); #endif -} - -#ifdef ShowCurrentDate - -// shamefully ripped to http://wiki.osdev.org/CMOS - -/* - * http://wiki.osdev.org/OSDev_Wiki:General_disclaimer - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#define CURRENT_YEAR 2012 // Change this each year! - -static int century_register = 0x00; // Set by ACPI table parsing code if possible(... in FADT table) - -enum { - cmos_address = 0x70, - cmos_data = 0x71 -}; - - -static int get_update_in_progress_flag() { - outb(cmos_address, 0x0A); - return (inb(cmos_data) & 0x80); -} - - -static unsigned char get_RTC_register(int reg) { - outb(cmos_address, reg); - return inb(cmos_data); -} - -static void read_rtc(EFI_TIME *time) { - unsigned char century; - unsigned char last_second; - unsigned char last_minute; - unsigned char last_hour; - unsigned char last_day; - unsigned char last_month; - unsigned char last_year; - unsigned char last_century; - unsigned char registerB; - - unsigned char second; - unsigned char minute; - unsigned char hour; - unsigned char day; - unsigned char month; - unsigned int year; - // Note: This uses the "read registers until you get the same values twice in a row" technique - // to avoid getting dodgy/inconsistent values due to RTC updates - - while (get_update_in_progress_flag()); // Make sure an update isn't in progress - second = get_RTC_register(0x00); - minute = get_RTC_register(0x02); - hour = get_RTC_register(0x04); - day = get_RTC_register(0x07); - month = get_RTC_register(0x08); - year = get_RTC_register(0x09); - if(century_register != 0) { - century = get_RTC_register(century_register); - } - - do { - last_second = second; - last_minute = minute; - last_hour = hour; - last_day = day; - last_month = month; - last_year = year; - last_century = century; - - while (get_update_in_progress_flag()); // Make sure an update isn't in progress - second = get_RTC_register(0x00); - minute = get_RTC_register(0x02); - hour = get_RTC_register(0x04); - day = get_RTC_register(0x07); - month = get_RTC_register(0x08); - year = get_RTC_register(0x09); - if(century_register != 0) { - century = get_RTC_register(century_register); - } - } while( (last_second == second) && (last_minute == minute) && (last_hour == hour) && - (last_day == day) && (last_month == month) && (last_year == year) && - (last_century == century) ); - - registerB = get_RTC_register(0x0B); - - // Convert BCD to binary values if necessary - - if (!(registerB & 0x04)) { - second = (second & 0x0F) + ((second / 16) * 10); - minute = (minute & 0x0F) + ((minute / 16) * 10); - hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); - day = (day & 0x0F) + ((day / 16) * 10); - month = (month & 0x0F) + ((month / 16) * 10); - year = (year & 0x0F) + ((year / 16) * 10); - if(century_register != 0) { - century = (century & 0x0F) + ((century / 16) * 10); - } - } - - // Calculate the full (4-digit) year - - if(century_register != 0) { - year += century * 100; - } else { - //year += (CURRENT_YEAR / 100) * 100; - //if(year < CURRENT_YEAR) year += 100; - - if ((year += 1900) < 1970) - year += 100; - } - - time->Second = second; - time->Minute = minute; - time->Hour = hour; - time->Day = day; - time->Month = month; - time->Year = year; -} - -void rtc_time(EFI_TIME *time) { - - read_rtc(time); - - time->TimeZone = EFI_UNSPECIFIED_TIMEZONE; - - return ; -} - -char * Date(void) -{ - EFI_TIME rtctime; - rtc_time(&rtctime); - - return newStringWithFormat("%02d/%02d/%04d %02d:%02d:%02d",rtctime.Month,rtctime.Day,rtctime.Year, - rtctime.Hour,rtctime.Minute,rtctime.Second); -} -#endif \ No newline at end of file +} \ No newline at end of file Index: branches/cparm/i386/libsaio/cpu.c =================================================================== --- branches/cparm/i386/libsaio/cpu.c (revision 1971) +++ branches/cparm/i386/libsaio/cpu.c (revision 1972) @@ -44,8 +44,8 @@ #if LEGACY_CPU -static uint64_t measure_tsc_frequency(void); + // DFE: enable_PIT2 and disable_PIT2 come from older xnu /* @@ -74,7 +74,8 @@ " outb %%al,$0x61 \n\t" : : : "%al" ); } - +#if 0 +static uint64_t measure_tsc_frequency(void); // DFE: set_PIT2_mode0, poll_PIT2_gate, and measure_tsc_frequency are // roughly based on Linux code @@ -171,7 +172,143 @@ disable_PIT2(); return retval; } +#endif +static inline static void +set_PIT2(int value) +{ + /* + * First, tell the clock we are going to write 16 bits to the counter + * and enable one-shot mode (command 0xB8 to port 0x43) + * Then write the two bytes into the PIT2 clock register (port 0x42). + * Loop until the value is "realized" in the clock, + * this happens on the next tick. + */ + asm volatile( + " movb $0xB8,%%al \n\t" + " outb %%al,$0x43 \n\t" + " movb %%dl,%%al \n\t" + " outb %%al,$0x42 \n\t" + " movb %%dh,%%al \n\t" + " outb %%al,$0x42 \n" + "1: inb $0x42,%%al \n\t" + " inb $0x42,%%al \n\t" + " cmp %%al,%%dh \n\t" + " jne 1b" + : : "d"(value) : "%al"); +} + + +static inline static uint64_t +get_PIT2(unsigned int *value) +{ + register uint64_t result; + /* + * This routine first latches the time (command 0x80 to port 0x43), + * then gets the time stamp so we know how long the read will take later. + * Read (from port 0x42) and return the current value of the timer. + */ +#ifdef __i386__ + asm volatile( + " xorl %%ecx,%%ecx \n\t" + " movb $0x80,%%al \n\t" + " outb %%al,$0x43 \n\t" + " rdtsc \n\t" + " pushl %%eax \n\t" + " inb $0x42,%%al \n\t" + " movb %%al,%%cl \n\t" + " inb $0x42,%%al \n\t" + " movb %%al,%%ch \n\t" + " popl %%eax " + : "=A"(result), "=c"(*value)); +#else /* __x86_64__ */ + asm volatile( + " xorq %%rcx,%%rcx \n\t" + " movb $0x80,%%al \n\t" + " outb %%al,$0x43 \n\t" + " rdtsc \n\t" + " pushq %%rax \n\t" + " inb $0x42,%%al \n\t" + " movb %%al,%%cl \n\t" + " inb $0x42,%%al \n\t" + " movb %%al,%%ch \n\t" + " popq %%rax " + : "=A"(result), "=c"(*value)); +#endif + + return result; +} + +/* + * timeRDTSC() + * This routine sets up PIT counter 2 to count down 1/20 of a second. + * It pauses until the value is latched in the counter + * and then reads the time stamp counter to return to the caller. + */ +static uint64_t timeRDTSC(void) +{ + int attempts = 0; + uint64_t latchTime; + uint64_t saveTime,intermediate; + unsigned int timerValue, lastValue; + //boolean_t int_enabled; + /* + * Table of correction factors to account for + * - timer counter quantization errors, and + * - undercounts 0..5 + */ +#define SAMPLE_CLKS_EXACT (((double) CLKNUM) / 20.0) +#define SAMPLE_CLKS_INT ((int) CLKNUM / 20) +#define SAMPLE_NSECS (2000000000LL) +#define SAMPLE_MULTIPLIER (((double)SAMPLE_NSECS)*SAMPLE_CLKS_EXACT) +#define ROUND64(x) ((uint64_t)((x) + 0.5)) + uint64_t scale[6] = { + ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-0)), + ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-1)), + ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-2)), + ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-3)), + ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-4)), + ROUND64(SAMPLE_MULTIPLIER/(double)(SAMPLE_CLKS_INT-5)) + }; + +restart: + if (attempts >= 9) // increase to up to 9 attempts. + // This will flash-reboot. TODO: Use tscPanic instead. + printf("Timestamp counter calibation failed with %d attempts\n", attempts); + attempts++; + enable_PIT2(); // turn on PIT2 + set_PIT2(0); // reset timer 2 to be zero + latchTime = rdtsc64(); // get the time stamp to time + latchTime = get_PIT2(&timerValue) - latchTime; // time how long this takes + set_PIT2(SAMPLE_CLKS_INT); // set up the timer for (almost) 1/20th a second + saveTime = rdtsc64(); // now time how long a 20th a second is... + get_PIT2(&lastValue); + get_PIT2(&lastValue); // read twice, first value may be unreliable + do { + intermediate = get_PIT2(&timerValue); + if (timerValue > lastValue) { + // Timer wrapped + set_PIT2(0); + disable_PIT2(); + goto restart; + } + lastValue = timerValue; + } while (timerValue > 5); + printf("timerValue %d\n",timerValue); + printf("intermediate 0x%016llx\n",intermediate); + printf("saveTime 0x%016llx\n",saveTime); + + intermediate -= saveTime; // raw count for about 1/20 second + intermediate *= scale[timerValue]; // rescale measured time spent + intermediate /= SAMPLE_NSECS; // so its exactly 1/20 a second + intermediate += latchTime; // add on our save fudge + + set_PIT2(0); // reset timer 2 to be zero + disable_PIT2(); // turn off PIT 2 + + return intermediate; +} + #ifdef AMD_SUPPORT #define MSR_AMD_APERF 0x000000E8 /* @@ -658,7 +795,7 @@ FSBFreq = (uint64_t)(compute_bclk() * 1000000); #if LEGACY_CPU - TSCFreq = measure_tsc_frequency(); + TSCFreq = timeRDTSC() * 20/*measure_tsc_frequency()*/; #endif #ifdef AMD_SUPPORT Index: branches/cparm/i386/libsaio/rtc.c =================================================================== --- branches/cparm/i386/libsaio/rtc.c (revision 0) +++ branches/cparm/i386/libsaio/rtc.c (revision 1972) @@ -0,0 +1,122 @@ +/* + * http://wiki.osdev.org/OSDev_Wiki:General_disclaimer + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include "libsaio.h" + +#define CURRENT_YEAR 2012 // Change this each year! + +static int century_register = 0x00; // Set by ACPI table parsing code if possible(... in FADT table) + +enum { + cmos_address = 0x70, + cmos_data = 0x71 +}; + + +static int get_update_in_progress_flag() { + outb(cmos_address, 0x0A); + return (inb(cmos_data) & 0x80); +} + + +static unsigned char get_RTC_register(int reg) { + outb(cmos_address, reg); + return inb(cmos_data); +} + +void rtc_read_clock(struct tm *time) { + unsigned char century = 0; + unsigned char last_second; + unsigned char last_minute; + unsigned char last_hour; + unsigned char last_day; + unsigned char last_month; + unsigned char last_year; + unsigned char last_century; + unsigned char registerB; + + unsigned char second; + unsigned char minute; + unsigned char hour; + unsigned char day; + unsigned char month; + unsigned int year; + // Note: This uses the "read registers until you get the same values twice in a row" technique + // to avoid getting dodgy/inconsistent values due to RTC updates + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + + do { + last_second = second; + last_minute = minute; + last_hour = hour; + last_day = day; + last_month = month; + last_year = year; + last_century = century; + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + } while( (last_second == second) && (last_minute == minute) && (last_hour == hour) && + (last_day == day) && (last_month == month) && (last_year == year) && + (last_century == century) ); + + registerB = get_RTC_register(0x0B); + + // Convert BCD to binary values if necessary + + if (!(registerB & 0x04)) { + second = (second & 0x0F) + ((second / 16) * 10); + minute = (minute & 0x0F) + ((minute / 16) * 10); + hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); + day = (day & 0x0F) + ((day / 16) * 10); + month = (month & 0x0F) + ((month / 16) * 10); + year = (year & 0x0F) + ((year / 16) * 10); + if(century_register != 0) { + century = (century & 0x0F) + ((century / 16) * 10); + } + } + + // Calculate the full (4-digit) year + + if(century_register != 0) { + year += century * 100; + } else { + //year += (CURRENT_YEAR / 100) * 100; + //if(year < CURRENT_YEAR) year += 100; + + if ((year += 1900) < 1970) + year += 100; + } + + time->tm_sec = second; + time->tm_min = minute; + time->tm_hour = hour; + time->tm_mday = day; + time->tm_mon = month; + time->tm_year = year; +} Index: branches/cparm/i386/libsaio/platform.h =================================================================== --- branches/cparm/i386/libsaio/platform.h (revision 1971) +++ branches/cparm/i386/libsaio/platform.h (revision 1972) @@ -119,9 +119,11 @@ #define envSysId "boot.hw.sysid" #define envgBIOSDev "boot.hw.bios_device" #define envgDeviceCount "boot.hw.device_count" +#define envarchCpuType "boot.hw.cputype" +#define envgHaveKernelCache "boot.kern.HaveKernelCache" #define envAdler32 "boot.kern.adler32" -#define envkCache "boot.kern.kernelcache" +#define envkCacheFile "boot.kern.kernelcache" #define envMKextName "boot.kern.mkextcache" #define envArgCntRemaining "boot.kern.argCount_remaining" #define envgBootArgs "boot.kern.boot_args" @@ -132,6 +134,7 @@ #define envgEnableCDROMRescan "boot.options.rescan_cdrom" #define envgScanSingleDrive "boot.options.single_drive" #define envShouldboot "boot.options.should_boot" +#define envgVerboseMode "boot.options.boot_verbose" #define envDriverExtSpec "boot.drivers.extspec" #define envDriverSpec "boot.drivers.spec" @@ -152,12 +155,20 @@ #define envgMenuStart "boot.ui.menu_start" #define envgMenuEnd "boot.ui.menu_end" +#define envConsoleErr "boot.console.stderr" + +#define envgBootFileType "boot.disk.Bootfiletype" +#define envHFSLoadVerbose "boot.disk.HFSLoadVerbose" +#define envgFSLoadAddress "boot.disk.FSLoadAddress" +#define envgBIOSBootVolume "boot.disk.BIOSBootVolume" +#define envgBootVolume "boot.disk.BootVolume" + #define envConvMem "boot.memmap.Conventional" #define envExtMem "boot.memmap.Extended" #define envMemoryMap "boot.memmap.Address" #define envMemoryMapCnt "boot.memmap.Count" +#define envMemoryMapNode "boot.memmap.devNode" - #define envRamFrequency "boot.ram.frequency" #define envRamCas "boot.ram.tCAS" #define envRamTrc "boot.ram.tRCD" Index: branches/cparm/i386/libsaio/disk.c =================================================================== --- branches/cparm/i386/libsaio/disk.c (revision 1971) +++ branches/cparm/i386/libsaio/disk.c (revision 1972) @@ -887,7 +887,8 @@ // turbo - we want the booter type scanned also case FDISK_BOOTER: if (part->bootid & FDISK_ACTIVE) { - gBIOSBootVolume = newFDiskBVRef( + /*gBIOSBootVolume =*/ + safe_set_env(envgBIOSBootVolume, (uint32_t)newFDiskBVRef( biosdev, partno, part->relsect, part, @@ -900,7 +901,7 @@ HFSGetDescription, HFSFree, 0, - kBIOSDevTypeHardDrive, 0); + kBIOSDevTypeHardDrive, 0)); break; } #ifndef UFS_SUPPORT @@ -1511,7 +1512,8 @@ #endif default: if (biosdev == (int)get_env(envgBIOSDev)) - gBIOSBootVolume = bvr; + //gBIOSBootVolume = bvr; + safe_set_env(envgBIOSBootVolume, (uint32_t)bvr); break; } } Index: branches/cparm/i386/libsaio/CoreHash.h =================================================================== --- branches/cparm/i386/libsaio/CoreHash.h (revision 1971) +++ branches/cparm/i386/libsaio/CoreHash.h (revision 1972) @@ -22,7 +22,7 @@ static struct HObj * HObj##_FindStrVar(const char *name, struct HObj *container) { \ struct HObj *var; \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ \ return NULL; \ } else { \ @@ -47,7 +47,7 @@ return NULL; \ } \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ \ free(var); \ return NULL; \ @@ -81,7 +81,7 @@ return; \ } \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ return; \ } else { \ HASH_DEL( container, var); \ @@ -104,7 +104,7 @@ static struct HObj * HObj##_FindIntVar(int id, struct HObj *container) { \ struct HObj *var; \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ \ return NULL; \ } else { \ @@ -123,7 +123,7 @@ \ var->id = id; \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ \ free(var); \ return NULL; \ @@ -157,7 +157,7 @@ return; \ } \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ return; \ } else { \ HASH_DEL( container, var); \ @@ -194,7 +194,7 @@ static void HObj##_DeleteAll(struct HObj *container ) { \ struct HObj *current_var, *tmp; \ \ - if (setjmp(h_buf_error) == -1) { \ + if (setjmp(uterror) == -1) { \ return; \ } else { \ HASH_ITER(hh, container, current_var, tmp) { \ Index: branches/cparm/i386/libsaio/uthash.h =================================================================== --- branches/cparm/i386/libsaio/uthash.h (revision 1971) +++ branches/cparm/i386/libsaio/uthash.h (revision 1972) @@ -1,5 +1,5 @@ /* -Copyright (c) 2003-2011, Troy D. Hanson http://uthash.sourceforge.net +Copyright (c) 2003-2012, Troy D. Hanson http://uthash.sourceforge.net All rights reserved. Redistribution and use in source and binary forms, with or without @@ -54,14 +54,23 @@ } while(0) #endif -#define UTHASH_VERSION 1.9.4 +#define UTHASH_VERSION 1.9.6 -#define uthash_fatal(msg) longjmp(h_buf_error,-1) /* fatal error (out of memory,etc) */ +#ifndef uthash_fatal +#define uthash_fatal(msg) longjmp(uterror,-1) /* fatal error (out of memory,etc) */ +#endif +#ifndef uthash_malloc #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef uthash_free #define uthash_free(ptr,sz) free(ptr) /* free fcn */ - +#endif +#ifndef uthash_noexpand_fyi #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#endif +#ifndef uthash_expand_fyi #define uthash_expand_fyi(tbl) /* can be defined to log expands */ +#endif /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ @@ -94,12 +103,12 @@ if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ -} while (0); +} while (0) #define HASH_BLOOM_FREE(tbl) \ do { \ uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ -} while (0); +} while (0) #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) @@ -144,7 +153,7 @@ unsigned _ha_bkt; \ (add)->hh.next = NULL; \ (add)->hh.key = (char*)keyptr; \ - (add)->hh.keylen = keylen_in; \ + (add)->hh.keylen = (unsigned)keylen_in; \ if (!(head)) { \ head = (add); \ (head)->hh.prev = NULL; \ @@ -237,7 +246,7 @@ * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. */ #ifdef HASH_DEBUG -#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); longjmp(h_buf_error,-1); } while (0) +#define HASH_OOPS(...) do { printf("%s\n"__VA_ARGS__); longjmp(THIS_BUF_ERROR,-1); } while (0) #define HASH_FSCK(hh,head) \ do { \ unsigned _bkt_i; \ @@ -345,7 +354,7 @@ for(_fn_i=0; _fn_i < keylen; _fn_i++) \ hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ bkt = hashv & (num_bkts-1); \ -} while(0); +} while(0) #define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ do { \ @@ -382,7 +391,7 @@ char *_hj_key=(char*)(key); \ hashv = 0xfeedbeef; \ _hj_i = _hj_j = 0x9e3779b9; \ - _hj_k = keylen; \ + _hj_k = (unsigned)keylen; \ while (_hj_k >= 12) { \ _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + ( (unsigned)_hj_key[2] << 16 ) \ @@ -470,7 +479,7 @@ hashv ^= hashv << 25; \ hashv += hashv >> 6; \ bkt = hashv & (num_bkts-1); \ -} while(0); +} while(0) #ifdef HASH_USING_NO_STRICT_ALIASING /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. @@ -555,17 +564,17 @@ #define HASH_KEYCMP(a,b,len) memcmp(a,b,len) /* iterate over items in a known bucket to find desired item */ -#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ -do { \ - if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ - else out=NULL; \ - while (out) { \ - if (out->hh.keylen == keylen_in) { \ - if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break; \ - } \ - if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \ - else out = NULL; \ - } \ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ +do { \ + if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ + else out=NULL; \ + while (out) { \ + if ((out)->hh.keylen == keylen_in) { \ + if ((HASH_KEYCMP((out)->hh.key,keyptr,keylen_in)) == 0) break; \ + } \ + if ((out)->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,(out)->hh.hh_next)); \ + else out = NULL; \ + } \ } while(0) /* add an item to a bucket */ Index: branches/cparm/i386/libsaio/lib.c =================================================================== --- branches/cparm/i386/libsaio/lib.c (revision 0) +++ branches/cparm/i386/libsaio/lib.c (revision 1972) @@ -0,0 +1,104 @@ +/* + * This file is part of the libpayload project. + * + * Copyright (C) 2008 Uwe Hermann + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "libsaio.h" + +/* + * Convert a number in BCD format to decimal. + * + * @param b The BCD number. + * @return The given BCD number in decimal format. + */ +int bcd2dec(int b) +{ + return ((b >> 4) & 0x0f) * 10 + (b & 0x0f); +} + +/* + * Convert a number in decimal format into the BCD format. + * + * @param d The decimal number. + * @return The given decimal number in BCD format. + */ +int dec2bcd(int d) +{ + return ((d / 10) << 4) | (d % 10); +} +#if UNUSED +/** + * Return the absolute value of the specified integer. + * + * @param j The integer of which we want to know the absolute value. + * @return The absolute value of the specified integer. + */ +int abs(int j) +{ + return (j >= 0 ? j : -j); +} + +long int labs(long int j) +{ + return (j >= 0 ? j : -j); +} + +long long int llabs(long long int j) +{ + return (j >= 0 ? j : -j); +} + +/** + * Given a 4-bit value, return the ASCII hex representation of it. + * + * @param b A 4-bit value which shall be converted to ASCII hex. + * @return The ASCII hex representation of the specified 4-bit value. + * Returned hex-characters will always be lower-case (a-f, not A-F). + */ +u8 bin2hex(u8 b) +{ + return (b < 10) ? '0' + b : 'a' + (b - 10); +} + +/** + * Given an ASCII hex input character, return its integer value. + * + * For example, the input value '6' will be converted to 6, 'a'/'A' will + * be converted to 10, 'f'/'F' will be converted to 15, and so on. + * + * The return value for invalid input characters is 0. + * + * @param h The input byte in ASCII hex format. + * @return The integer value of the specified ASCII hex byte. + */ +u8 hex2bin(u8 h) +{ + return (('0' <= h && h <= '9') ? (h - '0') : \ + ('A' <= h && h <= 'F') ? (h - 'A' + 10) : \ + ('a' <= h && h <= 'f') ? (h - 'a' + 10) : 0); +} +#endif Index: branches/cparm/i386/libsaio/arc4random-fbsd.c =================================================================== --- branches/cparm/i386/libsaio/arc4random-fbsd.c (revision 0) +++ branches/cparm/i386/libsaio/arc4random-fbsd.c (revision 1972) @@ -0,0 +1,310 @@ +/* + * Copyright (c) 1996, David Mazieres + * Copyright (c) 2008, Damien Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * Arc4 random number generator for OpenBSD. + * + * This code is derived from section 17.1 of Applied Cryptography, + * second edition, which describes a stream cipher allegedly + * compatible with RSA Labs "RC4" cipher (the actual description of + * which is a trade secret). The same algorithm is used as a stream + * cipher called "arcfour" in Tatu Ylonen's ssh package. + * + * Here the stream cipher has been modified always to include the time + * when initializing the state. That makes it impossible to + * regenerate the same random sequence twice, so this can't be used + * for encryption, but will generate good random numbers. + * + * RC4 is a registered trademark of RSA Laboratories. + */ + + +#include "libsaio.h" + + +struct arc4_stream { + u_int8_t i; + u_int8_t j; + u_int8_t s[256]; +}; + + +#define KEYSIZE 128 + +static struct arc4_stream rs = { + .i = 0, + .j = 0, + .s = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, + 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, + 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, + 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, + 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, + 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, + 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, + 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, + 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, + 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, + 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, + 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 + } +}; +//static int rs_initialized; +static int rs_stired; +static int arc4_count; + +static inline u_int8_t arc4_getbyte(void); +static void arc4_stir(void); + +static struct { + struct timeval tv; + u_int8_t rnd[KEYSIZE]; +} rdat; +static volatile int rs_data_available = 0; + +static inline void +arc4_addrandom(u_char *dat, int datlen) +{ + int n; + u_int8_t si; + + rs.i--; + for (n = 0; n < 256; n++) { + rs.i = (rs.i + 1); + si = rs.s[rs.i]; + rs.j = (rs.j + si + dat[n % datlen]); + rs.s[rs.i] = rs.s[rs.j]; + rs.s[rs.j] = si; + } + rs.j = rs.i; +} + +static void +arc4_fetch(void) +{ + + (void)gettimeofday(&rdat.tv, NULL); + +} + +static void +arc4_stir(void) +{ + int n; + /* + * If we don't have data, we need some now before we can integrate + * it into the static buffers + */ + if (!rs_data_available) + { + arc4_fetch(); + } + rs_data_available = 0; + __sync_synchronize(); + + arc4_addrandom((u_char *)&rdat, KEYSIZE); + + /* + * Throw away the first N bytes of output, as suggested in the + * paper "Weaknesses in the Key Scheduling Algorithm of RC4" + * by Fluher, Mantin, and Shamir. N=1024 is based on + * suggestions in the paper "(Not So) Random Shuffles of RC4" + * by Ilya Mironov. + */ + for (n = 0; n < 1024; n++) + (void) arc4_getbyte(); + arc4_count = 1600000; + rs_stired = 1; +} + +static inline u_int8_t +arc4_getbyte(void) +{ + u_int8_t si, sj; + + rs.i = (rs.i + 1); + si = rs.s[rs.i]; + rs.j = (rs.j + si); + sj = rs.s[rs.j]; + rs.s[rs.i] = sj; + rs.s[rs.j] = si; + + return (rs.s[(si + sj) & 0xff]); +} + +static inline u_int32_t +arc4_getword(void) +{ + u_int32_t val; + + val = arc4_getbyte() << 24; + val |= arc4_getbyte() << 16; + val |= arc4_getbyte() << 8; + val |= arc4_getbyte(); + + return (val); +} + +/* 7944700: force restir in child */ +__private_extern__ void +_arc4_fork_child(void) +{ + rs_stired = 0; + rs_data_available = 0; +} + +static inline int +arc4_check_stir(void) +{ + if (!rs_stired || arc4_count <= 0) { + arc4_stir(); + return 1; + } + return 0; +} + +void +arc4random_stir(void) +{ + arc4_stir(); +} + +void +arc4random_addrandom(u_char *dat, int datlen) +{ + arc4_check_stir(); + arc4_addrandom(dat, datlen); +} + +u_int32_t +arc4random(void) +{ + u_int32_t rnd; + + int did_stir = arc4_check_stir(); + rnd = arc4_getword(); + arc4_count -= 4; + + if (did_stir) + { + /* stirring used up our data pool, we need to read in new data outside of the lock */ + arc4_fetch(); + rs_data_available = 1; + __sync_synchronize(); + } + + return (rnd); +} + +void +arc4random_buf(void *_buf, size_t n) +{ + u_char *buf = (u_char *)_buf; + int did_stir = 0; + + while (n--) { + if (arc4_check_stir()) + { + did_stir = 1; + } + buf[n] = arc4_getbyte(); + arc4_count--; + } + + if (did_stir) + { + /* stirring used up our data pool, we need to read in new data outside of the lock */ + arc4_fetch(); + rs_data_available = 1; + __sync_synchronize(); + } +} + +/* + * Calculate a uniformly distributed random number less than upper_bound + * avoiding "modulo bias". + * + * Uniformity is achieved by generating new random numbers until the one + * returned is outside the range [0, 2**32 % upper_bound). This + * guarantees the selected random number will be inside + * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound) + * after reduction modulo upper_bound. + */ +u_int32_t +arc4random_uniform(u_int32_t upper_bound) +{ + u_int32_t r, min; + + if (upper_bound < 2) + return (0); + +#if (ULONG_MAX > 0xffffffffUL) + min = 0x100000000UL % upper_bound; +#else + /* Calculate (2**32 % upper_bound) avoiding 64-bit math */ + if (upper_bound > 0x80000000) + min = 1 + ~upper_bound; /* 2**32 - upper_bound */ + else { + /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */ + min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound; + } +#endif + + /* + * This could theoretically loop forever but each retry has + * p > 0.5 (worst case, usually far better) of selecting a + * number inside the range we need, so it should rarely need + * to re-roll. + */ + for (;;) { + r = arc4random(); + if (r >= min) + break; + } + + return (r % upper_bound); +} + +void +arc4_init(void) +{ +} + +#if 0 +/*-------- Test code for i386 --------*/ +#include +#include +int +main(int argc, char **argv) +{ + const int iter = 1000000; + int i; + pctrval v; + + v = rdtsc(); + for (i = 0; i < iter; i++) + arc4random(); + v = rdtsc() - v; + v /= iter; + + printf("%qd cycles\n", v); +} +#endif Index: branches/cparm/i386/libsaio/stack_protector.c =================================================================== --- branches/cparm/i386/libsaio/stack_protector.c (revision 1971) +++ branches/cparm/i386/libsaio/stack_protector.c (revision 1972) @@ -33,7 +33,7 @@ long __stack_chk_guard[8] = {0, 0, 0, 0, 0, 0, 0, 0}; //__private_extern__ void __guard_setup(void) /*__attribute__ ((visibility ("hidden")))*/; -static void __guard_setup(void) __attribute__((constructor)); +void __guard_setup(void) __attribute__((constructor)); void __stack_chk_fail(void); @@ -46,7 +46,7 @@ size_t i; long guard[__arraycount(__stack_chk_guard)]; - arc4rand(guard, sizeof(guard), 0); + arc4random_buf(guard, sizeof(guard)); for (i = 0; i < __arraycount(guard); i++) __stack_chk_guard[i] = guard[i]; @@ -56,14 +56,14 @@ to the "terminator canary" */ ((char*)__stack_chk_guard)[0] = 0; ((char*)__stack_chk_guard)[1] = 0; ((char*)__stack_chk_guard)[2] = '\n'; ((char*)__stack_chk_guard)[3] = 255; - + } void __stack_chk_fail() { #ifndef BOOT1 - stop("stack overflow"); + stop("stack overflow"); #endif - for(;;); + for(;;); } Index: branches/cparm/i386/libsaio/intel_acpi.h =================================================================== --- branches/cparm/i386/libsaio/intel_acpi.h (revision 1971) +++ branches/cparm/i386/libsaio/intel_acpi.h (revision 1972) @@ -34,7 +34,7 @@ #include "ppmsetup.h" // // All tables and structures must be byte-packed to match the ACPI specification -#pragma pack(1) +//#pragma pack(1) #define ACPI_SIG_DSDT "DSDT" // Differentiated System Description Table #define ACPI_SIG_FADT "FACP" // Fixed ACPI Description Table @@ -164,7 +164,7 @@ U32 OemRevision; // OEM revision number U8 AslCompilerId[4]; // ASCII ASL compiler vendor ID U32 AslCompilerRevision; // ASL compiler version -} ACPI_TABLE_HEADER; +} __attribute__((packed))ACPI_TABLE_HEADER; // GAS - Generic Address Structure (ACPI 2.0+) typedef struct acpi_generic_address { @@ -173,7 +173,7 @@ U8 BitOffset; // Bit offset within the register U8 AccessWidth; // Minimum Access size (ACPI 3.0) U64 Address; // 64-bit address of struct or register -} ACPI_GENERIC_ADDRESS; +} __attribute__((packed))ACPI_GENERIC_ADDRESS; // RSDP - Root System Description Pointer (Signature is "RSD PTR ") typedef struct acpi_table_rsdp { @@ -186,7 +186,7 @@ U64 XsdtPhysicalAddress; // 64-bit physical address of the XSDT (ACPI 2.0+) U8 ExtendedChecksum; // Checksum of entire table (ACPI 2.0+) U8 Reserved[3]; // Reserved, must be zero -} ACPI_TABLE_RSDP; +} __attribute__((packed))ACPI_TABLE_RSDP; #define ACPI_RSDP_REV0_SIZE 20 // Size of original ACPI 1.0 RSDP @@ -194,20 +194,20 @@ typedef struct acpi_table_rsdt { ACPI_TABLE_HEADER Header; // Common ACPI table header U32 TableOffsetEntry[1]; // Array of pointers to ACPI tables -} ACPI_TABLE_RSDT; +} __attribute__((packed))ACPI_TABLE_RSDT; // XSDT - Root System Description Table typedef struct acpi_table_xsdt { ACPI_TABLE_HEADER Header; // Common ACPI table header U64 TableOffsetEntry[1]; // Array of pointers to ACPI tables -} ACPI_TABLE_XSDT; +} __attribute__((packed))ACPI_TABLE_XSDT; // DSDT - Differentiated System Description Table typedef struct acpi_table_dsdt { ACPI_TABLE_HEADER Header; // Common ACPI table header U32 EntryStart; -} ACPI_TABLE_DSDT; +} __attribute__((packed))ACPI_TABLE_DSDT; // FACS - Firmware ACPI Control Structure (FACS) typedef struct acpi_table_facs { @@ -220,7 +220,7 @@ U64 XFirmwareWakingVector; // 64-bit version of the Firmware Waking Vector (ACPI 2.0+) U8 Version; // Version of this table (ACPI 2.0+) U8 Reserved[31]; // Reserved, must be zero -} ACPI_TABLE_FACS; +} __attribute__((packed))ACPI_TABLE_FACS; // SBST - Smart Battery Specification Table - Version 1 typedef struct acpi_table_sbst @@ -230,7 +230,7 @@ U32 LowLevel; U32 CriticalLevel; -} ACPI_TABLE_SBST; +} __attribute__((packed))ACPI_TABLE_SBST; // ASF - Alert Standard Format table (Signature "ASF!") typedef struct acpi_table_asf @@ -247,7 +247,7 @@ U8 Flags; U8 Reserved[10]; -} ACPI_TABLE_DMAR; +} __attribute__((packed))ACPI_TABLE_DMAR; // HPET - High Precision Event Timer table - Version 1 typedef struct acpi_table_hpet @@ -259,7 +259,7 @@ U16 MinimumTick; /* Main counter min tick, periodic mode */ U8 Flags; -} ACPI_TABLE_HPET; +} __attribute__((packed))ACPI_TABLE_HPET; //MCFG - PCI Memory Mapped Configuration table and sub-table - Version 1 typedef struct acpi_table_mcfg @@ -276,7 +276,7 @@ U8 Identifier[16]; /* UUID identifier */ U16 DataOffset; /* Offset of remaining data in table */ -} ACPI_TABLE_UEFI; +} __attribute__((packed))ACPI_TABLE_UEFI; // ECDT - Embedded Controller Boot Resources Table - Version 1 typedef struct acpi_table_ecdt @@ -288,7 +288,7 @@ U8 Gpe; /* The GPE for the EC */ U8 Id[1]; /* Full namepath of the EC in the ACPI namespace */ -} ACPI_TABLE_ECDT; +} __attribute__((packed))ACPI_TABLE_ECDT; // FADT - Fixed ACPI Description Table (Signature "FACP") typedef struct acpi_table_fadt { @@ -344,19 +344,19 @@ ACPI_GENERIC_ADDRESS XPmTimerBlock; // 64-bit Extended Power Mgt Timer Ctrl Reg Blk address ACPI_GENERIC_ADDRESS XGpe0Block; // 64-bit Extended General Purpose Event 0 Reg Blk address ACPI_GENERIC_ADDRESS XGpe1Block; // 64-bit Extended General Purpose Event 1 Reg Blk address -} ACPI_TABLE_FADT; +} __attribute__((packed))ACPI_TABLE_FADT; // SSDT - Secondary System Description Table typedef struct acpi_table_ssdt { ACPI_TABLE_HEADER Header; // Common ACPI table header -} ACPI_TABLE_SSDT; +} __attribute__((packed))ACPI_TABLE_SSDT; //MADT - Multiple APIC Description Table typedef struct acpi_table_madt { ACPI_TABLE_HEADER Header; // Common ACPI table header U32 Address; // Physical address of local APIC U32 Flags; -} ACPI_TABLE_MADT; +} __attribute__((packed))ACPI_TABLE_MADT; // Values for subtable type in ACPI_SUBTABLE_HEADER @@ -378,7 +378,7 @@ typedef struct acpi_subtable_header { U8 Type; U8 Length; -} ACPI_SUBTABLE_HEADER; +} __attribute__((packed))ACPI_SUBTABLE_HEADER; // MADT Sub-tables, correspond to Type in ACPI_SUBTABLE_HEADER @@ -388,7 +388,7 @@ U8 ProcessorId; // ACPI processor id U8 Id; // Processor's local APIC id U32 LapicFlags; -} ACPI_MADT_LOCAL_APIC; +} __attribute__((packed))ACPI_MADT_LOCAL_APIC; // 1: IO APIC typedef struct acpi_madt_io_apic { @@ -397,7 +397,7 @@ U8 Reserved; // Reserved - must be zero U32 Address; // APIC physical address U32 GlobalIrqBase; // Global system interrupt where INTI lines start -} ACPI_MADT_IO_APIC; +} __attribute__((packed))ACPI_MADT_IO_APIC; // 2: Interrupt Override typedef struct acpi_madt_interrupt_override { @@ -406,14 +406,14 @@ U8 SourceIrq; // Interrupt source (IRQ) U32 GlobalIrq; // Global system interrupt U16 IntiFlags; -} ACPI_MADT_INTERRUPT_OVERRIDE; +} __attribute__((packed))ACPI_MADT_INTERRUPT_OVERRIDE; // 3: NMI Source typedef struct acpi_madt_nmi_source { ACPI_SUBTABLE_HEADER Header; U16 IntiFlags; U32 GlobalIrq; // Global system interrupt -} ACPI_MADT_NMI_SOURCE; +} __attribute__((packed))ACPI_MADT_NMI_SOURCE; // 4: Local APIC NMI typedef struct acpi_madt_local_apic_nmi { @@ -421,14 +421,14 @@ U8 ProcessorId; // ACPI processor id U16 IntiFlags; U8 Lint; // LINTn to which NMI is connected -} ACPI_MADT_LOCAL_APIC_NMI; +} __attribute__((packed))ACPI_MADT_LOCAL_APIC_NMI; // 5: Address Override typedef struct acpi_madt_local_apic_override { ACPI_SUBTABLE_HEADER Header; U16 Reserved; // Reserved, must be zero U64 Address; // APIC physical address -} ACPI_MADT_LOCAL_APIC_OVERRIDE; +} __attribute__((packed))ACPI_MADT_LOCAL_APIC_OVERRIDE; // 6: I/O Sapic typedef struct acpi_madt_io_sapic { @@ -437,7 +437,7 @@ U8 Reserved; // Reserved, must be zero U32 GlobalIrqBase; // Global interrupt for SAPIC start U64 Address; // SAPIC physical address -} ACPI_MADT_IO_SAPIC; +} __attribute__((packed))ACPI_MADT_IO_SAPIC; // 7: Local Sapic typedef struct acpi_madt_local_sapic { @@ -449,7 +449,7 @@ U32 LapicFlags; U32 Uid; // Numeric UID - ACPI 3.0 char UidString[1]; // String UID - ACPI 3.0 -} ACPI_MADT_LOCAL_SAPIC; +} __attribute__((packed))ACPI_MADT_LOCAL_SAPIC; // 8: Platform Interrupt Source typedef struct acpi_madt_interrupt_source { @@ -461,7 +461,7 @@ U8 IoSapicVector; // Vector value for PMI interrupts U32 GlobalIrq; // Global system interrupt U32 Flags; // Interrupt Source Flags -} ACPI_MADT_INTERRUPT_SOURCE; +} __attribute__((packed))ACPI_MADT_INTERRUPT_SOURCE; // 9: Processor X2APIC typedef struct acpi_madt_x2apic { @@ -470,7 +470,7 @@ U32 x2apicId; // Processor's X2APIC ID U32 x2apicFlags; U32 UID; -} ACPI_MADT_X2APIC; +} __attribute__((packed))ACPI_MADT_X2APIC; // Common flags fields for MADT subtables @@ -499,111 +499,111 @@ typedef struct packageLength { U8 packageLength0; U8 packageLength1; -} ACPI_PACKAGE_LENGTH; +} __attribute__((packed))ACPI_PACKAGE_LENGTH; typedef struct acpi_scope { U8 scopeOpcode; ACPI_PACKAGE_LENGTH pkgLength; U8 rootChar; -} ACPI_SCOPE; +} __attribute__((packed))ACPI_SCOPE; typedef struct dual_name_path { U8 prefix; U32 nameseg[2]; -} DUAL_NAME_PATH; +} __attribute__((packed))DUAL_NAME_PATH; typedef struct multi_name_path { U8 prefix; U8 segCount; U32 nameseg[MAX_SUPPORTED_CPU_NAMESEGS]; -} MULTI_NAME_PATH; +} __attribute__((packed))MULTI_NAME_PATH; typedef struct generic_register { U8 genericRegisterField; ACPI_PACKAGE_LENGTH pkgLength; ACPI_GENERIC_ADDRESS gas; -} ACPI_GENERIC_REGISTER; +} __attribute__((packed))ACPI_GENERIC_REGISTER; typedef struct package { U8 packageOpcode; ACPI_PACKAGE_LENGTH pkgLength; U8 numElements; -} ACPI_PACKAGE; +} __attribute__((packed))ACPI_PACKAGE; typedef struct small_package { U8 packageOpcode; U8 packageLength; U8 numElements; -} ACPI_SMALL_PACKAGE; +} __attribute__((packed))ACPI_SMALL_PACKAGE; typedef struct small_buffer { U8 bufferOpcode; U8 packageLength; -} ACPI_SMALL_BUFFER; +} __attribute__((packed))ACPI_SMALL_BUFFER; typedef struct end_tag { U8 endTagField; U8 checksum; -} ACPI_END_TAG; +} __attribute__((packed))ACPI_END_TAG; typedef struct return_name_seg { U8 returnOpcode; U32 name; -} ACPI_RETURN_NAME_SEG; +} __attribute__((packed))ACPI_RETURN_NAME_SEG; typedef struct return_package { U8 returnOpcode; ACPI_PACKAGE package; -} ACPI_RETURN_PACKAGE; +} __attribute__((packed))ACPI_RETURN_PACKAGE; typedef struct return_zero { U8 returnOpcode; U8 zeroOpcode; -} ACPI_RETURN_ZERO; +} __attribute__((packed))ACPI_RETURN_ZERO; typedef struct return_opcode { U8 returnOpcode; U8 opcodeToReturn; -} ACPI_RETURN_OPCODE; +} __attribute__((packed))ACPI_RETURN_OPCODE; typedef struct byteConst { U8 byteOpcode; U8 byteData; -} ACPI_BYTE_CONST; +} __attribute__((packed))ACPI_BYTE_CONST; typedef struct wordConst { U8 wordOpcode; U16 wordData; -} ACPI_WORD_CONST; +} __attribute__((packed))ACPI_WORD_CONST; typedef struct dwordConst { U8 dwordOpcode; U32 dwordData; -} ACPI_DWORD_CONST; +} __attribute__((packed))ACPI_DWORD_CONST; typedef struct small_method { U8 methodOpcode; U8 packageLength; U32 name; U8 methodFlags; -} ACPI_SMALL_METHOD; +} __attribute__((packed))ACPI_SMALL_METHOD; typedef struct method { U8 methodOpcode; ACPI_PACKAGE_LENGTH pkgLength; U32 name; U8 methodFlags; -} ACPI_METHOD; +} __attribute__((packed))ACPI_METHOD; typedef struct namePath { U8 nameOpcode; U32 name; -} ACPI_NAME_PATH; +} __attribute__((packed))ACPI_NAME_PATH; typedef struct named_dword { ACPI_NAME_PATH namePath; ACPI_DWORD_CONST dword; -} ACPI_NAMED_DWORD; +} __attribute__((packed))ACPI_NAMED_DWORD; typedef struct rootNamePath { U8 nameOpcode; @@ -614,22 +614,22 @@ typedef struct root_named_dword { ACPI_ROOT_NAME_PATH rootNamePath; ACPI_DWORD_CONST dword; -} ACPI_ROOT_NAMED_DWORD; +} __attribute__((packed))ACPI_ROOT_NAMED_DWORD; typedef struct named_object { ACPI_NAME_PATH namePath; ACPI_PACKAGE package; -} ACPI_NAMED_OBJECT; +} __attribute__((packed))ACPI_NAMED_OBJECT; typedef struct small_named_object { ACPI_NAME_PATH namePath; ACPI_SMALL_PACKAGE package; -} ACPI_SMALL_NAMED_OBJECT; +} __attribute__((packed))ACPI_SMALL_NAMED_OBJECT; typedef struct create_dword_field { ACPI_NAME_PATH namePath; ACPI_SMALL_PACKAGE package; -} ACPI_CREATE_DWORD_FIELD; +} __attribute__((packed))ACPI_CREATE_DWORD_FIELD; typedef struct tstate_package { ACPI_SMALL_PACKAGE package; @@ -638,7 +638,7 @@ ACPI_DWORD_CONST TransLatency; ACPI_DWORD_CONST Control; ACPI_DWORD_CONST Status; -} ACPI_TSTATE_PACKAGE; +} __attribute__((packed))ACPI_TSTATE_PACKAGE; typedef struct pstate_package { ACPI_SMALL_PACKAGE package; @@ -648,7 +648,7 @@ ACPI_DWORD_CONST BMLatency; ACPI_DWORD_CONST Control; ACPI_DWORD_CONST Status; -} ACPI_PSTATE_PACKAGE; +} __attribute__((packed))ACPI_PSTATE_PACKAGE; typedef struct psd_package { ACPI_SMALL_PACKAGE package; @@ -657,7 +657,7 @@ ACPI_DWORD_CONST Domain; ACPI_DWORD_CONST CoordType; ACPI_DWORD_CONST NumProcessors; -} ACPI_PSD_PACKAGE; +} __attribute__((packed))ACPI_PSD_PACKAGE; typedef struct csd_package { ACPI_SMALL_PACKAGE package; @@ -667,7 +667,7 @@ ACPI_DWORD_CONST CoordType; ACPI_DWORD_CONST NumProcessors; ACPI_DWORD_CONST Index; -} ACPI_CSD_PACKAGE; +} __attribute__((packed))ACPI_CSD_PACKAGE; typedef struct tsd_package { ACPI_SMALL_PACKAGE package; @@ -676,7 +676,7 @@ ACPI_DWORD_CONST Domain; ACPI_DWORD_CONST CoordType; ACPI_DWORD_CONST NumProcessors; -} ACPI_TSD_PACKAGE; +} __attribute__((packed))ACPI_TSD_PACKAGE; typedef struct processor { U8 processorOpCode; @@ -685,8 +685,8 @@ ACPI_BYTE_CONST ProcID; ACPI_DWORD_CONST PblkAddr; ACPI_BYTE_CONST PblkLen; -} ACPI_PROCESSOR; +} __attribute__((packed))ACPI_PROCESSOR; -#pragma pack() +//#pragma pack() #endif /* !__LIBSAIO_INTEL_ACPI_H */ Index: branches/cparm/i386/libsaio/stringTable.c =================================================================== --- branches/cparm/i386/libsaio/stringTable.c (revision 1971) +++ branches/cparm/i386/libsaio/stringTable.c (revision 1972) @@ -421,6 +421,13 @@ return false; } +config_file_t *resolveConfig(config_file_t *config) +{ + ASSERT_CONFIG + config_file_t *new_config = config; + return new_config; +} +#if UNUSED /* * */ @@ -483,7 +490,7 @@ // key not found return false; -} +} /* * get color value from plist format #RRGGBB @@ -507,6 +514,7 @@ } return false; } +#endif bool getValueForKey( const char *key, const char **val, int *size, config_file_t *config ) { Index: branches/cparm/i386/libsaio/convert.c =================================================================== --- branches/cparm/i386/libsaio/convert.c (revision 1971) +++ branches/cparm/i386/libsaio/convert.c (revision 1972) @@ -54,6 +54,7 @@ } /** XXX AsereBLN replace by strtoul */ +#if UNUSED uint32_t ascii_hex_to_int(char *buff) { uint32_t value = 0, i, digit; @@ -72,6 +73,7 @@ } return value; } +#endif void *convertHexStr2Binary(const char *hexStr, int *outLength) { Index: branches/cparm/i386/libsaio/saio_types.h =================================================================== --- branches/cparm/i386/libsaio/saio_types.h (revision 1971) +++ branches/cparm/i386/libsaio/saio_types.h (revision 1972) @@ -92,12 +92,24 @@ */ #define IO_CONFIG_DATA_SIZE 40960 // was 4096 // was 163840 -#define rand_tab_len 100 +struct tm { + int tm_sec; /* seconds after the minute [0-60] */ + int tm_min; /* minutes after the hour [0-59] */ + int tm_hour; /* hours since midnight [0-23] */ + int tm_mday; /* day of the month [1-31] */ + int tm_mon; /* months since January [0-11] */ + int tm_year; /* years since 1900 */ + int tm_wday; /* days since Sunday [0-6] */ + int tm_yday; /* days since January 1 [0-365] */ + int tm_isdst; /* Daylight Savings Time flag */ + long tm_gmtoff; /* offset from CUT in seconds */ + char *tm_zone; /* timezone abbreviation */ +}; -struct ran_obj { - int tab[rand_tab_len]; - int rmin; - int n; +/** System time structure */ +struct timeval { + time_t tv_sec; /**< Seconds */ + suseconds_t tv_usec; /**< Microseconds */ }; typedef struct tm_t Index: branches/cparm/i386/libsaio/msdos.c =================================================================== --- branches/cparm/i386/libsaio/msdos.c (revision 1971) +++ branches/cparm/i386/libsaio/msdos.c (revision 1972) @@ -52,6 +52,7 @@ #include "msdos_private.h" #include "msdos.h" +#include "platform.h" #define LABEL_LENGTH 11 #define MSDOS_CACHE_BLOCKSIZE BPS @@ -131,14 +132,14 @@ union bootsector *bsp; struct bpb33 *b33; struct bpb50 *b50; - struct bpb710 *b710; + //struct bpb710 *b710; u_int16_t bps; u_int8_t spc; bsp = (union bootsector *)buffer; b33 = (struct bpb33 *)bsp->bs33.bsBPB; b50 = (struct bpb50 *)bsp->bs50.bsBPB; - b710 = (struct bpb710 *)bsp->bs710.bsBPB; + //b710 = (struct bpb710 *)bsp->bs710.bsBPB; /* We only work with 512, 1024, and 2048 byte sectors */ bps = OSSwapLittleToHostInt16(b33->bpbBytesPerSec); @@ -207,9 +208,11 @@ /* Check to make sure valid sectors per cluster */ spc = b33->bpbSecPerClust; - if ((spc == 0 ) || (spc & (spc - 1))) + if ((spc == 0 ) || (spc & (spc - 1))) + { + free (buf); return -1; - + } if (OSSwapLittleToHostInt16(b50->bpbRootDirEnts) == 0) { /* It's FAT32 */ if (memcmp(((struct extboot *)bsp->bs710.bsExt)->exFileSysType, "FAT32 ", 8)) { @@ -669,7 +672,7 @@ st = (struct msdosdirstate *)(long) *dirIndex; if (!st) { - st=malloc (sizeof (*st)); + st=malloc (sizeof (struct msdosdirstate)); if (dirPath[0]) { uint8_t *buf=malloc(msdosclustersize); @@ -779,7 +782,10 @@ cluster |= ((uint32_t)OSReadLittleInt16 ((dirp->deHighClust),0)) <<16; size = (uint32_t)OSReadLittleInt32 ((dirp->deFileSize),0); if (size<=offset) + { + free (buf); return -1; + } nskip=offset/msdosclustersize; for (i=0;iHdr.CRC32 = 0; gST32->Hdr.CRC32 = crc32(0L, gST32, gST32->Hdr.HeaderSize); @@ -241,7 +241,7 @@ void finalizeEFIConfigTable(void ) { - if (archCpuType == CPU_TYPE_I386) + if (get_env(envarchCpuType) == CPU_TYPE_I386) { EFI_SYSTEM_TABLE_32 *efiSystemTable = gST32; @@ -265,7 +265,7 @@ uint32_t table ; EFI_GUID Guid; - if (archCpuType == CPU_TYPE_I386) + if (get_env(envarchCpuType) == CPU_TYPE_I386) { num = gST32->NumberOfTableEntries; @@ -278,7 +278,7 @@ msglog("EFI Configuration table :\n"); for (i=0; iwidth = kFailedBootWidth; ((boot_progress_element *)bootPict)->height = kFailedBootHeight; ((boot_progress_element *)bootPict)->yOffset = kFailedBootOffset; - if (gBootVolume->OSVersion[3] == '8') + if (((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] == '8') { ((boot_progress_element *)bootPict)->res[0] = size - 32; } @@ -806,13 +806,13 @@ Node *runtimeServicesNode = DT__AddChild(efiNode, "runtime-services"); Node *kernelCompatibilityNode = 0; // ??? not sure that it should be used like that (because it's maybe the kernel capability and not the cpu capability) - if (gBootVolume->OSVersion[3] > '6') + if (((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] > '6') { kernelCompatibilityNode = DT__AddChild(efiNode, "kernel-compatibility"); DT__AddProperty(kernelCompatibilityNode, "i386", sizeof(uint32_t), (EFI_UINT32*)&DEVICE_SUPPORTED); } - if (archCpuType == CPU_TYPE_I386) + if (get_env(envarchCpuType) == CPU_TYPE_I386) { // The value of the table property is the 32-bit physical address for the RuntimeServices table. // Since the EFI system table already has a pointer to it, we simply use the address of that pointer @@ -1005,9 +1005,9 @@ if (mps_p) { - uint64_t mps = ((uint64_t)((uint32_t)mps_p)); + //uint64_t mps = ((uint64_t)((uint32_t)mps_p)); - addConfigurationTable(&gEfiMpsTableGuid, &mps, NULL); + addConfigurationTable(&gEfiMpsTableGuid, ((uint64_t*)((uint32_t)mps_p)), NULL); } #if DEBUG_EFI @@ -1062,7 +1062,7 @@ setup_Smbios(); // Initialize the base table - if (archCpuType == CPU_TYPE_I386) + if (get_env(envarchCpuType) == CPU_TYPE_I386) { setupEfiTables(32); } Index: branches/cparm/i386/libsaio/misc.c =================================================================== --- branches/cparm/i386/libsaio/misc.c (revision 1971) +++ branches/cparm/i386/libsaio/misc.c (revision 1972) @@ -120,133 +120,6 @@ } #endif -static bool fix_random=true; - -struct ran_obj* random_init (int rmin, int rmax) -{ - if (rmin > rmax) - return false; - - int n = (rmax+1) - rmin; - - int tab[rand_tab_len]; - - struct ran_obj * self = (struct ran_obj * )malloc(sizeof(struct ran_obj)); - if (!self) { - return NULL; - } - bzero(self,sizeof(struct ran_obj)); - - self->rmin= rmin; - - self->n= n; - - int i; - srand(time18()); - int limit1= 0, limit2= 0, gate1 = 0, gate2 = 0; - - if (fix_random) { - limit1 = (rand() % 20) ; - limit2 = (rand() % 20) ; - } - - for (i = 0; i < rand_tab_len; i++){ - - tab[i] = (rand() % n) + rmin; - - if (fix_random) { - - if (i > 1 && gate1 < limit1 && tab[i]==tab[i-2]) { - i--; - gate1++; - - continue; - } - - if (i > 7 && gate2 < limit2 && tab[i]==tab[i-((rand() % 4)+5)]) { - i--; - gate2++; - - continue; - } - - } - self->tab[i]= tab[i]; - } - - - return self; -} - -int random (struct ran_obj* self) -{ - - struct ran_obj * ret = self ; - - static int wheel = 0; - int gate3 = 0; - int limit3 = 0; - static int retlst[rand_tab_len]; - - - int index; - int rn; - - if (!ret) { - return -1; // TODO: fix this - } - - if (fix_random) { - gate3 = rand() % 2; - } - - -retry: - index = rand() % rand_tab_len; - rn = ret->tab[index]; - ret->tab[index] = (rand() % ret->n) + ret->rmin; - - - if (fix_random) { - if ((gate3 && limit3 < 5) && (ret->tab[index] == rn)) { - limit3++; - goto retry; - } - retlst[wheel] = rn; - - if (wheel > 0 && limit3 < 5) { - - if (gate3 && (rn == retlst[wheel-1])) { - limit3++; - goto retry; - } - - if (gate3 && (wheel > 3 && rn==retlst[wheel-((rand() % 3)+1)]) && (limit3 < 5)) { - limit3++; - goto retry; - } - } - - wheel++; - } - - self = ret; - return rn; -} - -void random_free (struct ran_obj* self) -{ - if (self /* && self->sgn == random_obj_sgn */) { - free(self); - } - -} - -void usefixedrandom (bool opt) -{ - fix_random = opt; -} - //========================================================================== // Return the platform name for this hardware. // Index: branches/cparm/i386/libsaio/saio_internal.h =================================================================== --- branches/cparm/i386/libsaio/saio_internal.h (revision 1971) +++ branches/cparm/i386/libsaio/saio_internal.h (revision 1972) @@ -29,8 +29,13 @@ /* arc4random.c */ extern void arc4_init(void); -extern void arc4rand(void *ptr, u_int len, int reseed); -extern uint32_t arc4random(void); +extern void arc4random_buf(void *_buf, size_t n); +extern u_int32_t arc4random_uniform(u_int32_t upper_bound); +extern u_int32_t arc4random(void); +extern void arc4random_addrandom(u_char *dat, int datlen); +extern void arc4random_stir(void); +#define arc4random_unirange(lo,hi) arc4random_uniform(hi - lo + 1) + lo +#define arc4random_range(lo,hi) (arc4random() % (hi - lo + 1)) + lo /* asm.s */ extern void real_to_prot(void); @@ -57,7 +62,6 @@ extern void putc(int ch); extern void putca(int ch, int attr, int repeat); extern int getc(void); -extern void pause(); extern int readKeyboardStatus(void); extern int readKeyboardShiftFlags(void); extern unsigned int time18(void); @@ -97,14 +101,12 @@ /* cache.c */ -extern void CacheReset(); +extern void CacheReset(); extern void CacheInit(CICell ih, long blockSize); extern long CacheRead(CICell ih, char *buffer, long long offset, long length, long cache); /* console.c */ -extern bool gVerboseMode; -extern bool gErrors; extern void initBooterLog(void); extern void setupBooterLog(void); extern void putchar(int ch); @@ -122,9 +124,9 @@ extern void pause(void); /* disk.c */ -extern void rescanBIOSDevice(int biosdev); +extern void rescanBIOSDevice(int biosdev); extern struct DiskBVMap* diskResetBootVolumes(int biosdev); -extern void diskFreeMap(struct DiskBVMap *map); +extern void diskFreeMap(struct DiskBVMap *map); extern int testBiosread( int biosdev, unsigned long long secno ); extern BVRef diskScanBootVolumes(int biosdev, int *count); extern void diskSeek(BVRef bvr, long long position); @@ -148,7 +150,6 @@ u_int16_t *ucslen, u_int32_t bufsize, int byte_order ); /* load.c */ -extern bool gHaveKernelCache; extern long ThinFatFile(void **binary, unsigned long *length); extern long DecodeMachO(void *binary, entry_t *rentry, char **raddr, int *rsize); @@ -157,20 +158,26 @@ */ extern int decompress_lzss(u_int8_t *dst, u_int8_t *src, u_int32_t srclen); +/* lib.c */ +extern int bcd2dec(int b); +extern int dec2bcd(int d); + + /* memory.c */ -long AllocateKernelMemory( long inSize ); +extern long AllocateKernelMemory( long inSize ); -long +extern long AllocateMemoryRange(char * rangeName, long start, long length); /* misc.c */ extern void enableA20(void); extern void turnOffFloppy(void); - +#if UNUSED extern void random_free (struct ran_obj* self); extern int random (struct ran_obj* self); extern struct ran_obj* random_init (int rmin, int rmax); extern void usefixedrandom (bool opt); +#endif extern void getPlatformName(char *nameBuf); @@ -205,10 +212,10 @@ extern void re_set_env(const char *name , unsigned long long value) ; extern void unset_env(const char *name); extern void free_platform_env(void); +void showError(void); void debug_platform_env(void); - /* stringTable.c */ extern char * newStringFromList(char **list, int *size); extern int stringLength(const char *table, int compress); @@ -221,8 +228,11 @@ extern const char * getStringForKey(const char * key, config_file_t *config); extern bool getBoolForKey(const char *key, bool *val, config_file_t *configBuff); extern bool getIntForKey(const char *key, int *val, config_file_t *configBuff); +extern config_file_t *resolveConfig(config_file_t *config); +#if UNUSED extern bool getColorForKey(const char *key, unsigned int *val, config_file_t *configBuff); extern bool getDimensionForKey( const char *key, unsigned int *value, config_file_t *config, unsigned int dimension_max, unsigned int object_size ); +#endif extern int loadConfigFile(const char *configFile, config_file_t *configBuff); extern int loadBooterConfig(void); extern int loadSystemConfig(void); @@ -238,11 +248,11 @@ extern int ParseXMLFile( char * buffer, TagPtr * dict ); /* sys.c */ -extern BVRef getBootVolumeRef( const char * path, const char ** outPath ); +extern BVRef getBootVolumeRef( const char * path, const char ** outPath ); extern long LoadVolumeFile(BVRef bvr, const char *fileSpec); extern long LoadFile(const char *fileSpec); extern long ReadFileAtOffset(const char * fileSpec, void *buffer, uint64_t offset, uint64_t length); -extern long LoadThinFatFile(const char *fileSpec, void **binary); +extern long LoadThinFatFile(const char *fileSpec, void **binary); extern long GetDirEntry(const char *dirSpec, long long *dirIndex, const char **name, long *flags, long *time); extern long GetFileInfo(const char *dirSpec, const char *name, @@ -261,6 +271,7 @@ extern int write(int fdesc, const char *buf, int count); extern int writebyte(int fdesc, char value); extern int writeint(int fdesc, int value); +extern struct iob * iob_from_fdesc(int fdesc); extern int b_lseek(int fdesc, int addr, int ptr); extern int tell(int fdesc); extern const char * systemConfigDir(void); @@ -281,15 +292,20 @@ extern void setBootGlobals(BVRef chain); extern int getDeviceDescription(BVRef volume, char *str); -extern int gBootFileType; -extern BVRef gBootVolume; -extern BVRef gBIOSBootVolume; +/* rtc.c */ +extern void rtc_read_clock(struct tm *time) ; /* smp.c */ extern void * getMPSTable(); +/* time.c */ +extern int gettimeofday(struct timeval *tv, void *tz); + /* uterror.c */ -extern jmp_buf h_buf_error; +extern jmp_buf uterror; extern void init_ut_fnc(void); +//#define LOCALIZE +//extern int localVPrintf(const char *format, va_list ap); + #endif /* !__LIBSAIO_SAIO_INTERNAL_H */ Index: branches/cparm/i386/libsaio/utarray.h =================================================================== --- branches/cparm/i386/libsaio/utarray.h (revision 1971) +++ branches/cparm/i386/libsaio/utarray.h (revision 1972) @@ -1,5 +1,5 @@ /* -Copyright (c) 2008-2011, Troy D. Hanson http://uthash.sourceforge.net +Copyright (c) 2008-2012, Troy D. Hanson http://uthash.sourceforge.net All rights reserved. Redistribution and use in source and binary forms, with or without @@ -27,7 +27,7 @@ #ifndef UTARRAY_H #define UTARRAY_H -#define UTARRAY_VERSION 1.9.4 +#define UTARRAY_VERSION 1.9.6 #ifdef __GNUC__ #define _UNUSED_ __attribute__ ((__unused__)) @@ -37,8 +37,18 @@ #include "libsaio.h" -#define oom() longjmp(h_buf_error,-1) - +#ifndef utarray_oom +#define utarray_oom() longjmp(uterror,-1) +#endif +#ifndef __utarray_malloc +#define __utarray_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef __utarray_free +#define __utarray_free(ptr) free(ptr) /* free fcn */ +#endif +#ifndef __utarray_realloc +#define __utarray_realloc(ptr,sz) realloc(ptr,sz) /* realloc fcn */ +#endif typedef void (ctor_f)(void *dst, const void *src); typedef void (dtor_f)(void *elt); typedef void (init_f)(void *elt); @@ -68,25 +78,25 @@ (a)->icd.dtor(utarray_eltptr(a,_ut_i)); \ } \ } \ - free((a)->d); \ + __utarray_free((a)->d); \ } \ (a)->n=0; \ } while(0) #define utarray_new(a,_icd) do { \ - a=(UT_array*)malloc(sizeof(UT_array)); \ + a=(UT_array*)utarray_malloc(sizeof(UT_array)); \ utarray_init(a,_icd); \ } while(0) #define utarray_free(a) do { \ utarray_done(a); \ - free(a); \ + __utarray_free(a); \ } while(0) #define utarray_reserve(a,by) do { \ if (((a)->i+by) > ((a)->n)) { \ while(((a)->i+by) > ((a)->n)) { (a)->n = ((a)->n ? (2*(a)->n) : 8); } \ - if ( ((a)->d=(char*)realloc((a)->d, (a)->n*(a)->icd.sz)) == NULL) oom(); \ + if ( ((a)->d=(char*)__utarray_realloc((a)->d, (a)->n*(a)->icd.sz)) == NULL) utarray_oom(); \ } \ } while(0) @@ -185,10 +195,10 @@ (a)->i -= (len); \ } while(0) -#define utarray_renew(a,u) do { \ - if (a) utarray_clear(a); \ - else utarray_new((a),(u)); \ -} while(0); +#define utarray_renew(a,u) do { \ + if (a) utarray_clear(a); \ + else utarray_new((a),(u)); \ +} while(0) #define utarray_clear(a) do { \ if ((a)->i > 0) { \ @@ -210,6 +220,7 @@ #define utarray_front(a) (((a)->i) ? (_utarray_eltptr(a,0)) : NULL) #define utarray_next(a,e) (((e)==NULL) ? utarray_front(a) : ((((a)->i) > (utarray_eltidx(a,e)+1)) ? _utarray_eltptr(a,utarray_eltidx(a,e)+1) : NULL)) +#define utarray_prev(a,e) (((e)==NULL) ? utarray_back(a) : ((utarray_eltidx(a,e) > 0) ? _utarray_eltptr(a,utarray_eltidx(a,e)-1) : NULL)) #define utarray_back(a) (((a)->i) ? (_utarray_eltptr(a,(a)->i-1)) : NULL) #define utarray_eltidx(a,e) (((char*)(e) >= (char*)((a)->d)) ? (((char*)(e) - (char*)((a)->d))/(a)->icd.sz) : -1) @@ -220,7 +231,7 @@ } static void utarray_str_dtor(void *elt) { char **eltc = (char**)elt; - if (*eltc) free(*eltc); + if (*eltc) __utarray_free(*eltc); } static const UT_icd ut_str_icd _UNUSED_ = {sizeof(char*),NULL,utarray_str_cpy,utarray_str_dtor}; static const UT_icd ut_int_icd _UNUSED_ = {sizeof(int),NULL,NULL,NULL}; Index: branches/cparm/i386/MakeInc.dir =================================================================== --- branches/cparm/i386/MakeInc.dir (revision 1971) +++ branches/cparm/i386/MakeInc.dir (revision 1972) @@ -39,7 +39,6 @@ .SUFFIXES: .s .i .c .o -ifeq "makedep" "NO" .c.o .m.o: $(CC) $(CPPFLAGS) $(CFLAGS) $(DEFINES) -c $(INC) $< -o $(OBJROOT)/$*.o @@ -48,35 +47,15 @@ $(OBJROOT)/%.o: %.m $(CC) $(CPPFLAGS) $(CFLAGS) $(DEFINES) -c $(INC) $< -o $(OBJROOT)/$*.o -else -.c.o .m.o: - $(CC) $(CPPFLAGS) $(CFLAGS) $(DEFINES) -c $(INC) $< -o $(OBJROOT)/$*.o \ - -MD -dependency-file $(OBJROOT)/$*.d - md -u $(OBJROOT)/Makedep -f -d $(OBJROOT)/$*.d -$(OBJROOT)/%.o: %.c - $(CC) $(CPPFLAGS) $(CFLAGS) $(DEFINES) -c $(INC) $< -o $(OBJROOT)/$*.o \ - -MD -dependency-file $(OBJROOT)/$*.d - md -u $(OBJROOT)/Makedep -f -d $(OBJROOT)/$*.d - -$(OBJROOT)/%.o: %.m - $(CC) $(CPPFLAGS) $(CFLAGS) $(DEFINES) -c $(INC) $< -o $(OBJROOT)/$*.o \ - -MD -dependency-file $(OBJROOT)/$*.d - md -u $(OBJROOT)/Makedep -f -d $(OBJROOT)/$*.d -endif - -#.s.o: -# cc $(INC) -E $< > $(OBJROOT)/$*.o2 -# $(AS) -o $(OBJROOT)/$@ $(OBJROOT)/$*.o2 - .s.o: - gcc $(CPPFLAGS) -c $(INC) -arch i386 -o $(OBJROOT)/$(@F) $< + $(CC) $(CPPFLAGS) -no-integrated-as -c $(INC) -arch i386 -o $(OBJROOT)/$(@F) $< boot2.o: - gcc $(CPPFLAGS) -Wa,-n -c $(INC) -arch i386 -o $(OBJROOT)/$(@F) boot2.s + $(CC) $(CPPFLAGS) -Wa,-n -c $(INC) -no-integrated-as -arch i386 -o $(OBJROOT)/$(@F) boot2.s $(OBJROOT)/%.o: %.s - gcc $(CPPFLAGS) -c $(INC) -arch i386 -o $(OBJROOT)/$(@F) $< + $(CC) $(CPPFLAGS) -no-integrated-as -c $(INC) -arch i386 -o $(OBJROOT)/$(@F) $< $(DIRS_NEEDED) $(INSTALLDIR) $(SRCROOT): $(MKDIRS) $@ Index: branches/cparm/i386/boot2/graphics.c =================================================================== --- branches/cparm/i386/boot2/graphics.c (revision 1971) +++ branches/cparm/i386/boot2/graphics.c (revision 1972) @@ -32,6 +32,7 @@ #include "appleClut8.h" #include "bootstruct.h" #include "modules.h" +#include "platform.h" #define VIDEO(x) (bootArgs->Video.v_ ## x) @@ -617,7 +618,7 @@ if ( mode == GRAPHICS_MODE ) { if ( (err=initGraphicsMode ()) == errSuccess ) { - if (gVerboseMode) { + if (get_env(envgVerboseMode)) { // Tell the kernel to use text mode on a linear frame buffer display bootArgs->Video.v_display = FB_TEXT_MODE; } else { Index: branches/cparm/i386/boot2/boot.c =================================================================== --- branches/cparm/i386/boot2/boot.c (revision 1971) +++ branches/cparm/i386/boot2/boot.c (revision 1972) @@ -61,6 +61,7 @@ #include "modules.h" #include "xml.h" #include "options.h" +#include "drivers.h" #ifndef DEBUG_BOOT #define DEBUG_BOOT 0 @@ -78,28 +79,22 @@ char rootPath[ROOT_PATH_LEN]; } PlatformInfo; -static char gBootKernelCacheFile[Cache_len_name]; -static char gMKextName[Cache_len_name]; - static BVRef bvChain; static bool forcecache = false; +static char gBootKernelCacheFile[Cache_len_name]; +static char gMKextName[Cache_len_name]; static void zeroBSS(void); -#ifdef SAFE_MALLOC -static inline void malloc_error(char *addr, size_t size, const char *file, int line); -#else -static inline void malloc_error(char *addr, size_t size); -#endif static int ExecKernel(void *binary); static void getRootDevice(); -#ifdef NBP_SUPPORT -static bool gUnloadPXEOnExit = false; -#endif static bool find_file_with_ext(const char* dir, const char *ext, const char * name_compare, size_t ext_size); static bool found_extra_kext(void); static void determineCpuArch(void); static void init_pic(void); void getKernelCachePath(void); +#ifdef NBP_SUPPORT +static bool gUnloadPXEOnExit = false; +#endif /* @@ -159,6 +154,7 @@ static void init_pic(void) { /* Remap IRQ's */ + /* outb(0x20, 0x11); outb(0xA0, 0x11); outb(0x21, 0x20); @@ -167,7 +163,7 @@ outb(0xA1, 0x02); outb(0x21, 0x01); outb(0xA1, 0x01); - + */ //outb(0x70, inb(0x70)|0x80); /* Disable NMI */ outb(0x21, 0xff); /* Maskout all interrupts Pic1 */ @@ -184,10 +180,10 @@ bootArgs->kaddr = bootArgs->ksize = 0; - if(gBootVolume->OSVersion[3] <= '6') + if(((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] <= '6') { bootArgs->Header.Version = kBootArgsVersion1; - bootArgs->Header.Revision = gBootVolume->OSVersion[3]; + bootArgs->Header.Revision = ((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3]; } else { @@ -196,7 +192,7 @@ bootArgs->Header.Version = kBootArgsVersion; bootArgs->Header.Revision = kBootArgsRevision; #else - if(gBootVolume->OSVersion[3] >= '7') + if(((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] >= '7') { bootArgs->Header.Version = 2; bootArgs->Header.Revision = 0; @@ -216,29 +212,22 @@ // Load boot drivers from the specifed root path. - if (!gHaveKernelCache) + if (!get_env(envgHaveKernelCache)) { LoadDrivers("/"); } - if (gErrors) - { - printf("Errors encountered while starting up the computer.\n"); -#if DEBUG_BOOT - printf("Pausing %d seconds...\n", kBootErrorTimeout); - sleep(kBootErrorTimeout); -#endif - } + showError(); execute_hook("md0Ramdisk", NULL, NULL, NULL, NULL, NULL, NULL); setupFakeEfi(); - verbose("Starting Darwin %s\n",( archCpuType == CPU_TYPE_I386 ) ? "x86" : "x86_64"); + verbose("Starting Darwin %s\n",( get_env(envarchCpuType) == CPU_TYPE_I386 ) ? "x86" : "x86_64"); #ifdef NBP_SUPPORT // Cleanup the PXE base code. - if ( (gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit ) + if ( (get_env(envgBootFileType) == kNetworkDeviceType) && gUnloadPXEOnExit ) { if ( (ret = nbpUnloadBaseCode()) != nbpStatusSuccess ) { @@ -277,7 +266,7 @@ __setVideoMode( GRAPHICS_MODE ); - if(!gVerboseMode) + if(!get_env(envgVerboseMode)) { __drawColorRectangle(0, 0, DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, 0x01); @@ -317,7 +306,7 @@ execute_hook("Kernel Start", (void*)kernelEntry, (void*)bootArgs, NULL, NULL, NULL, NULL); // Notify modules that the kernel is about to be started - switch (gBootVolume->OSVersion[3]) { + switch (((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3]) { case '4': case '5': case '6': @@ -342,7 +331,7 @@ IMPS_LAPIC_WRITE(LAPIC_LVT1, LAPIC_ICR_DM_NMI); #endif - switch (gBootVolume->OSVersion[3]) { + switch (((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3]) { case '4': case '5': case '6': @@ -425,8 +414,6 @@ init_ut_fnc(); - arc4_init(); - initBooterLog(); // Initialize boot info structure. @@ -435,14 +422,19 @@ // Scan and record the system's hardware information. scan_platform(); + // Pseudo-random generator initialization. + arc4_init(); + set_env(envgBIOSDev, (BIOSDev = biosdev & kBIOSDevMask)); set_env(envShouldboot, false); - set_env(envkCache, (uint32_t)gBootKernelCacheFile); + set_env(envkCacheFile, (uint32_t)gBootKernelCacheFile); set_env(envMKextName, (uint32_t)gMKextName); - + set_env(envHFSLoadVerbose, 1); + set_env(envarchCpuType, CPU_TYPE_I386); + set_env(envgHaveKernelCache, false); + InitBootPrompt(); - - + // First get info for boot volume. scanBootVolumes(BIOSDev, 0); @@ -501,15 +493,14 @@ // Create a separated bvr chain using the specified filters. bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &devcnt); - safe_set_env(envgDeviceCount,devcnt); + safe_set_env(envgDeviceCount,devcnt); - - gBootVolume = selectBootVolume(bvChain); + //gBootVolume = selectBootVolume(bvChain); + safe_set_env(envgBootVolume, (uint32_t)selectBootVolume(bvChain)); + - LoadBundles("/Extra/"); + LoadBundles("/Extra/"); - load_all_internal_modules(); - // Loading preboot ramdisk if exists. execute_hook("loadPrebootRAMDisk", NULL, NULL, NULL, NULL, NULL, NULL); @@ -538,8 +529,8 @@ } #if DEBUG - printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags); - printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags); + printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", ((BVRef)(uint32_t)get_env(envgBootVolume)), ((BVRef)(uint32_t)get_env(envgBootVolume))->biosdev, ((BVRef)(uint32_t)get_env(envgBootVolume))->part_no, ((BVRef)(uint32_t)get_env(envgBootVolume))->flags); + printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", ((BVRef)(uint32_t)get_env(envgBIOSBootVolume)), ((BVRef)(uint32_t)get_env(envgBIOSBootVolume))->biosdev, ((BVRef)(uint32_t)get_env(envgBIOSBootVolume))->part_no, ((BVRef)(uint32_t)get_env(envgBIOSBootVolume))->flags); getc(); #endif @@ -567,7 +558,6 @@ // Initialize globals. safe_set_env(envSysConfigValid, false); - gErrors = false; status = getBootOptions(firstRun); firstRun = false; @@ -580,7 +570,7 @@ if ( status == -1 ) { // gBootVolume == NULL usually means the user hit escape. - if(gBootVolume == NULL) + if(((BVRef)(uint32_t)get_env(envgBootVolume)) == NULL) { freeFilteredBVChain(bvChain); @@ -602,11 +592,13 @@ { if (strncmp(val, "x86_64", 4) == 0) { - archCpuType = CPU_TYPE_X86_64; + safe_set_env(envarchCpuType, CPU_TYPE_X86_64); + } else if (strncmp(val, "i386", 4) == 0) { - archCpuType = CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); + } else { @@ -629,7 +621,7 @@ if (((get_env(envgBootMode) & kBootModeSafe) == 0) && !get_env(envgOverrideKernel) && - (gBootFileType == kBlockDeviceType) && + (get_env(envgBootFileType) == kBlockDeviceType) && (gMKextName[0] == '\0') && !getValueForBootKey(bootArgs->CommandLine, kIgnorePrelinkKern, &val, &len)) { @@ -649,7 +641,7 @@ trycache = false; } - verbose("Loading Darwin %s\n", gBootVolume->OSVersion); + verbose("Loading Darwin %s\n", ((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion); { long cachetime, kerneltime = 0, exttime; if (trycache && !forcecache) do { @@ -665,7 +657,7 @@ break; } } - else if (gBootVolume->kernelfound != true) // Should never happen. + else if (((BVRef)(uint32_t)get_env(envgBootVolume))->kernelfound != true) // Should never happen. { bootFile = kDefaultKernel; goto out; @@ -711,12 +703,12 @@ { bootFile = gBootKernelCacheFile; verbose("Loading kernel cache %s\n", bootFile); - if (gBootVolume->OSVersion[3] > '6') + if (((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] > '6') { ret = LoadThinFatFile(bootFile, &binary); - if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) + if ((ret <= 0) && (get_env(envarchCpuType) == CPU_TYPE_X86_64)) { - archCpuType = CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); ret = LoadThinFatFile(bootFile, &binary); } } @@ -760,9 +752,9 @@ verbose("Loading kernel %s\n", bootFileSpec); ret = LoadThinFatFile(bootFileSpec, &binary); - if (ret <= 0 && archCpuType == CPU_TYPE_X86_64) + if ((ret <= 0) && (get_env(envarchCpuType) == CPU_TYPE_X86_64)) { - archCpuType = CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); ret = LoadThinFatFile(bootFileSpec, &binary); } @@ -780,7 +772,7 @@ sleep(1); #ifdef NBP_SUPPORT - if (gBootFileType == kNetworkDeviceType) + if (get_env(envgBootFileType) == kNetworkDeviceType) { // Return control back to PXE. Don't unload PXE base code. gUnloadPXEOnExit = false; @@ -810,7 +802,7 @@ } } #ifdef NBP_SUPPORT - if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) + if ((get_env(envgBootFileType) == kNetworkDeviceType) && gUnloadPXEOnExit) { nbpUnloadBaseCode(); } @@ -821,11 +813,12 @@ { if (cpu_mode_is64bit()) { - archCpuType = CPU_TYPE_X86_64; + safe_set_env(envarchCpuType, CPU_TYPE_X86_64); + } else { - archCpuType = CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); } } @@ -864,11 +857,11 @@ } else { - if(gBootVolume->OSVersion[3] > '6') + if(((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] > '6') { sprintf(gBootKernelCacheFile, "%s", kDefaultCachePath); } - else if(gBootVolume->OSVersion[3] <= '6') + else if(((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] <= '6') { PlatformInfo *platformInfo = malloc(sizeof(PlatformInfo)); @@ -921,7 +914,7 @@ DBG("Adler32: %08lX\n",Adler32); - if (gBootVolume->OSVersion[3] < '6') + if (((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] < '6') { long flags, cachetime; int ret = -1; @@ -938,7 +931,7 @@ } } else if (Adler32) - sprintf(gBootKernelCacheFile, "%s_%s.%08lX", kDefaultCachePath, (archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64", Adler32); //Snow Leopard + sprintf(gBootKernelCacheFile, "%s_%s.%08lX", kDefaultCachePath, (get_env(envarchCpuType) == CPU_TYPE_I386) ? "i386" : "x86_64", Adler32); //Snow Leopard } } @@ -981,7 +974,7 @@ // // Try an alternate method for getting the root UUID on boot helper partitions. // - if (gBootVolume->flags & kBVFlagBooter) + if (((BVRef)(uint32_t)get_env(envgBootVolume))->flags & kBVFlagBooter) { if((loadHelperConfig() == 0) && getValueForKey(kHelperRootUUIDKey, &val, &cnt, &bootInfo->helperConfig) ) @@ -1020,7 +1013,7 @@ goto out; } - if (gBootVolume->fs_getuuid && gBootVolume->fs_getuuid (gBootVolume, bootInfo->uuidStr) == 0) + if (((BVRef)(uint32_t)get_env(envgBootVolume))->fs_getuuid && (((BVRef)(uint32_t)get_env(envgBootVolume))->fs_getuuid (((BVRef)(uint32_t)get_env(envgBootVolume)), bootInfo->uuidStr) == 0)) { verbose("Setting boot-uuid to: %s\n", bootInfo->uuidStr); //uuidSet = true; @@ -1036,55 +1029,41 @@ SetgRootDevice(val); } -static bool find_file_with_ext(const char* dir, const char *ext, const char * name_compare, size_t ext_size) +static bool find_file_with_ext(const char* dir, const char *ext, const char * name_to_compare, size_t ext_size) { - char* name; - long flags; - long time; - struct dirstuff* moduleDir = opendir(dir); - while(readdir(moduleDir, (const char**)&name, &flags, &time) >= 0) - { - int len = strlen(name); + long ret, length, flags, time; + long long index; + const char * name; + + DBG("FileLoadBundles in %s\n",dirSpec); + + index = 0; + while (1) { + ret = GetDirEntry(dir, &index, &name, &flags, &time); + if (ret == -1) break; - if (len >= ext_size) - { - if(strcmp(&name[len - ext_size], ext) == 0) - { - if (name_compare) - { - if (strcmp(name, name_compare) == 0) - { - DBG("found : %s\n", name); - closedir(moduleDir); - return true; - } - } - else - { - DBG("found : %s\n", name); - closedir(moduleDir); - return true; - } - } -#if DEBUG_BOOT - else - { - DBG("Ignoring %s\n", name); - } -#endif - } -#if DEBUG_BOOT - else - { - DBG("Ignoring %s\n", name); - } -#endif - } - - if (moduleDir) { - closedir(moduleDir); + // Make sure this is not a directory. + if ((flags & kFileTypeMask) != kFileTypeFlat) continue; + + // Make sure this is a kext or mkext. + length = strlen(name); + if (strcmp(name + length - ext_size, ext)) continue; - } + if (name_to_compare) + { + if (strcmp(name, name_to_compare) == 0) + { + DBG("found : %s\n", name); + return true; + } + } + else + { + DBG("found : %s\n", name); + return true; + } + + } return false; } @@ -1098,9 +1077,9 @@ { #define EXTENSIONS "Extensions" #define MKEXT_EXT ".mkext" -#define MKEXT_EXT_SIZE sizeof("mkext") +#define MKEXT_EXT_SIZE strlen(MKEXT_EXT) #define KEXT_EXT ".kext" -#define KEXT_EXT_SIZE sizeof("kext") +#define KEXT_EXT_SIZE strlen(KEXT_EXT) long flags; long exttime; Index: branches/cparm/i386/boot2/boot.h =================================================================== --- branches/cparm/i386/boot2/boot.h (revision 1971) +++ branches/cparm/i386/boot2/boot.h (revision 1972) @@ -45,8 +45,6 @@ kF10Key = 0x4400 }; - - /* * Flags to the booter or kernel */ @@ -83,33 +81,7 @@ extern void common_boot(int biosdev); extern BVRef getBvChain(void); -/* - * drivers.c - */ -extern long LoadDrivers(char * dirSpec); -extern long DecodeKernel(void *binary, entry_t *rentry, char **raddr, int *rsize); -typedef long (*FileLoadDrivers_t)(char *dirSpec, long plugin); -/*! - Hookable function pointer called during the driver loading phase that - allows other code to cause additional drivers to be loaded. - */ -//extern struct multiboot_info *gMI; - - -struct compressed_kernel_header { - u_int32_t signature; - u_int32_t compress_type; - u_int32_t adler32; - u_int32_t uncompressed_size; - u_int32_t compressed_size; - u_int32_t reserved[11]; - char platform_name[PLATFORM_NAME_LEN]; - char root_path[ROOT_PATH_LEN]; - u_int8_t data[0]; -}; -typedef struct compressed_kernel_header compressed_kernel_header; - /* * prompt.c */ Index: branches/cparm/i386/boot2/drivers.c =================================================================== --- branches/cparm/i386/boot2/drivers.c (revision 1971) +++ branches/cparm/i386/boot2/drivers.c (revision 1972) @@ -91,6 +91,8 @@ static char * gTempSpec; static char * gFileName; +long LoadDrivers( char * dirSpec ); +long DecodeKernel(void *binary, entry_t *rentry, char **raddr, int *rsize); long InitDriverSupport(void); long FileLoadDrivers(char *dirSpec, long plugin); long LoadDriverMKext(char *fileSpec); @@ -156,7 +158,7 @@ int step = 0; execute_hook("ramDiskLoadDrivers", &step, NULL, NULL, NULL, NULL, NULL); #ifdef NBP_SUPPORT - if ( gBootFileType == kNetworkDeviceType ) + if ( get_env(envgBootFileType) == kNetworkDeviceType ) { if (NetLoadDrivers(dirSpec) != 0) { error("Could not load drivers from the network\n"); @@ -165,7 +167,7 @@ } else #endif - if ( gBootFileType == kBlockDeviceType ) + if ( get_env(envgBootFileType) == kBlockDeviceType ) { // First try to load Extra extensions from the ramdisk if isn't aliased as bt(0,0). @@ -176,7 +178,7 @@ // First try a specfic OS version folder ie 10.5 - sprintf(dirSpecExtra, "/Extra/%s/", (char*)gBootVolume->OSVersion); + sprintf(dirSpecExtra, "/Extra/%s/", (char*)((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion); if (FileLoadDrivers(dirSpecExtra, 0) != 0) { // Next try to load Extra extensions from the selected root partition. @@ -185,10 +187,11 @@ { // If failed, then try to load Extra extensions from the boot partition // in case we have a separate booter partition or a bt(0,0) aliased ramdisk. - if (!(gBIOSBootVolume->biosdev == gBootVolume->biosdev && gBIOSBootVolume->part_no == gBootVolume->part_no)) + //if (!(gBIOSBootVolume->biosdev == gBootVolume->biosdev && gBIOSBootVolume->part_no == gBootVolume->part_no)) + if (!((((BVRef)(uint32_t)get_env(envgBIOSBootVolume))->biosdev == ((BVRef)(uint32_t)get_env(envgBootVolume))->biosdev) && (((BVRef)(uint32_t)get_env(envgBIOSBootVolume))->part_no == ((BVRef)(uint32_t)get_env(envgBootVolume))->part_no))) { // First try a specfic OS version folder ie 10.5 - sprintf(dirSpecExtra, "bt(0,0)/Extra/%s/", (char*)gBootVolume->OSVersion); + sprintf(dirSpecExtra, "bt(0,0)/Extra/%s/", (char*)((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion); if (FileLoadDrivers(dirSpecExtra, 0) != 0) { // Next we'll try the base @@ -206,7 +209,7 @@ #ifdef BOOT_HELPER_SUPPORT // TODO: fix this, the order does matter, and it's not correct now. // Also try to load Extensions from boot helper partitions. - if (gBootVolume->flags & kBVFlagBooter) + if (((BVRef)(uint32_t)get_env(envgBootVolume))->flags & kBVFlagBooter) { strlcpy(dirSpecExtra, "/com.apple.boot.P/System/Library/", sizeof(dirSpecExtra)); if (FileLoadDrivers(dirSpecExtra, 0) != 0) @@ -810,25 +813,25 @@ printf("adler mismatch\n"); return -1; } - char* BootKernelCacheFile = (char*)(uint32_t)get_env(envkCache); - if (((get_env(envgBootMode) & kBootModeSafe) == 0) && (BootKernelCacheFile[0] != '\0') && gBootVolume->OSVersion[3] > '6') + char* BootKernelCacheFile = (char*)(uint32_t)get_env(envkCacheFile); + if (((get_env(envgBootMode) & kBootModeSafe) == 0) && (BootKernelCacheFile[0] != '\0') && ((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] > '6') safe_set_env(envAdler32, kernel_header->adler32); } { unsigned long len; ret = ThinFatFile(&binary, &len); - if (ret == 0 && len == 0 && archCpuType==CPU_TYPE_X86_64) + if ((ret == 0) && (len == 0) && (get_env(envarchCpuType)==CPU_TYPE_X86_64)) { - archCpuType=CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); ThinFatFile(&binary, &len); } ret = DecodeMachO(binary, rentry, raddr, rsize); - if (ret<0 && archCpuType==CPU_TYPE_X86_64) + if (ret<0 && get_env(envarchCpuType)==CPU_TYPE_X86_64) { - archCpuType=CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); ret = DecodeMachO(binary, rentry, raddr, rsize); } } Index: branches/cparm/i386/boot2/drivers.h =================================================================== --- branches/cparm/i386/boot2/drivers.h (revision 1971) +++ branches/cparm/i386/boot2/drivers.h (revision 1972) @@ -40,7 +40,22 @@ #include "xml.h" #include "modules.h" -long LoadDrivers( char * dirSpec ); -long DecodeKernel(void *binary, entry_t *rentry, char **raddr, int *rsize); +struct compressed_kernel_header { + u_int32_t signature; + u_int32_t compress_type; + u_int32_t adler32; + u_int32_t uncompressed_size; + u_int32_t compressed_size; + u_int32_t reserved[11]; + char platform_name[PLATFORM_NAME_LEN]; + char root_path[ROOT_PATH_LEN]; + u_int8_t data[0]; +}; +typedef struct compressed_kernel_header compressed_kernel_header; +extern long LoadDrivers(char * dirSpec); +extern long DecodeKernel(void *binary, entry_t *rentry, char **raddr, int *rsize); + +typedef long (*FileLoadDrivers_t)(char *dirSpec, long plugin); + #endif /* _BOOT2_DRIVERS_H */ \ No newline at end of file Index: branches/cparm/i386/boot2/options.c =================================================================== --- branches/cparm/i386/boot2/options.c (revision 1971) +++ branches/cparm/i386/boot2/options.c (revision 1972) @@ -585,8 +585,9 @@ int optionKey; // Initialize default menu selection entry. - gBootVolume = menuBVR = selectBootVolume(getBvChain()); - + /*gBootVolume =*/ menuBVR = selectBootVolume(getBvChain()); + safe_set_env(envgBootVolume, (uint32_t)menuBVR); + if (biosDevIsCDROM((int)get_env(envgBIOSDev))) { isCDROM = true; } else { @@ -690,7 +691,7 @@ stop("Couldn't allocate memory for the device name\n"); //TODO: Find a better stategie return -1; } - getBootVolumeDescription(gBootVolume, name, 79, false); + getBootVolumeDescription(((BVRef)(uint32_t)get_env(envgBootVolume)), name, 79, false); prompt = malloc(256); if (!prompt) { free(name); @@ -745,7 +746,8 @@ // Look at partitions hosting OS X other than the CD-ROM for (bvr = getBvChain(); bvr; bvr=bvr->next) { if ((bvr->flags & kBVFlagSystemVolume) && bvr->biosdev != (int)get_env(envgBIOSDev)) { - gBootVolume = bvr; + //gBootVolume = bvr; + safe_set_env(envgBootVolume, (uint32_t)bvr); } } } @@ -889,7 +891,8 @@ showBootPrompt(nextRow, showPrompt); break; } - gBootVolume = menuBVR; + //gBootVolume = menuBVR; + safe_set_env(envgBootVolume, (uint32_t)menuBVR); setRootVolume(menuBVR); safe_set_env(envgBIOSDev,menuBVR->biosdev); break; @@ -904,7 +907,8 @@ // if the user enabled rescanning the optical drive. // Otherwise boot the default boot volume. if (get_env(envgEnableCDROMRescan)) { - gBootVolume = NULL; + //gBootVolume = NULL; + safe_set_env(envgBootVolume, (uint32_t)NULL); clearBootArgs(); } break; @@ -914,7 +918,9 @@ scanDisks(); - gBootVolume = NULL; + //gBootVolume = NULL; + safe_set_env(envgBootVolume, (uint32_t)NULL); + clearBootArgs(); break; @@ -992,11 +998,11 @@ // Update the unit and partition number. - if ( gBootVolume ) + if ( ((BVRef)(uint32_t)get_env(envgBootVolume)) ) { - if (!( gBootVolume->flags & kBVFlagNativeBoot )) + if (!( ((BVRef)(uint32_t)get_env(envgBootVolume))->flags & kBVFlagNativeBoot )) { - readBootSector( gBootVolume->biosdev, gBootVolume->part_boff, + readBootSector( ((BVRef)(uint32_t)get_env(envgBootVolume))->biosdev, ((BVRef)(uint32_t)get_env(envgBootVolume))->part_boff, (void *) 0x7c00 ); // @@ -1004,13 +1010,13 @@ // foreign booter. // - chainbootdev = gBootVolume->biosdev; + chainbootdev = ((BVRef)(uint32_t)get_env(envgBootVolume))->biosdev; chainbootflag = 1; return 1; } - setRootVolume(gBootVolume); + setRootVolume(((BVRef)(uint32_t)get_env(envgBootVolume))); } // If no boot volume fail immediately because we're just going to fail @@ -1059,11 +1065,11 @@ if (strcmp( bootInfo->bootFile, kDefaultKernel ) != 0) { safe_set_env(envgOverrideKernel,true); } - } else if (gBootVolume->kernelfound == true) { + } else if (((BVRef)(uint32_t)get_env(envgBootVolume))->kernelfound == true) { strlcpy( bootInfo->bootFile, kDefaultKernel, sizeof(bootInfo->bootFile) ); } else { - printf("No kernel found on this volume : hd(%d,%d)\n", BIOS_DEV_UNIT(gBootVolume), gBootVolume->part_no); + printf("No kernel found on this volume : hd(%d,%d)\n", BIOS_DEV_UNIT(((BVRef)(uint32_t)get_env(envgBootVolume))), ((BVRef)(uint32_t)get_env(envgBootVolume))->part_no); sleep(1); return -1; } @@ -1120,8 +1126,9 @@ if(!get_env(envShouldboot)) { - gVerboseMode = getValueForKey( kVerboseModeFlag, &val, &cnt, DEFAULT_BOOT_CONFIG ) || + bool gVerboseMode = getValueForKey( kVerboseModeFlag, &val, &cnt, DEFAULT_BOOT_CONFIG ) || getValueForKey( kSingleUserModeFlag, &val, &cnt, DEFAULT_BOOT_CONFIG ); + safe_set_env(envgVerboseMode, gVerboseMode); long gBootMode = ( getValueForKey( kSafeModeFlag, &val, &cnt, DEFAULT_BOOT_CONFIG ) ) ? kBootModeSafe : kBootModeNormal; Index: branches/cparm/i386/boot2/Makefile =================================================================== --- branches/cparm/i386/boot2/Makefile (revision 1971) +++ branches/cparm/i386/boot2/Makefile (revision 1972) @@ -27,7 +27,7 @@ CFLAGS = $(RC_CFLAGS) $(OPTIM) $(MORECPP) -arch i386 -g -Wmost -Werror -fno-stack-protector \ -fno-builtin -DSAIO_INTERNAL_USER -static $(OMIT_FRAME_POINTER_CFLAG) \ -mpreferred-stack-boundary=2 -fno-align-functions \ - -march=pentium4 -msse2 -mfpmath=sse -msoft-float + -march=pentium4 -msse2 -mfpmath=sse -msoft-float -Qunused-arguments -ffreestanding -DBOOT_CORE DEFINES= CONFIG = hd @@ -68,7 +68,7 @@ BOOT2ADDR = 20200 MAXBOOTSIZE = 458240 -#CFLAGS += -DSAFE_MALLOC +CFLAGS += -DSAFE_MALLOC # CFLAGS += -DBOOT_HELPER_SUPPORT # +992 bytes @@ -80,7 +80,7 @@ @echo "\t[LD] boot.sys" @$(CC) -static -Wl,-preload -Wl,-segaddr,__INIT,$(BOOT2ADDR) \ -nostdlib -arch i386 -Wl,-segalign,20 \ - -o $(SYMROOT)/boot.sys $(filter %.o,$^) $(LIBS) #-e boot2 + -o $(SYMROOT)/boot.sys $(filter %.o,$^) $(LIBS) -e boot2 @echo "\t[MACHOCONV] boot" @$(SYMROOT)/machOconv $(SYMROOT)/boot.sys $(SYMROOT)/boot &> /dev/null Index: branches/cparm/i386/modules/NetbookInstaller/NBI.c =================================================================== --- branches/cparm/i386/modules/NetbookInstaller/NBI.c (revision 1971) +++ branches/cparm/i386/modules/NetbookInstaller/NBI.c (revision 1972) @@ -129,8 +129,9 @@ } // Force arch=i386 + -v - archCpuType = CPU_TYPE_I386; - gVerboseMode = true; + //archCpuType = CPU_TYPE_I386; + safe_set_env(envarchCpuType, CPU_TYPE_I386); + safe_set_env(envgVerboseMode, true); } } @@ -208,7 +209,7 @@ int step = 0; execute_hook("ramDiskLoadDrivers", &step, NULL, NULL, NULL, NULL, NULL); #ifdef NBP_SUPPORT - if ( gBootFileType == kNetworkDeviceType ) + if ( get_env(envgBootFileType) == kNetworkDeviceType ) { if (NetLoadDrivers(dirSpec) != 0) { @@ -218,7 +219,7 @@ } else #endif - if ( gBootFileType == kBlockDeviceType ) + if ( get_env(envgBootFileType) == kBlockDeviceType ) { verbose("Loading Recovery Extensions\n"); strcpy(dirSpecExtra, "/Extra/RecoveryExtensions/"); @@ -227,7 +228,7 @@ #ifdef BOOT_HELPER_SUPPORT // TODO: fix this, the order does matter, and it's not correct now. // Also try to load Extensions from boot helper partitions. - if (gBootVolume->flags & kBVFlagBooter) + if (((BVRef)(uint32_t)get_env(envgBootVolume))->flags & kBVFlagBooter) { strcpy(dirSpecExtra, "/com.apple.boot.P/System/Library/"); if (FileLoadDrivers(dirSpecExtra, 0) != 0) Index: branches/cparm/i386/modules/RamDiskLoader/RamDiskLoader.c =================================================================== --- branches/cparm/i386/modules/RamDiskLoader/RamDiskLoader.c (revision 1971) +++ branches/cparm/i386/modules/RamDiskLoader/RamDiskLoader.c (revision 1972) @@ -13,6 +13,7 @@ #include "ramdisk.h" #include "drivers.h" #include "disk.h" +#include "platform.h" void loadPrebootRAMDisk_hook(void* arg1, void* arg2, void* arg3, void* arg4, void* arg5, void* arg6); @@ -60,7 +61,7 @@ break; case 1: // First try a specfic OS version folder ie 10.5 - sprintf(dirSpecExtra, "rd(0,0)/Extra/%s/", (char*)gBootVolume->OSVersion); + sprintf(dirSpecExtra, "rd(0,0)/Extra/%s/", (char*)((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion); if (FileLoadDrivers(dirSpecExtra, 0) != 0) { // Next we'll try the base @@ -70,7 +71,7 @@ break; case 2: // First try a specfic OS version folder ie 10.5 - sprintf(dirSpecExtra, "bt(0,0)/Extra/%s/", (char*)gBootVolume->OSVersion); + sprintf(dirSpecExtra, "bt(0,0)/Extra/%s/", (char*)((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion); if (FileLoadDrivers(dirSpecExtra, 0) != 0) { // Next we'll try the base Index: branches/cparm/i386/modules/RamDiskLoader/ramdisk.c =================================================================== --- branches/cparm/i386/modules/RamDiskLoader/ramdisk.c (revision 1971) +++ branches/cparm/i386/modules/RamDiskLoader/ramdisk.c (revision 1972) @@ -393,6 +393,8 @@ { char extensionsSpec[1024]; int ramdiskUnit; + long ret, flags, cachetime; + for(ramdiskUnit = 0; ramdiskUnit < gRAMDiskMI->mi_mods_count; ++ramdiskUnit) { int partCount; // unused @@ -405,16 +407,18 @@ for(; ramdiskChain != NULL; ramdiskChain = ramdiskChain->next) { sprintf(extensionsSpec, "rd(%d,%d)/Extra/", ramdiskUnit, ramdiskChain->part_no); - struct dirstuff *extradir = opendir(extensionsSpec); - closedir(extradir); - if(extradir != NULL) + + ret = GetFileInfo(NULL, extensionsSpec, &flags, &cachetime); + + if (!ret) continue; + + if (((flags & kFileTypeMask) != kFileTypeDirectory)) continue; + + ret = FileLoadDrivers_p(extensionsSpec, 0 /* this is a kext root dir, not a kext with plugins */); + if(ret != 0) { - int ret = FileLoadDrivers_p(extensionsSpec, 0 /* this is a kext root dir, not a kext with plugins */); - if(ret != 0) - { - verbose("FileLoadDrivers failed on a ramdisk\n"); - return ret; - } + verbose("FileLoadDrivers failed on a ramdisk\n"); + return ret; } } } Index: branches/cparm/i386/modules/GUI/gui.c =================================================================== --- branches/cparm/i386/modules/GUI/gui.c (revision 1971) +++ branches/cparm/i386/modules/GUI/gui.c (revision 1972) @@ -319,6 +319,89 @@ { setCursorPosition( col, row, 0 ); } + +/* + * + */ + +bool getDimensionForKey( const char *key, unsigned int *value, config_file_t *config, unsigned int dimension_max, unsigned int object_size ) +{ + const char *val; + + int size = 0; + int sum = 0; + + bool negative = false; + bool percentage = false; + + config = resolveConfig(config); + + if (getValueForKey(key, &val, &size, config)) + { + if ( size ) + { + if (*val == '-') + { + negative = true; + val++; + size--; + } + + if (val[size-1] == '%') + { + percentage = true; + size--; + } + + // convert string to integer + for (sum = 0; size > 0; size--) + { + if (*val < '0' || *val > '9') + return false; + + sum = (sum * 10) + (*val++ - '0'); + } + + if (percentage) + sum = ( dimension_max * sum ) / 100; + + // calculate offset from opposite origin + if (negative) + sum = ( ( dimension_max - object_size ) - sum ); + + } else { + + // null value calculate center + sum = ( dimension_max - object_size ) / 2; + + } + + *value = (uint16_t) sum; + return true; + } + + // key not found + return false; +} + +static bool getColorForKey( const char *key, unsigned int *value, config_file_t *config ) +{ + const char *val; + int size; + + config = resolveConfig(config); + + if (getValueForKey(key, &val, &size, config)) + { + if (*val == '#') + { + val++; + *value = strtol(val, NULL, 16); + return true; + } + } + return false; +} //========================================================================== /* Flush keyboard buffer; returns TRUE if any of the flushed @@ -1035,9 +1118,7 @@ if (i) { - srand (time18()); - - uint8_t choosen = rand() % i; + uint8_t choosen = arc4random_uniform(i+1); themeList_t* entry = themeList; @@ -2653,8 +2734,8 @@ position_t p = pos( gui.screen.width / 2 + 1 , ( gui.devicelist.pos.y + 3 ) + ( ( gui.devicelist.height - gui.devicelist.iconspacing ) / 2 ) ); char dummy[80]; - getBootVolumeDescription( gBootVolume, dummy, sizeof(dummy) - 1, true ); - drawDeviceIcon( gBootVolume, gui.screen.pixmap, p, true ); + getBootVolumeDescription( ((BVRef)(uint32_t)get_env(envgBootVolume)), dummy, sizeof(dummy) - 1, true ); + drawDeviceIcon( ((BVRef)(uint32_t)get_env(envgBootVolume)), gui.screen.pixmap, p, true ); drawStrCenteredAt( (char *) msg, &font_small, gui.screen.pixmap, gui.countdown.pos ); // make this screen the new background Index: branches/cparm/i386/modules/GUI/GUI_module.c =================================================================== --- branches/cparm/i386/modules/GUI/GUI_module.c (revision 1971) +++ branches/cparm/i386/modules/GUI/GUI_module.c (revision 1972) @@ -96,7 +96,6 @@ int GUI_printf(const char * fmt, ...); int GUI_verbose(const char * fmt, ...); -int GUI_error(const char * fmt, ...); void GUI_stop(const char * fmt, ...); @@ -106,8 +105,6 @@ char * last_str; }; void sputc(int c, struct putc_info * pi); -extern char *msgbuf; -extern char *cursor; static void (*showTextBuffer)(char *, int ) = NULL; static char *(*getMemoryInfoString)(void) = NULL; @@ -179,7 +176,7 @@ **/ void GUI_ExecKernel_hook(void* arg1, void* arg2, void* arg3, void* arg4, void* arg5, void* arg6) { - if(!gVerboseMode) + if(!get_env(envgVerboseMode)) { // Note: shouldn't be needed, but just in case drawBootGraphics(); @@ -212,7 +209,7 @@ drawBackground(); updateVRAM(); - if(!gVerboseMode) + if(!get_env(envgVerboseMode)) { // Disable outputs, they will still show in the boot log. replace_system_function("_printf", &GUI_verbose); @@ -247,7 +244,6 @@ replace_system_function("_printf", &GUI_printf); replace_system_function("_verbose", &GUI_verbose); - replace_system_function("_error", &GUI_error); replace_system_function("_stop", &GUI_stop); replace_system_function("_showMessage", &GUI_showMessage); @@ -373,25 +369,25 @@ switch (res) { case BOOT_NORMAL: - gVerboseMode = false; + safe_set_env(envgVerboseMode, false); safe_set_env(envgBootMode, kBootModeNormal); break; case BOOT_VERBOSE: - gVerboseMode = true; + safe_set_env(envgVerboseMode, true); safe_set_env(envgBootMode, kBootModeNormal); GUI_addBootArg(kVerboseModeFlag); break; case BOOT_IGNORECACHE: - gVerboseMode = false; + safe_set_env(envgVerboseMode, false); safe_set_env(envgBootMode, kBootModeNormal); GUI_addBootArg(kIgnoreCachesFlag); break; case BOOT_SINGLEUSER: - gVerboseMode = true; + safe_set_env(envgVerboseMode, true); safe_set_env(envgBootMode, kBootModeNormal); GUI_addBootArg(kSingleUserModeFlag); break; @@ -703,8 +699,9 @@ int devcnt = (int)get_env(envgDeviceCount); // Initialize default menu selection entry. - gBootVolume = menuBVR = selectBootVolume(getBvChain()); - + /*gBootVolume =*/ menuBVR = selectBootVolume(getBvChain()); + safe_set_env(envgBootVolume, (uint32_t)menuBVR); + if (biosDevIsCDROM((int)get_env(envgBIOSDev))) { isCDROM = true; @@ -831,7 +828,7 @@ stop("Couldn't allocate memory for the device name\n"); //TODO: Find a better stategie return -1; } - getBootVolumeDescription(gBootVolume, name, 79, false); + getBootVolumeDescription(((BVRef)(uint32_t)get_env(envgBootVolume)), name, 79, false); prompt = malloc(256); if (!prompt) { free(name); @@ -892,7 +889,8 @@ // Look at partitions hosting OS X other than the CD-ROM for (bvr = getBvChain(); bvr; bvr=bvr->next) { if ((bvr->flags & kBVFlagSystemVolume) && bvr->biosdev != (int)get_env(envgBIOSDev)) { - gBootVolume = bvr; + //gBootVolume = bvr; + safe_set_env(envgBootVolume, (uint32_t)bvr); } } } @@ -1097,7 +1095,8 @@ GUI_showBootPrompt(nextRow, showPrompt); break; } - gBootVolume = menuBVR; + //gBootVolume = menuBVR; + safe_set_env(envgBootVolume, (uint32_t)menuBVR); setRootVolume(menuBVR); safe_set_env(envgBIOSDev,menuBVR->biosdev); break; @@ -1112,7 +1111,8 @@ // if the user enabled rescanning the optical drive. // Otherwise boot the default boot volume. if (get_env(envgEnableCDROMRescan)) { - gBootVolume = NULL; + //gBootVolume = NULL; + safe_set_env(envgBootVolume, (uint32_t)NULL); GUI_clearBootArgs(); } break; @@ -1124,7 +1124,9 @@ #else scanDisks(); #endif - gBootVolume = NULL; + //gBootVolume = NULL; + safe_set_env(envgBootVolume, (uint32_t)NULL); + GUI_clearBootArgs(); break; @@ -1202,34 +1204,13 @@ return 0; } - - -int GUI_error(const char * fmt, ...) -{ - va_list ap; - gErrors = true; - va_start(ap, fmt); - - if (getVideoMode() == VGA_TEXT_MODE) - { - prf(fmt, ap, putchar, 0); - } - else - { - vprf(fmt, ap); - } - - va_end(ap); - return(0); -} - int GUI_verbose(const char * fmt, ...) { va_list ap; va_start(ap, fmt); - if (gVerboseMode && (KernelStart == false)) + if (get_env(envgVerboseMode) && (KernelStart == false)) { if (getVideoMode() == VGA_TEXT_MODE) { @@ -1244,15 +1225,15 @@ /* Kabyl: BooterLog */ struct putc_info pi; - if (!msgbuf) + if (!getConsoleMsg()) return 0; - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((getConsoleCursor() - getConsoleMsg()) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) return 0; - pi.str = cursor; + pi.str = getConsoleCursor(); pi.last_str = 0; prf(fmt, ap, sputc, &pi); - cursor += strlen((char *)cursor); + setConsoleCursor(getConsoleCursor() + strlen(getConsoleCursor())); va_end(ap); @@ -1278,15 +1259,15 @@ /* Kabyl: BooterLog */ struct putc_info pi; - if (!msgbuf) + if (!getConsoleMsg()) return 0; - if (((cursor - msgbuf) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) + if (((getConsoleCursor() - getConsoleMsg()) > (BOOTER_LOG_SIZE - SAFE_LOG_SIZE))) return 0; - pi.str = cursor; + pi.str = getConsoleCursor(); pi.last_str = 0; prf(fmt, ap, sputc, &pi); - cursor += strlen((char *)cursor); + setConsoleCursor(getConsoleCursor() + strlen(getConsoleCursor())); va_end(ap); return 0; Index: branches/cparm/i386/modules/GUI/graphic_utils.c =================================================================== --- branches/cparm/i386/modules/GUI/graphic_utils.c (revision 1971) +++ branches/cparm/i386/modules/GUI/graphic_utils.c (revision 1972) @@ -9,6 +9,7 @@ #include "appleClut8.h" #include "vbe.h" #include "gui.h" +#include "platform.h" #define VIDEO(x) (((boot_args_common*)getBootArgs())->Video.v_ ## x) @@ -682,7 +683,7 @@ if ( mode == GRAPHICS_MODE ) { if ( (err=GUI_initGraphicsMode ()) == errSuccess ) { - if (gVerboseMode) { + if (get_env(envgVerboseMode)) { // Tell the kernel to use text mode on a linear frame buffer display setBootArgsVideoMode(FB_TEXT_MODE); Index: branches/cparm/i386/modules/SMBiosGetters/mysmbios.c =================================================================== --- branches/cparm/i386/modules/SMBiosGetters/mysmbios.c (revision 1971) +++ branches/cparm/i386/modules/SMBiosGetters/mysmbios.c (revision 1972) @@ -535,12 +535,11 @@ int rand_sn1 ; int rand_sn2 ; int rand_sn3 ; - struct ran_obj* random_serial_obj = random_init(0,35); - rand_sn1 = random(random_serial_obj); - rand_sn2 = random(random_serial_obj); - rand_sn3 = random(random_serial_obj); - random_free(random_serial_obj); + rand_sn1 = arc4random_unirange(0,35); + rand_sn2 = arc4random_unirange(0,35); + rand_sn3 = arc4random_unirange(0,35); + // Append all charaters to the string char tmp[2]; bzero(tmp,sizeof(tmp)); @@ -566,10 +565,8 @@ { // Get randomized characters int rand_week ; - struct ran_obj* random_week_obj = random_init(0,47)/* random_init(1,48) */; - rand_week = random(random_week_obj); - random_free(random_week_obj); - + rand_week = arc4random_unirange(0,47); + // Append all charaters to the string char tmp[3]; bzero(tmp,sizeof(tmp)); @@ -595,10 +592,9 @@ { // Get randomized characters int rand_year ; - struct ran_obj* random_year_obj = random_init(0,9); - rand_year = random(random_year_obj); - random_free(random_year_obj); + rand_year = arc4random_unirange(0,9); + // Append all charaters to the string char tmp[2]; bzero(tmp,sizeof(tmp)); @@ -622,10 +618,9 @@ // Get randomized characters int rand_country ; - struct ran_obj* random_country_obj = random_init(0,(sizeof(sm_country_list) / sizeof(sm_country_list[0]))-1); - rand_country = random(random_country_obj); - random_free(random_country_obj); + rand_country = arc4random_unirange(0,(sizeof(sm_country_list) / sizeof(sm_country_list[0]))-1); + strlcpy (str, sm_country_list[rand_country].code,strlen(sm_country_list[rand_country].code)+1); DBG ("fake_country: %s (%s)\n",str,sm_country_list[rand_country].info); Index: branches/cparm/i386/modules/HibernateEnabler/resume.c =================================================================== --- branches/cparm/i386/modules/HibernateEnabler/resume.c (revision 1971) +++ branches/cparm/i386/modules/HibernateEnabler/resume.c (revision 1972) @@ -297,7 +297,7 @@ IOHibernateImageHeader * header = &_header; long buffer; - if(gBootVolume->OSVersion[3] >= '7') // TODO: unlocked, but please check the compatibility with the 10.8 + if(((BVRef)(uint32_t)get_env(envgBootVolume))->OSVersion[3] >= '7') // TODO: unlocked, but please check the compatibility with the 10.8 { HibernateBoot107(image_filename); return; Index: branches/cparm/i386/modules/HibernateEnabler/graphic_utils.c =================================================================== --- branches/cparm/i386/modules/HibernateEnabler/graphic_utils.c (revision 1971) +++ branches/cparm/i386/modules/HibernateEnabler/graphic_utils.c (revision 1972) @@ -10,8 +10,8 @@ #include "bmdecompress.h" #include "vbe.h" #include "appleClut8.h" +#include "platform.h" - #ifndef offsetof #define offsetof(st, m) \ ((size_t) ( (char *)&((st *)(0))->m - (char *)0 )) @@ -482,7 +482,7 @@ if ( mode == GRAPHICS_MODE ) { if ( (err=initGraphicsMode ()) == errSuccess ) { - if (gVerboseMode) { + if (get_env(envgVerboseMode)) { // Tell the kernel to use text mode on a linear frame buffer display setBootArgsVideoMode(FB_TEXT_MODE); } else { Index: branches/cparm/i386/modules/Keymapper/Keylayout.c =================================================================== --- branches/cparm/i386/modules/Keymapper/Keylayout.c (revision 1971) +++ branches/cparm/i386/modules/Keymapper/Keylayout.c (revision 1972) @@ -25,6 +25,22 @@ #define kKeyboardLayout "KeyboardLayout" +//========================================================================== +// lseek() - Reposition the byte offset of the file descriptor from the +// beginning of the file. Returns the relocated offset. + +int key_b_lseek(int fdesc, int offset, int ptr) +{ + struct iob * io; + + if ((io = iob_from_fdesc(fdesc)) == NULL) + return (-1); + + io->i_offset = offset; + + return offset; +} + struct keyboard_layout *current_layout = NULL; int getchar_replacement(void); @@ -99,7 +115,7 @@ if (!current_layout) goto fail; - b_lseek(fd, KEYBOARD_LAYOUTS_MAP_OFFSET, 0); + key_b_lseek(fd, KEYBOARD_LAYOUTS_MAP_OFFSET, 0); if (read(fd, (char*) current_layout, sizeof(*current_layout)) != sizeof(*current_layout)) { printf("Wrong keyboard layout file %s size\n", filename); Index: branches/cparm/i386/modules/SMBiosPatcher/smbios_patcher.c =================================================================== --- branches/cparm/i386/modules/SMBiosPatcher/smbios_patcher.c (revision 1971) +++ branches/cparm/i386/modules/SMBiosPatcher/smbios_patcher.c (revision 1972) @@ -305,12 +305,11 @@ int rand_sn1 ; int rand_sn2 ; int rand_sn3 ; - struct ran_obj* random_serial_obj = random_init(0,35); - rand_sn1 = random(random_serial_obj); - rand_sn2 = random(random_serial_obj); - rand_sn3 = random(random_serial_obj); - random_free(random_serial_obj); + rand_sn1 = arc4random_unirange(0,35); + rand_sn2 = arc4random_unirange(0,35); + rand_sn3 = arc4random_unirange(0,35); + // Append all charaters to the string char tmp[2]; bzero(tmp,sizeof(tmp)); @@ -336,10 +335,8 @@ { // Get randomized characters int rand_week ; - struct ran_obj* random_week_obj = random_init(0,47)/* random_init(1,48) */; - rand_week = random(random_week_obj); - random_free(random_week_obj); - + rand_week = arc4random_unirange(0,47); + // Append all charaters to the string char tmp[3]; bzero(tmp,sizeof(tmp)); @@ -365,10 +362,9 @@ { // Get randomized characters int rand_year ; - struct ran_obj* random_year_obj = random_init(0,9); - rand_year = random(random_year_obj); - random_free(random_year_obj); + rand_year = arc4random_unirange(0,9); + // Append all charaters to the string char tmp[2]; bzero(tmp,sizeof(tmp)); @@ -392,10 +388,9 @@ // Get randomized characters int rand_country ; - struct ran_obj* random_country_obj = random_init(0,(sizeof(sm_country_list) / sizeof(sm_country_list[0]))-1); - rand_country = random(random_country_obj); - random_free(random_country_obj); + rand_country = arc4random_unirange(0,(sizeof(sm_country_list) / sizeof(sm_country_list[0]))-1); + strlcpy (str, sm_country_list[rand_country].code,strlen(sm_country_list[rand_country].code)+1); DBG ("fake_country: %s (%s)\n",str,sm_country_list[rand_country].info); Index: branches/cparm/i386/modules/Memory/Makefile =================================================================== --- branches/cparm/i386/modules/Memory/Makefile (revision 1971) +++ branches/cparm/i386/modules/Memory/Makefile (revision 1972) @@ -10,7 +10,7 @@ BUNDLE_LIBS = BUNDLE_INFO = BUNDLE_ID = com.boot.SMBIOS.SMBIOSPLATFORM.MEMORY.memory -BUNDLE_COPYRIGHT = +BUNDLE_COPYRIGHT = GPL V2.0 BUNDLE_LICENCE = BUNDLE_VERSION = 1.0 BUNDLE_ICON = @@ -98,6 +98,8 @@ @mkdir $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/PlugIns @mv $(SYMROOT)/$(BUNDLE_EXEC) $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/MacOS @#mv $(SYMROOT)/$(SYMBOLS_BUNDLE_LIBS) $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/PlugIns + @cp GPL_V2_LICENSE $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/Resources + @cp MEMTEST86_LICENSE $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/Resources @defaults write $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/Info "CFBundleGetInfoString" '$(BUNDLE_INFO)' @defaults write $(SYMROOT)/$(BUNDLE_NAME).bundle/Contents/Info "NSHumanReadableCopyright" '$(BUNDLE_COPYRIGHT)' Index: branches/cparm/i386/modules/Memory/README =================================================================== --- branches/cparm/i386/modules/Memory/README (revision 1971) +++ branches/cparm/i386/modules/Memory/README (revision 1972) @@ -1,6 +1,6 @@ -Memory.dylib is a module for Chameleon (the Darwin/XNU boot loader based on Apple's boot-132). +Memory is a module for Chameleon (the Darwin/XNU boot loader based on Apple's boot-132). -Memory.dylib can be freely distributed under the term of the GPL V2 license. +Memory can be freely distributed under the term of the GPL V2 license. see GPL_V2_LICENSE and MEMTEST86_LICENSE for more informations. Index: branches/cparm/i386/modules/ACPICodec/acpi_codec.c =================================================================== --- branches/cparm/i386/modules/ACPICodec/acpi_codec.c (revision 1971) +++ branches/cparm/i386/modules/ACPICodec/acpi_codec.c (revision 1972) @@ -94,7 +94,7 @@ static ACPI_TABLE_RSDT * gen_alloc_rsdt_from_xsdt(ACPI_TABLE_XSDT *xsdt); static ACPI_TABLE_XSDT * gen_alloc_xsdt_from_rsdt(ACPI_TABLE_RSDT *rsdt); static void MakeAcpiSgn(void); -static void *loadACPITable(U32 *new_table_list, char *dirspec, char *filename ); +static void *loadACPITable(U32 *new_table_list, char *dirspec, const char *filename ); static int generate_cpu_map_from_acpi(ACPI_TABLE_DSDT * DsdtPointer); static ACPI_GENERIC_ADDRESS FillGASStruct(U32 Address, U8 Length); static U32 process_xsdt (ACPI_TABLE_RSDP *rsdp_mod , U32 *new_table_list); @@ -557,7 +557,7 @@ } -static void *loadACPITable(U32 *new_table_list, char *dirspec, char *filename ) +static void *loadACPITable(U32 *new_table_list, char *dirspec, const char *filename ) { int fd = -1; char acpi_file[512]; @@ -567,7 +567,7 @@ sprintf(acpi_file, "%s%s",dirspec, filename); - HFSLoadVerbose = 0; + safe_set_env(envHFSLoadVerbose, 0); fd=open(acpi_file); if (fd<0) @@ -4743,10 +4743,10 @@ } { - char* name; - long flags; - long time; - long ret = -1; + long ret, length, flags, time; + long long index = 0; + const char * name; + U8 i = 0; char dirspec[512]; bool acpidir_found = false; @@ -4782,70 +4782,76 @@ if (acpidir_found == true) { - struct dirstuff* AcpiDir = opendir(dirspec); - if (AcpiDir != NULL) + if (checkOem == true) { - if (checkOem == true) + MakeAcpiSgn(); + } + + while (1) { + ret = GetDirEntry(dirspec, &index, &name, &flags, &time); + if (ret == -1) break; +#if DEBUG_ACPI + printf("testing %s\n", name); +#endif + // Make sure this is a directory. + if ((flags & kFileTypeMask) == kFileTypeDirectory) continue; + + // Make sure this is a kext. + length = strlen(name); + if (strcmp(name + length - 4, ".aml")) { - MakeAcpiSgn(); +#if DEBUG_ACPI + printf("Ignoring %s\n", name); +#endif + continue; } - while(readdir(AcpiDir, (const char**)&name, &flags, &time) >= 0) - { - if((strstr(name, ".aml")) && ((strlen(dirspec)+strlen(name)) < 512)) - { - // Some simple verifications to save time in case of those tables simply named as follow: - if ((strncmp(name, "RSDT", 4) == 0) || (strncmp(name, "rsdt", 4) == 0) || - (strncmp(name, "XSDT", 4) == 0) || (strncmp(name, "xsdt", 4) == 0) || - (strncmp(name, "RSDP", 4) == 0) || (strncmp(name, "rsdp", 4) == 0)) - { - continue; - } - - if ((strncmp(name, "FACS", 4) == 0) || (strncmp(name, "facs", 4) == 0)) // FACS is not supported - { - continue; - } - - DBG("* Attempting to load acpi table: %s\n", name); - if ( (new_table_list[i]=(U32)loadACPITable(new_table_list,dirspec,name))) - { - if (i < MAX_ACPI_TABLE) - { - i++; - } - else - { - DBG("Max nb of allowed aml files reached, exiting ."); - break; - } - } - - } + // Some simple verifications to save time in case of those tables simply named as follow: + if ((strncmp(name, "RSDT", 4) == 0) || (strncmp(name, "rsdt", 4) == 0) || + (strncmp(name, "XSDT", 4) == 0) || (strncmp(name, "xsdt", 4) == 0) || + (strncmp(name, "RSDP", 4) == 0) || (strncmp(name, "rsdp", 4) == 0)) + { #if DEBUG_ACPI - else - { - - printf("Ignoring %s\n", name); - } + printf("Ignoring %s\n", name); #endif - - } + continue; + } - if (i) + if ((strncmp(name, "FACS", 4) == 0) || (strncmp(name, "facs", 4) == 0)) // FACS is not supported + { +#if DEBUG_ACPI + printf("Ignoring %s\n", name); +#endif + continue; + } + + DBG("* Attempting to load acpi table: %s\n", name); + if ( (new_table_list[i]=(U32)loadACPITable(new_table_list,dirspec,name))) { - //sanitize the new tables list - sanitize_new_table_list(new_table_list); - - //move to kernel memory - move_table_list_to_kmem(new_table_list); - - DBG("New ACPI tables Loaded in memory\n"); + if (i < MAX_ACPI_TABLE) + { + i++; + } + else + { + DBG("Max nb of allowed aml files reached, exiting ."); + break; + } } + } + + if (i) + { + //sanitize the new tables list + sanitize_new_table_list(new_table_list); - closedir(AcpiDir); - - } + //move to kernel memory + move_table_list_to_kmem(new_table_list); + + DBG("New ACPI tables Loaded in memory\n"); + } + + } } Index: branches/cparm/i386/modules/Makefile =================================================================== --- branches/cparm/i386/modules/Makefile (revision 1971) +++ branches/cparm/i386/modules/Makefile (revision 1972) @@ -26,7 +26,7 @@ VPATH = $(OBJROOT):$(SYMROOT) # The order of building is important. -SUBDIRS = HelloWorld KernelPatcher USBFix Networking HPET NetbookInstaller CPUfreq Keymapper YellowIconFixer ACPICodec ACPIPatcher GraphicsEnabler Memory RamDiskLoader SMBiosPatcher SMBiosGetters GUI HibernateEnabler +SUBDIRS = lua HelloWorld KernelPatcher USBFix Networking HPET NetbookInstaller CPUfreq Keymapper YellowIconFixer ACPICodec ACPIPatcher GraphicsEnabler Memory RamDiskLoader SMBiosPatcher SMBiosGetters GUI HibernateEnabler all embedtheme tags debug install installhdrs: @rm -rf $(OBJROOT) @mkdir $(OBJROOT) Index: branches/cparm/i386/libsa/rand.c =================================================================== --- branches/cparm/i386/libsa/rand.c (revision 1971) +++ branches/cparm/i386/libsa/rand.c (revision 1972) @@ -1,20 +0,0 @@ -/* - * - * rand & srand implementation for chameleon by Cadet-petit Armel - */ - -#include "libsa.h" - -static long holdrand = 1L; -#define RAND_MAX 0x7fffffff - -void srand (unsigned int seed) -{ - holdrand = (long)seed; -} - -int rand (void) -{ - holdrand = holdrand * 214013L + 2531011L; - return ((holdrand >> 16) & RAND_MAX); -} \ No newline at end of file Index: branches/cparm/i386/libsa/libsa.h =================================================================== --- branches/cparm/i386/libsa/libsa.h (revision 1971) +++ branches/cparm/i386/libsa/libsa.h (revision 1972) @@ -102,8 +102,6 @@ extern unsigned long adler32( unsigned char * buffer, long length ); extern void * bsearch(register const void *key,const void *base0,size_t nmemb,register size_t size,register int (*compar)(const void *, const void *)); -extern int rand (void); -extern void srand (unsigned int seed); /* * strtol.c */ @@ -130,11 +128,12 @@ extern void free(void * start); extern void * realloc(void * ptr, size_t size); -//#if SAFE_MALLOC -//extern size_t zalloced_size; -//#endif - +#ifdef SAFE_MALLOC +extern size_t zalloced_size; +extern void malloc_init(char * start, int size, int nodes, void (*malloc_err_fn)(char *, size_t, const char *, int)); +#else extern void malloc_init(char * start, int size, int nodes, void (*malloc_error)(char *, size_t)); +#endif extern void * malloc(size_t size); #endif /* !__BOOT_LIBSA_H */ Index: branches/cparm/i386/libsa/string.c =================================================================== --- branches/cparm/i386/libsa/string.c (revision 1971) +++ branches/cparm/i386/libsa/string.c (revision 1972) @@ -206,7 +206,7 @@ bcopy(src, dst, ulen); return dst; } - +#if UNUSED int ptol(const char *str) { @@ -219,7 +219,7 @@ else c = 0; return c; } - +#endif /* * atoi: * @@ -239,7 +239,7 @@ return( number ); } - +#if UNUSED /* * convert an integer to an ASCII string. * inputs: @@ -276,7 +276,7 @@ return str; } - +#endif /* * Appends src to string dst of size siz (unlike strncat, siz is the * full size of dst, not space left). At most siz-1 characters @@ -351,7 +351,7 @@ { return (size_t)_mach_strlen(str); } - +#if UNUSED /* * Does the same thing as strlen, except only looks up * to max chars inside the buffer. @@ -371,7 +371,7 @@ return p - s; } - +#endif /* * Deprecation Warning: * strcat() is being deprecated. Please use strlcat() instead. @@ -406,6 +406,7 @@ * NULL If MALLOC() fails. * */ + static char * STRDUP(const char *string) { @@ -564,20 +565,6 @@ return result; } -static long holdrand = 1L; -#define RAND_MAX 0x7fffffff - -void srand (unsigned int seed) -{ - holdrand = (long)seed; -} - -int rand (void) -{ - holdrand = holdrand * 214013L + 2531011L; - return ((holdrand >> 16) & RAND_MAX); -} - /*- * For memcmp, bsearch. * Copyright (c) 1990, 1993 @@ -668,4 +655,4 @@ } /* else move left */ } return (NULL); -} \ No newline at end of file +} Index: branches/cparm/i386/libsa/zalloc.c =================================================================== --- branches/cparm/i386/libsa/zalloc.c (revision 1971) +++ branches/cparm/i386/libsa/zalloc.c (revision 1972) @@ -399,11 +399,8 @@ { if (!start || !(newsize>0)) return NULL; -#ifdef SAFE_MALLOC - void * newstart = safe_malloc(newsize, __FILE__, __LINE__); -#else void * newstart = malloc(newsize); -#endif + if (newstart) { bcopy(start, newstart, newsize); } Index: branches/cparm/i386/libsa/strtol.c =================================================================== --- branches/cparm/i386/libsa/strtol.c (revision 1971) +++ branches/cparm/i386/libsa/strtol.c (revision 1972) @@ -254,7 +254,7 @@ return (acc); } - +#if UNUSED /* * Convert a string to an unsigned quad integer. * @@ -334,3 +334,4 @@ return (acc); } +#endif Index: branches/cparm/i386/libsa/Makefile =================================================================== --- branches/cparm/i386/libsa/Makefile (revision 1971) +++ branches/cparm/i386/libsa/Makefile (revision 1972) @@ -10,7 +10,7 @@ OPTIM = -Os -Oz CFLAGS = $(RC_CFLAGS) $(OPTIM) $(MORECPP) -arch i386 -g -Wmost -Werror -fno-stack-protector \ -fno-builtin -static $(OMIT_FRAME_POINTER_CFLAG) \ - -march=pentium4 -msse2 -msoft-float -ffreestanding -mpreferred-stack-boundary=2 -fno-align-functions -mfpmath=sse + -march=pentium4 -msse2 -msoft-float -Qunused-arguments -ffreestanding -DBOOT_CORE -mpreferred-stack-boundary=2 -fno-align-functions -mfpmath=sse INC = -I. -I$(SYMROOT) -I$(UTILDIR) -I$(LIBSAIODIR) ifneq "" "$(wildcard /bin/mkdirs)" @@ -42,7 +42,7 @@ LIBS = libsa.a DIRS_NEEDED = $(OBJROOT) $(SYMROOT) -#CFLAGS += -DSAFE_MALLOC +CFLAGS += -DSAFE_MALLOC all embedtheme: $(DIRS_NEEDED) $(LIBS) Index: branches/cparm/i386/util/rand-fbsd.c =================================================================== --- branches/cparm/i386/util/rand-fbsd.c (revision 0) +++ branches/cparm/i386/util/rand-fbsd.c (revision 1972) @@ -0,0 +1,131 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * Posix rand_r function added May 1999 by Wes Peters . + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rand.c 8.1 (Berkeley) 6/14/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/stdlib/rand.c,v 1.17 2007/12/11 20:39:32 ache Exp $"); + +#ifdef TEST +#include +#else +#include "libsaio.h" +#endif /* TEST */ + +static int +do_rand(unsigned long *ctx) +{ +#ifdef USE_WEAK_SEEDING + /* + * Historic implementation compatibility. + * The random sequences do not vary much with the seed, + * even with overflowing. + */ + return ((*ctx = *ctx * 1103515245 + 12345) % ((u_long)RAND_MAX + 1)); +#else /* !USE_WEAK_SEEDING */ + /* + * Compute x = (7^5 * x) mod (2^31 - 1) + * without overflowing 31 bits: + * (2^31 - 1) = 127773 * (7^5) + 2836 + * From "Random number generators: good ones are hard to find", + * Park and Miller, Communications of the ACM, vol. 31, no. 10, + * October 1988, p. 1195. + */ + long hi, lo, x; + + /* Can't be initialized with 0, so use another value. */ + if (*ctx == 0) + *ctx = 123459876; + hi = *ctx / 127773; + lo = *ctx % 127773; + x = 16807 * lo - 2836 * hi; + if (x < 0) + x += 0x7fffffff; + return ((*ctx = x) % ((u_long)RAND_MAX + 1)); +#endif /* !USE_WEAK_SEEDING */ +} + + +int +rand_r(unsigned int *ctx) +{ + u_long val = (u_long) *ctx; + int r = do_rand(&val); + + *ctx = (unsigned int) val; + return (r); +} + + +static u_long next = 1; + +int +rand() +{ + return (do_rand(&next)); +} + +void +srand(seed) +u_int seed; +{ + next = seed; +} + + +#ifdef TEST + +main() +{ + int i; + unsigned myseed; + + printf("seeding rand with 0x19610910: \n"); + srand(0x19610910); + + printf("generating three pseudo-random numbers:\n"); + for (i = 0; i < 3; i++) + { + printf("next random number = %d\n", rand()); + } + + printf("generating the same sequence with rand_r:\n"); + myseed = 0x19610910; + for (i = 0; i < 3; i++) + { + printf("next random number = %d\n", rand_r(&myseed)); + } + + return 0; +} + +#endif /* TEST */ Index: branches/cparm/i386/util/utstring.h =================================================================== --- branches/cparm/i386/util/utstring.h (revision 0) +++ branches/cparm/i386/util/utstring.h (revision 1972) @@ -0,0 +1,159 @@ +/* +Copyright (c) 2008-2012, Troy D. Hanson http://uthash.sourceforge.net +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* a dynamic string implementation using macros + * see http://uthash.sourceforge.net/utstring + */ +#ifndef UTSTRING_H +#define UTSTRING_H + +#define UTSTRING_VERSION 1.9.6 + +#ifdef __GNUC__ +#define _UNUSED_ __attribute__ ((__unused__)) +#else +#define _UNUSED_ +#endif + +#include "libsaio.h" +#ifndef utstring_oom +#define utstring_oom() longjmp(THIS_BUF_ERROR,-1) +#endif +#ifndef __utstring_malloc +#define __utstring_malloc(sz) pool_alloc(THIS_POOL,sz) /* malloc fcn */ +#endif +#ifndef __utstring_free +#define __utstring_free(ptr) pool_free(THIS_POOL,ptr) /* free fcn */ +#endif +#ifndef __utarray_realloc +#define __utarray_realloc(ptr,sz) pool_realloc(THIS_POOL,nmemb,sz) /* realloc fcn */ +#endif +#ifndef __utarray_calloc +#define __utarray_calloc(n,sz) pool_calloc(THIS_POOL,n,sz) /* calloc fcn */ +#endif +typedef struct { + char *d; + size_t n; /* allocd size */ + size_t i; /* index of first unused byte */ +} UT_string; + +#define utstring_reserve(s,amt) \ +do { \ + if (((s)->n - (s)->i) < (size_t)(amt)) { \ + (s)->d = (char*)__utarray_realloc((s)->d, (s)->n + amt); \ + if ((s)->d == NULL) utstring_oom(); \ + (s)->n += amt; \ + } \ +} while(0) + +#define utstring_init(s) \ +do { \ + (s)->n = 0; (s)->i = 0; (s)->d = NULL; \ + utstring_reserve(s,100); \ + (s)->d[0] = '\0'; \ +} while(0) + +#define utstring_done(s) \ +do { \ + if ((s)->d != NULL) __utstring_free((s)->d); \ + (s)->n = 0; \ +} while(0) + +#define utstring_free(s) \ +do { \ + utstring_done(s); \ + __utstring_free(s); \ +} while(0) + +#define utstring_new(s) \ +do { \ + s = (UT_string*)__utarray_calloc(sizeof(UT_string),1); \ + if (!s) utstring_oom(); \ + utstring_init(s); \ +} while(0) + +#define utstring_renew(s) \ +do { \ + if (s) { \ + utstring_clear(s); \ + } else { \ + utstring_new(s); \ + } \ +} while(0) + +#define utstring_clear(s) \ +do { \ + (s)->i = 0; \ + (s)->d[0] = '\0'; \ +} while(0) + +#define utstring_bincpy(s,b,l) \ +do { \ + utstring_reserve((s),(l)+1); \ + if (l) memcpy(&(s)->d[(s)->i], b, l); \ + (s)->i += l; \ + (s)->d[(s)->i]='\0'; \ +} while(0) + +#define utstring_concat(dst,src) \ +do { \ + utstring_reserve((dst),((src)->i)+1); \ + if ((src)->i) memcpy(&(dst)->d[(dst)->i], (src)->d, (src)->i); \ + (dst)->i += (src)->i; \ + (dst)->d[(dst)->i]='\0'; \ +} while(0) + +#define utstring_len(s) ((unsigned)((s)->i)) + +#define utstring_body(s) ((s)->d) + +_UNUSED_ static void utstring_printf_va(UT_string *s, const char *fmt, va_list ap) { + int n; + va_list cp; + while (1) { +#ifdef _WIN32 + cp = ap; +#else + va_copy(cp, ap); +#endif + n = vsnprintf (&s->d[s->i], s->n-s->i, fmt, cp); // vsnprintf not implemented yet in chameleon + va_end(cp); + + if ((n > -1) && (n < (int)(s->n-s->i))) { + s->i += n; + return; + } + + /* Else try again with more space. */ + if (n > -1) utstring_reserve(s,n+1); /* exact */ + else utstring_reserve(s,(s->n)*2); /* 2x */ + } +} +_UNUSED_ static void utstring_printf(UT_string *s, const char *fmt, ...) { + va_list ap; + va_start(ap,fmt); + utstring_printf_va(s,fmt,ap); + va_end(ap); +} + +#endif /* UTSTRING_H */ Index: branches/cparm/i386/util/smbios-fbsd.c =================================================================== --- branches/cparm/i386/util/smbios-fbsd.c (revision 0) +++ branches/cparm/i386/util/smbios-fbsd.c (revision 1972) @@ -0,0 +1,142 @@ +/*- + * Copyright (c) 2005-2009 Jung-uk Kim + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* + * Detect SMBIOS and export information about the SMBIOS into the + * environment. + * + * System Management BIOS Reference Specification, v2.6 Final + * http://www.dmtf.org/standards/published_documents/DSP0134_2.6.0.pdf + */ + +/* + * 2.1.1 SMBIOS Structure Table Entry Point + * + * "On non-EFI systems, the SMBIOS Entry Point structure, described below, can + * be located by application software by searching for the anchor-string on + * paragraph (16-byte) boundaries within the physical memory address range + * 000F0000h to 000FFFFFh. This entry point encapsulates an intermediate anchor + * string that is used by some existing DMI browsers." + */ + +#include "libsaio.h" + +#define SMBIOS_START 0xf0000 +#define SMBIOS_LENGTH 0x10000 +#define SMBIOS_STEP 0x10 +#define SMBIOS_SIG "_SM_" +#define SMBIOS_DMI_SIG "_DMI_" + +#define SMBIOS_GET8(base, off) (*(uint8_t *)((base) + (off))) +#define SMBIOS_GET16(base, off) (*(uint16_t *)((base) + (off))) +#define SMBIOS_GET32(base, off) (*(uint32_t *)((base) + (off))) + +#define SMBIOS_GETLEN(base) SMBIOS_GET8(base, 0x01) +#define SMBIOS_GETSTR(base) ((base) + SMBIOS_GETLEN(base)) + +static uint32_t smbios_enabled_memory = 0; +static uint32_t smbios_old_enabled_memory = 0; +static uint8_t smbios_enabled_sockets = 0; +static uint8_t smbios_populated_sockets = 0; +typedef char* caddr_t; + +static uint8_t +smbios_checksum(const caddr_t addr, const uint8_t len) +{ + uint8_t sum; + int i; + + for (sum = 0, i = 0; i < len; i++) + sum += SMBIOS_GET8(addr, i); + return (sum); +} + +static caddr_t +smbios_sigsearch(const caddr_t addr, const uint32_t len) +{ + caddr_t cp; + + /* Search on 16-byte boundaries. */ + for (cp = addr; cp < addr + len; cp += SMBIOS_STEP) + if (strncmp(cp, SMBIOS_SIG, 4) == 0 && + smbios_checksum(cp, SMBIOS_GET8(cp, 0x05)) == 0 && + strncmp(cp + 0x10, SMBIOS_DMI_SIG, 5) == 0 && + smbios_checksum(cp + 0x10, 0x0f) == 0) + return (cp); + return (NULL); +} + +void +smbios_detect(void) +{ + char buf[16]; + caddr_t addr, dmi, smbios; + size_t count, length; + uint32_t paddr; + int i, major, minor, ver; + + /* Search signatures and validate checksums. */ + smbios = smbios_sigsearch(PTOV(SMBIOS_START), SMBIOS_LENGTH); + if (smbios == NULL) + return; + + length = SMBIOS_GET16(smbios, 0x16); /* Structure Table Length */ + paddr = SMBIOS_GET32(smbios, 0x18); /* Structure Table Address */ + count = SMBIOS_GET16(smbios, 0x1c); /* No of SMBIOS Structures */ + ver = SMBIOS_GET8(smbios, 0x1e); /* SMBIOS BCD Revision */ + + if (ver != 0) { + major = ver >> 4; + minor = ver & 0x0f; + if (major > 9 || minor > 9) + ver = 0; + } + if (ver == 0) { + major = SMBIOS_GET8(smbios, 0x06); /* SMBIOS Major Version */ + minor = SMBIOS_GET8(smbios, 0x07); /* SMBIOS Minor Version */ + } + ver = (major << 8) | minor; + + addr = PTOV(paddr); + for (dmi = addr, i = 0; dmi < addr + length && i < count; i++) + dmi = smbios_parse_table(dmi, ver); + + sprintf(buf, "%d.%d", major, minor); + setenv("smbios.version", buf, 1); + if (smbios_enabled_memory > 0 || smbios_old_enabled_memory > 0) { + sprintf(buf, "%u", smbios_enabled_memory > 0 ? + 336 smbios_enabled_memory : smbios_old_enabled_memory); + setenv("smbios.memory.enabled", buf, 1); + } + if (smbios_enabled_sockets > 0) { + sprintf(buf, "%u", smbios_enabled_sockets); + setenv("smbios.socket.enabled", buf, 1); + } + if (smbios_populated_sockets > 0) { + sprintf(buf, "%u", smbios_populated_sockets); + setenv("smbios.socket.populated", buf, 1); + } +} Index: branches/cparm/i386/util/utlist.h =================================================================== --- branches/cparm/i386/util/utlist.h (revision 0) +++ branches/cparm/i386/util/utlist.h (revision 1972) @@ -0,0 +1,522 @@ +/* +Copyright (c) 2007-2012, Troy D. Hanson http://uthash.sourceforge.net +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTLIST_H +#define UTLIST_H + +#define UTLIST_VERSION 1.9.6 + +#include + +/* + * This file contains macros to manipulate singly and doubly-linked lists. + * + * 1. LL_ macros: singly-linked lists. + * 2. DL_ macros: doubly-linked lists. + * 3. CDL_ macros: circular doubly-linked lists. + * + * To use singly-linked lists, your structure must have a "next" pointer. + * To use doubly-linked lists, your structure must "prev" and "next" pointers. + * Either way, the pointer to the head of the list must be initialized to NULL. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *prev, *next; + * } + * + * struct item *list = NULL: + * + * int main() { + * struct item *item; + * ... allocate and populate item ... + * DL_APPEND(list, item); + * } + * -------------------------------------------------- + * + * For doubly-linked lists, the append and delete macros are O(1) + * For singly-linked lists, append and delete are O(n) but prepend is O(1) + * The sort macro is O(n log(n)) for all types of single/double/circular lists. + */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ code), this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#ifdef _MSC_VER /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define LDECLTYPE(x) decltype(x) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define LDECLTYPE(x) char* +#endif +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#endif + +/* for VS2008 we use some workarounds to get around the lack of decltype, + * namely, we always reassign our tmp variable to the list head if we need + * to dereference its prev/next pointers, and save/restore the real head.*/ +#ifdef NO_DECLTYPE +#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } +#define _NEXT(elt,list) ((char*)((list)->next)) +#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } +#define _PREV(elt,list) ((char*)((list)->prev)) +#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } +#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } +#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } +#else +#define _SV(elt,list) +#define _NEXT(elt,list) ((elt)->next) +#define _NEXTASGN(elt,list,to) ((elt)->next)=(to) +#define _PREV(elt,list) ((elt)->prev) +#define _PREVASGN(elt,list,to) ((elt)->prev)=(to) +#define _RS(list) +#define _CASTASGN(a,b) (a)=(b) +#endif + +/****************************************************************************** + * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * + * Unwieldy variable names used here to avoid shadowing passed-in variables. * + *****************************************************************************/ +#define LL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +#define DL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev, _ls_tail); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +#define CDL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + LDECLTYPE(list) _tmp2; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); \ + if (_NEXT(_ls_q,list) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = _NEXT(_ls_q,list); \ + } \ + _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev,_ls_tail); \ + _CASTASGN(_tmp2,list); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +/****************************************************************************** + * singly linked list macros (non-circular) * + *****************************************************************************/ +#define LL_PREPEND(head,add) \ +do { \ + (add)->next = head; \ + head = add; \ +} while (0) + +#define LL_CONCAT(head1,head2) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head1) { \ + _tmp = head1; \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(head2); \ + } else { \ + (head1)=(head2); \ + } \ +} while (0) + +#define LL_APPEND(head,add) \ +do { \ + LDECLTYPE(head) _tmp; \ + (add)->next=NULL; \ + if (head) { \ + _tmp = head; \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(add); \ + } else { \ + (head)=(add); \ + } \ +} while (0) + +#define LL_DELETE(head,del) \ +do { \ + LDECLTYPE(head) _tmp; \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + _tmp = head; \ + while (_tmp->next && (_tmp->next != (del))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = ((del)->next); \ + } \ + } \ +} while (0) + +/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */ +#define LL_APPEND_VS2008(head,add) \ +do { \ + if (head) { \ + (add)->next = head; /* use add->next as a temp variable */ \ + while ((add)->next->next) { (add)->next = (add)->next->next; } \ + (add)->next->next=(add); \ + } else { \ + (head)=(add); \ + } \ + (add)->next=NULL; \ +} while (0) + +#define LL_DELETE_VS2008(head,del) \ +do { \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + char *_tmp = (char*)(head); \ + while ((head)->next && ((head)->next != (del))) { \ + head = (head)->next; \ + } \ + if ((head)->next) { \ + (head)->next = ((del)->next); \ + } \ + { \ + char **_head_alias = (char**)&(head); \ + *_head_alias = _tmp; \ + } \ + } \ +} while (0) +#ifdef NO_DECLTYPE +#undef LL_APPEND +#define LL_APPEND LL_APPEND_VS2008 +#undef LL_DELETE +#define LL_DELETE LL_DELETE_VS2008 +#undef LL_CONCAT /* no LL_CONCAT_VS2008 */ +#undef DL_CONCAT /* no DL_CONCAT_VS2008 */ +#endif +/* end VS2008 replacements */ + +#define LL_FOREACH(head,el) \ + for(el=head;el;el=(el)->next) + +#define LL_FOREACH_SAFE(head,el,tmp) \ + for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) + +#define LL_SEARCH_SCALAR(head,out,field,val) \ +do { \ + LL_FOREACH(head,out) { \ + if ((out)->field == (val)) break; \ + } \ +} while(0) + +#define LL_SEARCH(head,out,elt,cmp) \ +do { \ + LL_FOREACH(head,out) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while(0) + +/****************************************************************************** + * doubly linked list macros (non-circular) * + *****************************************************************************/ +#define DL_PREPEND(head,add) \ +do { \ + (add)->next = head; \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev = (add); \ + } else { \ + (add)->prev = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define DL_APPEND(head,add) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev->next = (add); \ + (head)->prev = (add); \ + (add)->next = NULL; \ + } else { \ + (head)=(add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ +} while (0) + +#define DL_CONCAT(head1,head2) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head2) { \ + if (head1) { \ + _tmp = (head2)->prev; \ + (head2)->prev = (head1)->prev; \ + (head1)->prev->next = (head2); \ + (head1)->prev = _tmp; \ + } else { \ + (head1)=(head2); \ + } \ + } \ +} while (0) + +#define DL_DELETE(head,del) \ +do { \ + assert((del)->prev != NULL); \ + if ((del)->prev == (del)) { \ + (head)=NULL; \ + } else if ((del)==(head)) { \ + (del)->next->prev = (del)->prev; \ + (head) = (del)->next; \ + } else { \ + (del)->prev->next = (del)->next; \ + if ((del)->next) { \ + (del)->next->prev = (del)->prev; \ + } else { \ + (head)->prev = (del)->prev; \ + } \ + } \ +} while (0) + + +#define DL_FOREACH(head,el) \ + for(el=head;el;el=(el)->next) + +/* this version is safe for deleting the elements during iteration */ +#define DL_FOREACH_SAFE(head,el,tmp) \ + for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) + +/* these are identical to their singly-linked list counterparts */ +#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR +#define DL_SEARCH LL_SEARCH + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#define CDL_PREPEND(head,add) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + } \ +(head)=(add); \ +} while (0) + +#define CDL_DELETE(head,del) \ +do { \ + if ( ((head)==(del)) && ((head)->next == (head))) { \ + (head) = 0L; \ + } else { \ + (del)->next->prev = (del)->prev; \ + (del)->prev->next = (del)->next; \ + if ((del) == (head)) (head)=(del)->next; \ + } \ +} while (0) + +#define CDL_FOREACH(head,el) \ + for(el=head;el;el=((el)->next==head ? 0L : (el)->next)) + +#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ + for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL); \ + (el) && ((tmp2)=(el)->next, 1); \ + ((el) = (((el)==(tmp1)) ? 0L : (tmp2)))) + +#define CDL_SEARCH_SCALAR(head,out,field,val) \ +do { \ + CDL_FOREACH(head,out) { \ + if ((out)->field == (val)) break; \ + } \ +} while(0) + +#define CDL_SEARCH(head,out,elt,cmp) \ +do { \ + CDL_FOREACH(head,out) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while(0) + +#endif /* UTLIST_H */ + Index: branches/cparm/i386/util/amlsgn.m =================================================================== --- branches/cparm/i386/util/amlsgn.m (revision 1971) +++ branches/cparm/i386/util/amlsgn.m (revision 1972) @@ -238,8 +238,8 @@ NSMutableData * mem = [[NSMutableData alloc] initWithContentsOfFile : inStr ]; if (!mem) { NSLog(@"Error while opening the file : %@ \n",inStr); - //CFRelease(data); - //data = NULL; + CFRelease(data); + data = NULL; goto out; } ACPI_TABLE_HEADER * head = (ACPI_TABLE_HEADER *)[mem mutableBytes]; @@ -258,8 +258,8 @@ [mem release]; } - //CFRelease(data); - //data = NULL; + CFRelease(data); + data = NULL; goto out; } @@ -290,8 +290,8 @@ NSMutableData * mem = [[NSMutableData alloc] initWithContentsOfFile : inStr ]; if (!mem) { NSLog(@"Error while opening the file : %@\n",inStr); - //CFRelease(data); - //data = NULL; + CFRelease(data); + data = NULL; goto out; } ACPI_TABLE_HEADER * head = (ACPI_TABLE_HEADER *)[mem mutableBytes]; @@ -308,8 +308,8 @@ [mem release]; } - //CFRelease(data); - //data = NULL; + CFRelease(data); + data = NULL; goto out; } Index: branches/cparm/i386/util/random-fbsd.c =================================================================== --- branches/cparm/i386/util/random-fbsd.c (revision 0) +++ branches/cparm/i386/util/random-fbsd.c (revision 1972) @@ -0,0 +1,510 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)random.c 8.2 (Berkeley) 5/19/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/stdlib/random.c,v 1.25 2007/01/09 00:28:10 imp Exp $"); + +/* + * We always compile with __DARWIN_UNIX03 set to one, relying on the fact that + * (for non-LP64) sizeof(int) == sizeof(long) == sizeof(size_t), so that we + * don't have to have two different versions of the prototypes. For LP64, + * we only support the POSIX-compatible prototypes. + */ +#undef __DARWIN_UNIX03 +#define __DARWIN_UNIX03 1 +#include "namespace.h" +#include /* for srandomdev() */ +#include /* for srandomdev() */ +#include +#include +#include +#include /* for srandomdev() */ +#include "un-namespace.h" + +/* + * random.c: + * + * An improved random number generation package. In addition to the standard + * rand()/srand() like interface, this package also has a special state info + * interface. The initstate() routine is called with a seed, an array of + * bytes, and a count of how many bytes are being passed in; this array is + * then initialized to contain information for random number generation with + * that much state information. Good sizes for the amount of state + * information are 32, 64, 128, and 256 bytes. The state can be switched by + * calling the setstate() routine with the same array as was initiallized + * with initstate(). By default, the package runs with 128 bytes of state + * information and generates far better random numbers than a linear + * congruential generator. If the amount of state information is less than + * 32 bytes, a simple linear congruential R.N.G. is used. + * + * Internally, the state information is treated as an array of uint32_t's; the + * zeroeth element of the array is the type of R.N.G. being used (small + * integer); the remainder of the array is the state information for the + * R.N.G. Thus, 32 bytes of state information will give 7 ints worth of + * state information, which will allow a degree seven polynomial. (Note: + * the zeroeth word of state information also has some other information + * stored in it -- see setstate() for details). + * + * The random number generation technique is a linear feedback shift register + * approach, employing trinomials (since there are fewer terms to sum up that + * way). In this approach, the least significant bit of all the numbers in + * the state table will act as a linear feedback shift register, and will + * have period 2^deg - 1 (where deg is the degree of the polynomial being + * used, assuming that the polynomial is irreducible and primitive). The + * higher order bits will have longer periods, since their values are also + * influenced by pseudo-random carries out of the lower bits. The total + * period of the generator is approximately deg*(2**deg - 1); thus doubling + * the amount of state information has a vast influence on the period of the + * generator. Note: the deg*(2**deg - 1) is an approximation only good for + * large deg, when the period of the shift is the dominant factor. + * With deg equal to seven, the period is actually much longer than the + * 7*(2**7 - 1) predicted by this formula. + * + * Modified 28 December 1994 by Jacob S. Rosenberg. + * The following changes have been made: + * All references to the type u_int have been changed to unsigned long. + * All references to type int have been changed to type long. Other + * cleanups have been made as well. A warning for both initstate and + * setstate has been inserted to the effect that on Sparc platforms + * the 'arg_state' variable must be forced to begin on word boundaries. + * This can be easily done by casting a long integer array to char *. + * The overall logic has been left STRICTLY alone. This software was + * tested on both a VAX and Sun SpacsStation with exactly the same + * results. The new version and the original give IDENTICAL results. + * The new version is somewhat faster than the original. As the + * documentation says: "By default, the package runs with 128 bytes of + * state information and generates far better random numbers than a linear + * congruential generator. If the amount of state information is less than + * 32 bytes, a simple linear congruential R.N.G. is used." For a buffer of + * 128 bytes, this new version runs about 19 percent faster and for a 16 + * byte buffer it is about 5 percent faster. + */ + +/* + * For each of the currently supported random number generators, we have a + * break value on the amount of state information (you need at least this + * many bytes of state info to support this random number generator), a degree + * for the polynomial (actually a trinomial) that the R.N.G. is based on, and + * the separation between the two lower order coefficients of the trinomial. + */ +#define TYPE_0 0 /* linear congruential */ +#define BREAK_0 8 +#define DEG_0 0 +#define SEP_0 0 + +#define TYPE_1 1 /* x**7 + x**3 + 1 */ +#define BREAK_1 32 +#define DEG_1 7 +#define SEP_1 3 + +#define TYPE_2 2 /* x**15 + x + 1 */ +#define BREAK_2 64 +#define DEG_2 15 +#define SEP_2 1 + +#define TYPE_3 3 /* x**31 + x**3 + 1 */ +#define BREAK_3 128 +#define DEG_3 31 +#define SEP_3 3 + +#define TYPE_4 4 /* x**63 + x + 1 */ +#define BREAK_4 256 +#define DEG_4 63 +#define SEP_4 1 + +/* + * Array versions of the above information to make code run faster -- + * relies on fact that TYPE_i == i. + */ +#define MAX_TYPES 5 /* max number of types above */ + +#ifdef USE_WEAK_SEEDING +#define NSHUFF 0 +#else /* !USE_WEAK_SEEDING */ +#define NSHUFF 50 /* to drop some "seed -> 1st value" linearity */ +#endif /* !USE_WEAK_SEEDING */ + +static const int degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 }; +static const int seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 }; + +/* + * Initially, everything is set up as if from: + * + * initstate(1, randtbl, 128); + * + * Note that this initialization takes advantage of the fact that srandom() + * advances the front and rear pointers 10*rand_deg times, and hence the + * rear pointer which starts at 0 will also end up at zero; thus the zeroeth + * element of the state information, which contains info about the current + * position of the rear pointer is just + * + * MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3. + */ + +static uint32_t randtbl[DEG_3 + 1] = { + TYPE_3, +#ifdef USE_WEAK_SEEDING + /* Historic implementation compatibility */ + /* The random sequences do not vary much with the seed */ + 0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5, + 0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd, + 0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88, + 0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc, + 0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b, + 0x27fb47b9, +#else /* !USE_WEAK_SEEDING */ + 0x991539b1, 0x16a5bce3, 0x6774a4cd, 0x3e01511e, 0x4e508aaa, 0x61048c05, + 0xf5500617, 0x846b7115, 0x6a19892c, 0x896a97af, 0xdb48f936, 0x14898454, + 0x37ffd106, 0xb58bff9c, 0x59e17104, 0xcf918a49, 0x09378c83, 0x52c7a471, + 0x8d293ea9, 0x1f4fc301, 0xc3db71be, 0x39b44e1c, 0xf8a44ef9, 0x4c8b80b1, + 0x19edc328, 0x87bf4bdd, 0xc9b240e5, 0xe9ee4b1b, 0x4382aee7, 0x535b6b41, + 0xf3bec5da +#endif /* !USE_WEAK_SEEDING */ +}; + +/* + * fptr and rptr are two pointers into the state info, a front and a rear + * pointer. These two pointers are always rand_sep places aparts, as they + * cycle cyclically through the state information. (Yes, this does mean we + * could get away with just one pointer, but the code for random() is more + * efficient this way). The pointers are left positioned as they would be + * from the call + * + * initstate(1, randtbl, 128); + * + * (The position of the rear pointer, rptr, is really 0 (as explained above + * in the initialization of randtbl) because the state table pointer is set + * to point to randtbl[1] (as explained below). + */ +static uint32_t *fptr = &randtbl[SEP_3 + 1]; +static uint32_t *rptr = &randtbl[1]; + +/* + * The following things are the pointer to the state information table, the + * type of the current generator, the degree of the current polynomial being + * used, and the separation between the two pointers. Note that for efficiency + * of random(), we remember the first location of the state information, not + * the zeroeth. Hence it is valid to access state[-1], which is used to + * store the type of the R.N.G. Also, we remember the last location, since + * this is more efficient than indexing every time to find the address of + * the last element to see if the front and rear pointers have wrapped. + */ +static uint32_t *state = &randtbl[1]; +static int rand_type = TYPE_3; +static int rand_deg = DEG_3; +static int rand_sep = SEP_3; +static uint32_t *end_ptr = &randtbl[DEG_3 + 1]; + +static inline uint32_t good_rand(int32_t) __attribute__((always_inline)); + +static inline uint32_t good_rand (x) +int32_t x; +{ +#ifdef USE_WEAK_SEEDING + /* + * Historic implementation compatibility. + * The random sequences do not vary much with the seed, + * even with overflowing. + */ + return (1103515245 * x + 12345); +#else /* !USE_WEAK_SEEDING */ + /* + * Compute x = (7^5 * x) mod (2^31 - 1) + * wihout overflowing 31 bits: + * (2^31 - 1) = 127773 * (7^5) + 2836 + * From "Random number generators: good ones are hard to find", + * Park and Miller, Communications of the ACM, vol. 31, no. 10, + * October 1988, p. 1195. + */ + int32_t hi, lo; + + /* Can't be initialized with 0, so use another value. */ + if (x == 0) + x = 123459876; + hi = x / 127773; + lo = x % 127773; + x = 16807 * lo - 2836 * hi; + if (x < 0) + x += 0x7fffffff; + return (x); +#endif /* !USE_WEAK_SEEDING */ +} + +/* + * srandom: + * + * Initialize the random number generator based on the given seed. If the + * type is the trivial no-state-information type, just remember the seed. + * Otherwise, initializes state[] based on the given "seed" via a linear + * congruential generator. Then, the pointers are set to known locations + * that are exactly rand_sep places apart. Lastly, it cycles the state + * information a given number of times to get rid of any initial dependencies + * introduced by the L.C.R.N.G. Note that the initialization of randtbl[] + * for default usage relies on values produced by this routine. + */ +void +srandom(x) +unsigned x; +{ + int i, lim; + + state[0] = (uint32_t)x; + if (rand_type == TYPE_0) + lim = NSHUFF; + else { + for (i = 1; i < rand_deg; i++) + state[i] = good_rand(state[i - 1]); + fptr = &state[rand_sep]; + rptr = &state[0]; + lim = 10 * rand_deg; + } + for (i = 0; i < lim; i++) + (void)random(); +} + +/* + * srandomdev: + * + * Many programs choose the seed value in a totally predictable manner. + * This often causes problems. We seed the generator using the much more + * secure random(4) interface. Note that this particular seeding + * procedure can generate states which are impossible to reproduce by + * calling srandom() with any value, since the succeeding terms in the + * state buffer are no longer derived from the LC algorithm applied to + * a fixed seed. + */ +void +srandomdev() +{ + int fd, done; + size_t len; + + if (rand_type == TYPE_0) + len = sizeof state[0]; + else + len = rand_deg * sizeof state[0]; + + done = 0; + fd = _open("/dev/random", O_RDONLY, 0); + if (fd >= 0) { + if (_read(fd, (void *) state, len) == (ssize_t) len) + done = 1; + _close(fd); + } + + if (!done) { + struct timeval tv; + unsigned long junk; + + gettimeofday(&tv, NULL); + srandom((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec ^ junk); + return; + } + + if (rand_type != TYPE_0) { + fptr = &state[rand_sep]; + rptr = &state[0]; + } +} + +/* + * initstate: + * + * Initialize the state information in the given array of n bytes for future + * random number generation. Based on the number of bytes we are given, and + * the break values for the different R.N.G.'s, we choose the best (largest) + * one we can and set things up for it. srandom() is then called to + * initialize the state information. + * + * Note that on return from srandom(), we set state[-1] to be the type + * multiplexed with the current value of the rear pointer; this is so + * successive calls to initstate() won't lose this information and will be + * able to restart with setstate(). + * + * Note: the first thing we do is save the current state, if any, just like + * setstate() so that it doesn't matter when initstate is called. + * + * Returns a pointer to the old state. + * + * Note: The Sparc platform requires that arg_state begin on an int + * word boundary; otherwise a bus error will occur. Even so, lint will + * complain about mis-alignment, but you should disregard these messages. + */ +char * +initstate(seed, arg_state, n) +unsigned seed; /* seed for R.N.G. */ +char *arg_state; /* pointer to state array */ +size_t n; /* # bytes of state info */ +{ + char *ostate = (char *)(&state[-1]); + uint32_t *int_arg_state = (uint32_t *)arg_state; + + if (rand_type == TYPE_0) + state[-1] = rand_type; + else + state[-1] = MAX_TYPES * (rptr - state) + rand_type; + if (n < BREAK_0) { + (void)fprintf(stderr, + "random: not enough state (%ld bytes); ignored.\n", n); + return(0); + } + if (n < BREAK_1) { + rand_type = TYPE_0; + rand_deg = DEG_0; + rand_sep = SEP_0; + } else if (n < BREAK_2) { + rand_type = TYPE_1; + rand_deg = DEG_1; + rand_sep = SEP_1; + } else if (n < BREAK_3) { + rand_type = TYPE_2; + rand_deg = DEG_2; + rand_sep = SEP_2; + } else if (n < BREAK_4) { + rand_type = TYPE_3; + rand_deg = DEG_3; + rand_sep = SEP_3; + } else { + rand_type = TYPE_4; + rand_deg = DEG_4; + rand_sep = SEP_4; + } + state = int_arg_state + 1; /* first location */ + end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */ + srandom(seed); + if (rand_type == TYPE_0) + int_arg_state[0] = rand_type; + else + int_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type; + return(ostate); +} + +/* + * setstate: + * + * Restore the state from the given state array. + * + * Note: it is important that we also remember the locations of the pointers + * in the current state information, and restore the locations of the pointers + * from the old state information. This is done by multiplexing the pointer + * location into the zeroeth word of the state information. + * + * Note that due to the order in which things are done, it is OK to call + * setstate() with the same state as the current state. + * + * Returns a pointer to the old state information. + * + * Note: The Sparc platform requires that arg_state begin on an int + * word boundary; otherwise a bus error will occur. Even so, lint will + * complain about mis-alignment, but you should disregard these messages. + */ +char * +setstate(arg_state) +const char *arg_state; /* pointer to state array */ +{ + uint32_t *new_state = (uint32_t *)arg_state; + uint32_t type = new_state[0] % MAX_TYPES; + uint32_t rear = new_state[0] / MAX_TYPES; + char *ostate = (char *)(&state[-1]); + + if (rand_type == TYPE_0) + state[-1] = rand_type; + else + state[-1] = MAX_TYPES * (rptr - state) + rand_type; + switch(type) { + case TYPE_0: + case TYPE_1: + case TYPE_2: + case TYPE_3: + case TYPE_4: + rand_type = type; + rand_deg = degrees[type]; + rand_sep = seps[type]; + break; + default: + (void)fprintf(stderr, + "random: state info corrupted; not changed.\n"); + } + state = new_state + 1; + if (rand_type != TYPE_0) { + rptr = &state[rear]; + fptr = &state[(rear + rand_sep) % rand_deg]; + } + end_ptr = &state[rand_deg]; /* set end_ptr too */ + return(ostate); +} + +/* + * random: + * + * If we are using the trivial TYPE_0 R.N.G., just do the old linear + * congruential bit. Otherwise, we do our fancy trinomial stuff, which is + * the same in all the other cases due to all the global variables that have + * been set up. The basic operation is to add the number at the rear pointer + * into the one at the front pointer. Then both pointers are advanced to + * the next location cyclically in the table. The value returned is the sum + * generated, reduced to 31 bits by throwing away the "least random" low bit. + * + * Note: the code takes advantage of the fact that both the front and + * rear pointers can't wrap on the same call by not testing the rear + * pointer if the front one has wrapped. + * + * Returns a 31-bit random number. + */ +long +random() +{ + uint32_t i; + uint32_t *f, *r; + + if (rand_type == TYPE_0) { + i = state[0]; + state[0] = i = (good_rand(i)) & 0x7fffffff; + } else { + /* + * Use local variables rather than static variables for speed. + */ + f = fptr; r = rptr; + *f += *r; + i = (*f >> 1) & 0x7fffffff; /* chucking least random bit */ + if (++f >= end_ptr) { + f = state; + ++r; + } + else if (++r >= end_ptr) { + r = state; + } + + fptr = f; rptr = r; + } + return((long)i); +} Index: branches/cparm/xcode3_sym.zip =================================================================== Cannot display: file marked as a binary type. svn:mime-type = application/octet-stream